@agentica/chat 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1 +1,165 @@
1
- # WrtnLabs POC Agent Chat Applications
1
+ # Agentica, AI Function Calling Framework
2
+
3
+ <!-- https://github.com/user-attachments/assets/5326cc59-5129-470d-abcb-c3f458b5c488 -->
4
+
5
+ ![Logo](https://wrtnlabs.io/agentica/og.jpg?refresh)
6
+
7
+ [![GitHub License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/wrtnlabs/agentica/blob/master/LICENSE)
8
+ [![NPM Version](https://img.shields.io/npm/v/@agentica/core.svg)](https://www.npmjs.com/package/@agentica/core)
9
+ [![NPM Downloads](https://img.shields.io/npm/dm/@agentica/core.svg)](https://www.npmjs.com/package/@agentica/core)
10
+ [![Build Status](https://github.com/wrtnlabs/agentica/workflows/build/badge.svg)](https://github.com/wrtnlabs/agentica/actions?query=workflow%3Abuild)
11
+ [![Guide Documents](https://img.shields.io/badge/Guide-Documents-forestgreen)](https://wrtnlabs.io/agentica/)
12
+ [![Discord Badge](https://dcbadge.limes.pink/api/server/https://discord.gg/aMhRmzkqCx?style=flat)](https://discord.gg/aMhRmzkqCx)
13
+
14
+ Agentic AI framework specialized in AI Function Calling.
15
+
16
+ Don't be afraid of AI agent development. Just list functions from three protocols below. This is everything you should do for AI agent development.
17
+
18
+ - TypeScript Class
19
+ - Swagger/OpenAPI Document
20
+ - MCP (Model Context Protocol) Server
21
+
22
+ Wanna make an e-commerce agent? Bring in e-commerce functions. Need a newspaper agent? Get API functions from the newspaper company. Just prepare any functions that you need, then it becomes an AI agent.
23
+
24
+ Are you a TypeScript developer? Then you're already an AI developer. Familiar with backend development? You're already well-versed in AI development. Anyone who can make functions can make AI agents.
25
+
26
+ <!-- eslint-skip -->
27
+
28
+ ```typescript
29
+ import { Agentica, assertHttpLlmApplication } from "@agentica/core";
30
+ import OpenAI from "openai";
31
+ import typia from "typia";
32
+
33
+ import { MobileFileSystem } from "./services/MobileFileSystem";
34
+
35
+ const agent = new Agentica({
36
+ vendor: {
37
+ api: new OpenAI({ apiKey: "********" }),
38
+ model: "gpt-4o-mini",
39
+ },
40
+ controllers: [
41
+ // functions from TypeScript class
42
+ {
43
+ protocol: "http",
44
+ application: typia.llm.application<MobileFileSystem, "chatgpt">(),
45
+ execute: new MobileFileSystem(),
46
+ },
47
+ // functions from Swagger/OpenAPI
48
+ {
49
+ protocol: "http",
50
+ application: assertHttpLlmApplication({
51
+ model: "chatgpt",
52
+ document: await fetch(
53
+ "https://shopping-be.wrtn.ai/editor/swagger.json",
54
+ ).then(r => r.json()),
55
+ }),
56
+ connection: {
57
+ host: "https://shopping-be.wrtn.ai",
58
+ headers: { Authorization: "Bearer ********" },
59
+ },
60
+ },
61
+ ],
62
+ });
63
+ await agent.conversate("I wanna buy MacBook Pro");
64
+ ```
65
+
66
+ ## 📦 Setup
67
+
68
+ ```bash
69
+ $ npx agentica start <directory>
70
+
71
+ ----------------------------------------
72
+ Agentica Setup Wizard
73
+ ----------------------------------------
74
+ ? Package Manager (use arrow keys)
75
+ > npm
76
+ pnpm
77
+ yarn (berry is not supported)
78
+ ? Project Type
79
+ NodeJS Agent Server
80
+ > NestJS Agent Server
81
+ React Client Application
82
+ Standalone Application
83
+ ? Embedded Controllers (multi-selectable)
84
+ (none)
85
+ Google Calendar
86
+ Google News
87
+ > Github
88
+ Reddit
89
+ Slack
90
+ ...
91
+ ```
92
+
93
+ The setup wizard helps you create a new project tailored to your needs.
94
+
95
+ For reference, when selecting a project type, any option other than "Standalone Application" will implement the [WebSocket Protocol](https://wrtnlabs.io/agentica/docs/websocket/) for client-server communication.
96
+
97
+ For comprehensive setup instructions, visit our [Getting Started](https://wrtnlabs.io/agentica/docs/) guide.
98
+
99
+ ## 💻 Playground
100
+
101
+ Experience Agentica firsthand through our [interactive playground](https://wrtnlabs.io/agentica/playground) before installing.
102
+
103
+ Our demonstrations showcase the power and simplicity of Agentica's function calling capabilities across different integration methods.
104
+
105
+ - [TypeScript Class](https://wrtnlabs.io/agentica/playground/bbs)
106
+ - [Swagger/OpenAPI Document](https://wrtnlabs.io/agentica/playground/swagger)
107
+ - [Enterprise E-commerce Agent](https://wrtnlabs.io/agentica/playground/shopping)
108
+
109
+ <!--
110
+ @todo this section would be changed after making tutorial playground
111
+ -->
112
+
113
+ ## 📚 Documentation Resources
114
+
115
+ Find comprehensive resources at our [official website](https://wrtnlabs.io/agentica).
116
+
117
+ - [Home](https://wrtnlabs.io/agentica)
118
+ - [Guide Documents](https://wrtnlabs.io/agentica/docs)
119
+ - [Tutorial](https://wrtnlabs.io/agentica/tutorial)
120
+ - [API Documents](https://wrtnlabs.io/agentica/api)
121
+ - [Youtube](https://www.youtube.com/@wrtnlabs)
122
+ - [Paper](https://wrtnlabs.io/agentica/paper)
123
+
124
+ ## 🌟 Why Agentica?
125
+
126
+ ```mermaid
127
+ flowchart
128
+ subgraph "JSON Schema Specification"
129
+ schemav4("JSON Schema v4 ~ v7") --upgrades--> emended[["OpenAPI v3.1 (emended)"]]
130
+ schema2910("JSON Schema 2019-03") --upgrades--> emended
131
+ schema2020("JSON Schema 2020-12") --emends--> emended
132
+ end
133
+ subgraph "Agentica"
134
+ emended --"Artificial Intelligence"--> fc{{"AI Function Calling"}}
135
+ fc --"OpenAI"--> chatgpt("ChatGPT")
136
+ fc --"Google"--> gemini("Gemini")
137
+ fc --"Anthropic"--> claude("Claude")
138
+ fc --"High-Flyer"--> deepseek("DeepSeek")
139
+ fc --"Meta"--> llama("Llama")
140
+ chatgpt --"3.1"--> custom(["Custom JSON Schema"])
141
+ gemini --"3.0"--> custom(["Custom JSON Schema"])
142
+ claude --"3.1"--> standard(["Standard JSON Schema"])
143
+ deepseek --"3.1"--> standard
144
+ llama --"3.1"--> standard
145
+ end
146
+ ```
147
+
148
+ Agentica enhances AI function calling by the following strategies:
149
+
150
+ - [**Compiler Driven Development**](https://wrtnlabs.io/agentica/docs/concepts/compiler-driven-development): constructs function calling schema automatically by compiler skills without hand-writing.
151
+ - [**JSON Schema Conversion**](https://wrtnlabs.io/agentica/docs/core/vendor/#schema-specification): automatically handles specification differences between LLM vendors, ensuring seamless integration regardless of your chosen AI model.
152
+ - [**Validation Feedback**](https://wrtnlabs.io/agentica/docs/concepts/function-calling#validation-feedback): detects and corrects AI mistakes in argument composition, dramatically reducing errors and improving reliability.
153
+ - [**Selector Agent**](https://wrtnlabs.io/agentica/docs/concepts/function-calling#orchestration-strategy): filtering candidate functions to minimize context usage, optimize performance, and reduce token consumption.
154
+
155
+ Thanks to these innovations, Agentica makes AI function calling easier, safer, and more accurate than before. Development becomes more intuitive since you only need to prepare functions relevant to your specific use case, and scaling your agent's capabilities is as simple as adding or removing functions.
156
+
157
+ In 2023, when OpenAI announced function calling, many predicted that function calling-driven AI development would become the mainstream. However, in reality, due to the difficulty and instability of function calling, the trend in AI development became agent workflow. Agent workflow, which is inflexible and must be created for specific purposes, has conquered the AI agent ecosystem.
158
+ By the way, as Agentica has resolved the difficulty and instability problems of function calling, the time has come to embrace function-driven AI development once again.
159
+
160
+ | Type | Workflow | Vanilla Function Calling | Agentica Function Calling |
161
+ | ----------- | ------------- | ------------------------ | ------------------------- |
162
+ | Purpose | ❌ Specific | 🟢 General | 🟢 General |
163
+ | Difficulty | ❌ Difficult | ❌ Difficult | 🟢 Easy |
164
+ | Stability | 🟢 Stable | ❌ Unstable | 🟢 Stable |
165
+ | Flexibility | ❌ Inflexible | 🟢 Flexible | 🟢 Flexible |
@@ -3196,7 +3196,7 @@ Also, if you A.I. agent can't specify a specific function to call due to lack
3196
3196
  of specificity or homogeneity of candidate functions, just assign all of them
3197
3197
  by in the\` functions\` property\` too. Instead, when you A.I. agent can specify
3198
3198
  a specific function to call, the others would be eliminated.`,validate:(()=>{const o=G=>Array.isArray(G.functions)&&G.functions.every(J=>typeof J=="object"&&J!==null&&h(J)),h=G=>typeof G.reason=="string"&&typeof G.name=="string",b=(G,J,U=!0)=>[(Array.isArray(G.functions)||B(U,{path:J+".functions",expected:"Array<___IChatFunctionReference>",value:G.functions}))&&G.functions.map((nt,et)=>(typeof nt=="object"&&nt!==null||B(U,{path:J+".functions["+et+"]",expected:"___IChatFunctionReference",value:nt}))&&k(nt,J+".functions["+et+"]",U)||B(U,{path:J+".functions["+et+"]",expected:"___IChatFunctionReference",value:nt})).every(nt=>nt)||B(U,{path:J+".functions",expected:"Array<___IChatFunctionReference>",value:G.functions})].every(nt=>nt),k=(G,J,U=!0)=>[typeof G.reason=="string"||B(U,{path:J+".reason",expected:"string",value:G.reason}),typeof G.name=="string"||B(U,{path:J+".name",expected:"string",value:G.name})].every(nt=>nt),O=G=>typeof G=="object"&&G!==null&&o(G);let P,B;return G=>{if(O(G)===!1){P=[],B=rP(P),((U,nt,et=!0)=>(typeof U=="object"&&U!==null||B(!0,{path:nt+"",expected:"__IChatFunctionReference.IProps",value:U}))&&b(U,nt+"",!0)||B(!0,{path:nt+"",expected:"__IChatFunctionReference.IProps",value:U}))(G,"$input",!0);const J=P.length===0;return J?{success:J,data:G}:{success:J,errors:P,data:G}}return{success:!0,data:G}}})()}]};async function gDn(o){var P;if(o.operations.divided===void 0)return Smt(o,o.operations.array,0);const h=o.operations.divided.map(()=>[]),b=[],k=await Promise.all(o.operations.divided.map(async(B,G)=>Smt({...o,stack:h[G],dispatch:async J=>{b.push(J)}},B,0)));if(h.every(B=>B.length===0))return k[0];if((((P=o.config)==null?void 0:P.eliticism)??nT.ELITICISM)===!0)return Smt(o,h.flat().map(B=>o.operations.group.get(B.operation.controller.name).get(B.operation.function.name)),0);const O=sbt({id:njt(),selections:[]});for(const B of b)B.type==="select"&&(O.selections.push(B.selection),await R7e(o,{name:B.selection.operation.name,reason:B.selection.reason}));return[O]}async function Smt(o,h,b,k){var J,U,nt,et;const O=await o.request("select",{messages:[{role:"system",content:qj.write(o.config)},{role:"assistant",tool_calls:[{type:"function",id:"getApiFunctions",function:{name:"getApiFunctions",arguments:JSON.stringify({})}}]},{role:"tool",tool_call_id:"getApiFunctions",content:JSON.stringify(h.map(tt=>({name:tt.name,description:tt.function.description,...tt.protocol==="http"?{method:tt.function.method,path:tt.function.path,tags:tt.function.tags}:{}})))},...o.histories.map(Gj).flat(),{role:"user",content:o.prompt.text},{role:"system",content:((nt=(U=(J=o.config)==null?void 0:J.systemPrompt)==null?void 0:U.select)==null?void 0:nt.call(U,o.histories))??nP.SELECT},...mDn(k??[])],tools:pDn.functions.map(tt=>({type:"function",function:{name:tt.name,description:tt.description,parameters:tt.parameters}})),tool_choice:"auto",parallel_tool_calls:!1}),P=await Z8.readAll(O),B=p6.merge(P);if(b++<(((et=o.config)==null?void 0:et.retry)??nT.RETRY)){const tt=[];for(const st of B.choices)for(const it of st.message.tool_calls??[]){if(it.function.name!=="selectFunctions")continue;const At=JSON.parse(it.function.arguments),Dt=(()=>{const Ot=Kn=>Array.isArray(Kn.functions)&&Kn.functions.every(Bn=>typeof Bn=="object"&&Bn!==null&&oe(Bn)),oe=Kn=>typeof Kn.reason=="string"&&typeof Kn.name=="string",re=(Kn,Bn,Gn=!0)=>[(Array.isArray(Kn.functions)||Ln(Gn,{path:Bn+".functions",expected:"Array<___IChatFunctionReference>",value:Kn.functions}))&&Kn.functions.map((Vn,lr)=>(typeof Vn=="object"&&Vn!==null||Ln(Gn,{path:Bn+".functions["+lr+"]",expected:"___IChatFunctionReference",value:Vn}))&&Pe(Vn,Bn+".functions["+lr+"]",Gn)||Ln(Gn,{path:Bn+".functions["+lr+"]",expected:"___IChatFunctionReference",value:Vn})).every(Vn=>Vn)||Ln(Gn,{path:Bn+".functions",expected:"Array<___IChatFunctionReference>",value:Kn.functions})].every(Vn=>Vn),Pe=(Kn,Bn,Gn=!0)=>[typeof Kn.reason=="string"||Ln(Gn,{path:Bn+".reason",expected:"string",value:Kn.reason}),typeof Kn.name=="string"||Ln(Gn,{path:Bn+".name",expected:"string",value:Kn.name})].every(Vn=>Vn),mn=Kn=>typeof Kn=="object"&&Kn!==null&&Ot(Kn);let ge,Ln;return Kn=>{if(mn(Kn)===!1){ge=[],Ln=rP(ge),((Gn,Vn,lr=!0)=>(typeof Gn=="object"&&Gn!==null||Ln(!0,{path:Vn+"",expected:"__IChatFunctionReference.IProps",value:Gn}))&&re(Gn,Vn+"",!0)||Ln(!0,{path:Vn+"",expected:"__IChatFunctionReference.IProps",value:Gn}))(Kn,"$input",!0);const Bn=ge.length===0;return Bn?{success:Bn,data:Kn}:{success:Bn,errors:ge,data:Kn}}return{success:!0,data:Kn}}})()(At);Dt.success===!1&&tt.push({id:it.id,name:it.function.name,validation:Dt})}if(tt.length>0)return Smt(o,h,b,tt)}const G=[];for(const tt of B.choices){if(tt.message.tool_calls!=null)for(const st of tt.message.tool_calls){if(st.type!=="function"||st.function.name!=="selectFunctions")continue;const it=(()=>{const Dt=re=>Array.isArray(re.functions)&&re.functions.every(Pe=>typeof Pe=="object"&&Pe!==null&&Ot(Pe)),Ot=re=>typeof re.reason=="string"&&typeof re.name=="string",oe=re=>typeof re=="object"&&re!==null&&Dt(re);return re=>(re=JSON.parse(re),oe(re)?re:null)})()(st.function.arguments);if(it===null)continue;const At=sbt({id:st.id,selections:[]});for(const Dt of it.functions){const Ot=await R7e(o,Dt);Ot!==null&&At.selections.push(Wj({operation:Ot,reason:Dt.reason}))}At.selections.length!==0&&G.push(At)}if(tt.message.role==="assistant"&&tt.message.content!=null&&tt.message.content.length!==0){const st=LX({role:"assistant",text:tt.message.content});G.push(st),o.dispatch(ubt({role:"assistant",stream:ajt(st.text),join:async()=>Promise.resolve(st.text),done:()=>!0,get:()=>st.text})).catch(()=>{})}}return G}function mDn(o){return o.map(h=>[{role:"assistant",tool_calls:[{type:"function",id:h.id,function:{name:h.name,arguments:JSON.stringify(h.validation.data)}}]},{role:"tool",content:JSON.stringify(h.validation.errors),tool_call_id:h.id},{role:"system",content:["You A.I. assistant has composed wrong typed arguments.","","Correct it at the next function calling."].join(`
3199
- `)}]).flat()}function bDn(o){return async h=>{const b=[];if(h.ready()===!1){if((o==null?void 0:o.initialize)===null)await h.initialize();else if(b.push(...await((o==null?void 0:o.initialize)??dDn)(h)),h.ready()===!1)return b}if(h.stack.length!==0&&b.push(...await((o==null?void 0:o.cancel)??cDn)(h)),b.push(...await((o==null?void 0:o.select)??gDn)(h)),h.stack.length===0)return b;for(;;){const k=await((o==null?void 0:o.call)??ZMn)(h,h.stack.map(P=>P.operation));b.push(...k);const O=k.filter(P=>P.type==="execute");if(b.push(...await((o==null?void 0:o.describe)??fDn)(h,O)),O.length===0||h.stack.length===0)break}return b}}function yDn(o){if(o.history.type==="text")return B7e({history:o.history});if(o.history.type==="select")return j7e({operations:o.operations,history:o.history});if(o.history.type==="cancel")return F7e({operations:o.operations,history:o.history});if(o.history.type==="execute")return sjt({operations:o.operations,history:o.history});if(o.history.type==="describe")return $7e({operations:o.operations,history:o.history});throw new Error("Invalid prompt type.")}function B7e(o){return LX(o.history)}function j7e(o){return sbt({id:o.history.id,selections:o.history.selections.map(h=>Wj({operation:cjt({operations:o.operations,input:h.operation}),reason:h.reason}))})}function F7e(o){return cbt({id:o.history.id,selections:o.history.selections.map(h=>Wj({operation:cjt({operations:o.operations,input:h.operation}),reason:h.reason}))})}function sjt(o){return eT({id:o.history.id,operation:cjt({operations:o.operations,input:o.history.operation}),arguments:o.history.arguments,value:o.history.value})}function $7e(o){return S7e({text:o.history.text,executes:o.history.executes.map(h=>sjt({operations:o.operations,history:h}))})}function cjt(o){var b;const h=(b=o.operations.get(o.input.controller))==null?void 0:b.get(o.input.function);if(h===void 0)throw new Error(`No operation found: (controller: ${o.input.controller}, function: ${o.input.function})`);return h}const wDn={transform:yDn,transformText:B7e,transformSelect:j7e,transformCancel:F7e,transformExecute:sjt,transformDescribe:$7e};class H7e{constructor(h){var b,k;this.props=h,this.operations_=pLn.compose({controllers:h.controllers,config:h.config}),this.stack_=[],this.listeners_=new Map,this.histories_=(h.histories??[]).map(O=>wDn.transform({operations:this.operations_.group,history:O})),this.token_usage_=hX.zero(),this.ready_=!1,this.executor_=typeof((b=h.config)==null?void 0:b.executor)=="function"?h.config.executor:bDn(((k=h.config)==null?void 0:k.executor)??null)}clone(){var h;return new H7e({...this.props,histories:(h=this.props.histories)==null?void 0:h.slice()})}async conversate(h){const b=LX({role:"user",text:h});this.dispatch(ubt({role:"user",stream:ajt(h),done:()=>!0,get:()=>h,join:async()=>Promise.resolve(h)})).catch(()=>{});const k=await this.executor_(this.getContext({prompt:b,usage:this.token_usage_}));return this.histories_.push(b,...k),[b,...k]}getConfig(){return this.props.config}getVendor(){return this.props.vendor}getControllers(){return this.props.controllers}getOperations(){return this.operations_.array}getHistories(){return this.histories_}getTokenUsage(){return this.token_usage_}getContext(h){const b=async k=>this.dispatch(k);return{operations:this.operations_,config:this.props.config,histories:this.histories_,stack:this.stack_,ready:()=>this.ready_,prompt:h.prompt,dispatch:async k=>this.dispatch(k),request:async(k,O)=>{const P=SLn({source:k,body:{...O,model:this.props.vendor.model,stream:!0,stream_options:{include_usage:!0}},options:this.props.vendor.options});await b(P);const B=await this.props.vendor.api.chat.completions.create(P.body,P.options),[G,J]=Z8.transform(B.toReadableStream(),st=>p6.transformCompletionChunk(st)).tee(),[U,nt]=J.tee();(async()=>{const st=U.getReader();for(;;){const it=await st.read();if(it.done)break;it.value.usage!=null&&mLn.aggregate({kind:k,completionUsage:it.value.usage,usage:h.usage})}})().catch(()=>{});const[et,tt]=G.tee();return await b({type:"response",source:k,stream:lbt(et.getReader()),body:P.body,options:P.options,join:async()=>{const st=await Z8.readAll(tt);return p6.merge(st)}}),nt},initialize:async()=>{this.ready_=!0,await b(xLn())}}}on(h,b){return T7e(this.listeners_,h,()=>new Set).add(b),this}off(h,b){const k=this.listeners_.get(h);return k!==void 0&&(k.delete(b),k.size===0&&this.listeners_.delete(h)),this}async dispatch(h){const b=this.listeners_.get(h.type);b!==void 0&&await Promise.all(Array.from(b).map(async k=>{try{await k(h)}catch{}}))}}const dBt="RFC3986",pBt={RFC1738:o=>String(o).replace(/%20/g,"+"),RFC3986:o=>String(o)},vDn="RFC1738",xDn=Array.isArray,o6=(()=>{const o=[];for(let h=0;h<256;++h)o.push("%"+((h<16?"0":"")+h.toString(16)).toUpperCase());return o})(),iRt=1024,kDn=(o,h,b,k,O)=>{if(o.length===0)return o;let P=o;if(typeof o=="symbol"?P=Symbol.prototype.toString.call(o):typeof o!="string"&&(P=String(o)),b==="iso-8859-1")return escape(P).replace(/%u[0-9a-f]{4}/gi,function(G){return"%26%23"+parseInt(G.slice(2),16)+"%3B"});let B="";for(let G=0;G<P.length;G+=iRt){const J=P.length>=iRt?P.slice(G,G+iRt):P,U=[];for(let nt=0;nt<J.length;++nt){let et=J.charCodeAt(nt);if(et===45||et===46||et===95||et===126||et>=48&&et<=57||et>=65&&et<=90||et>=97&&et<=122||O===vDn&&(et===40||et===41)){U[U.length]=J.charAt(nt);continue}if(et<128){U[U.length]=o6[et];continue}if(et<2048){U[U.length]=o6[192|et>>6]+o6[128|et&63];continue}if(et<55296||et>=57344){U[U.length]=o6[224|et>>12]+o6[128|et>>6&63]+o6[128|et&63];continue}nt+=1,et=65536+((et&1023)<<10|J.charCodeAt(nt)&1023),U[U.length]=o6[240|et>>18]+o6[128|et>>12&63]+o6[128|et>>6&63]+o6[128|et&63]}B+=U.join("")}return B};function _Dn(o){return!o||typeof o!="object"?!1:!!(o.constructor&&o.constructor.isBuffer&&o.constructor.isBuffer(o))}function X8e(o,h){if(xDn(o)){const b=[];for(let k=0;k<o.length;k+=1)b.push(h(o[k]));return b}return h(o)}const EDn=Object.prototype.hasOwnProperty,z7e={brackets(o){return String(o)+"[]"},comma:"comma",indices(o,h){return String(o)+"["+h+"]"},repeat(o){return String(o)}},c6=Array.isArray,TDn=Array.prototype.push,U7e=function(o,h){TDn.apply(o,c6(h)?h:[h])},SDn=Date.prototype.toISOString,Xp={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:kDn,encodeValuesOnly:!1,format:dBt,formatter:pBt[dBt],indices:!1,serializeDate(o){return SDn.call(o)},skipNulls:!1,strictNullHandling:!1};function IDn(o){return typeof o=="string"||typeof o=="number"||typeof o=="boolean"||typeof o=="symbol"||typeof o=="bigint"}const aRt={};function G7e(o,h,b,k,O,P,B,G,J,U,nt,et,tt,st,it,At,Dt,Ot){let oe=o,re=Ot,Pe=0,mn=!1;for(;(re=re.get(aRt))!==void 0&&!mn;){const Gn=re.get(o);if(Pe+=1,typeof Gn<"u"){if(Gn===Pe)throw new RangeError("Cyclic object value");mn=!0}typeof re.get(aRt)>"u"&&(Pe=0)}if(typeof U=="function"?oe=U(h,oe):oe instanceof Date?oe=tt==null?void 0:tt(oe):b==="comma"&&c6(oe)&&(oe=X8e(oe,function(Gn){return Gn instanceof Date?tt==null?void 0:tt(Gn):Gn})),oe===null){if(P)return J&&!At?J(h,Xp.encoder,Dt,"key",st):h;oe=""}if(IDn(oe)||_Dn(oe)){if(J){const Gn=At?h:J(h,Xp.encoder,Dt,"key",st);return[(it==null?void 0:it(Gn))+"="+(it==null?void 0:it(J(oe,Xp.encoder,Dt,"value",st)))]}return[(it==null?void 0:it(h))+"="+(it==null?void 0:it(String(oe)))]}const ge=[];if(typeof oe>"u")return ge;let Ln;if(b==="comma"&&c6(oe))At&&J&&(oe=X8e(oe,J)),Ln=[{value:oe.length>0?oe.join(",")||null:void 0}];else if(c6(U))Ln=U;else{const Gn=Object.keys(oe);Ln=nt?Gn.sort(nt):Gn}const Kn=G?String(h).replace(/\./g,"%2E"):String(h),Bn=k&&c6(oe)&&oe.length===1?Kn+"[]":Kn;if(O&&c6(oe)&&oe.length===0)return Bn+"[]";for(let Gn=0;Gn<Ln.length;++Gn){const Vn=Ln[Gn],lr=typeof Vn=="object"&&typeof Vn.value<"u"?Vn.value:oe[Vn];if(B&&lr===null)continue;const hi=et&&G?Vn.replace(/\./g,"%2E"):Vn,$n=c6(oe)?typeof b=="function"?b(Bn,hi):Bn:Bn+(et?"."+hi:"["+hi+"]");Ot.set(o,Pe);const Kt=new WeakMap;Kt.set(aRt,Ot),U7e(ge,G7e(lr,$n,b,k,O,P,B,G,b==="comma"&&At&&c6(oe)?null:J,U,nt,et,tt,st,it,At,Dt,Kt))}return ge}function CDn(o=Xp){if(typeof o.allowEmptyArrays<"u"&&typeof o.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof o.encodeDotInKeys<"u"&&typeof o.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(o.encoder!==null&&typeof o.encoder<"u"&&typeof o.encoder!="function")throw new TypeError("Encoder has to be a function.");const h=o.charset||Xp.charset;if(typeof o.charset<"u"&&o.charset!=="utf-8"&&o.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let b=dBt;if(typeof o.format<"u"){if(!EDn.call(pBt,o.format))throw new TypeError("Unknown format option provided.");b=o.format}const k=pBt[b];let O=Xp.filter;(typeof o.filter=="function"||c6(o.filter))&&(O=o.filter);let P;if(o.arrayFormat&&o.arrayFormat in z7e?P=o.arrayFormat:"indices"in o?P=o.indices?"indices":"repeat":P=Xp.arrayFormat,"commaRoundTrip"in o&&typeof o.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const B=typeof o.allowDots>"u"?o.encodeDotInKeys?!0:Xp.allowDots:!!o.allowDots;return{addQueryPrefix:typeof o.addQueryPrefix=="boolean"?o.addQueryPrefix:Xp.addQueryPrefix,allowDots:B,allowEmptyArrays:typeof o.allowEmptyArrays=="boolean"?!!o.allowEmptyArrays:Xp.allowEmptyArrays,arrayFormat:P,charset:h,charsetSentinel:typeof o.charsetSentinel=="boolean"?o.charsetSentinel:Xp.charsetSentinel,commaRoundTrip:!!o.commaRoundTrip,delimiter:typeof o.delimiter>"u"?Xp.delimiter:o.delimiter,encode:typeof o.encode=="boolean"?o.encode:Xp.encode,encodeDotInKeys:typeof o.encodeDotInKeys=="boolean"?o.encodeDotInKeys:Xp.encodeDotInKeys,encoder:typeof o.encoder=="function"?o.encoder:Xp.encoder,encodeValuesOnly:typeof o.encodeValuesOnly=="boolean"?o.encodeValuesOnly:Xp.encodeValuesOnly,filter:O,format:b,formatter:k,serializeDate:typeof o.serializeDate=="function"?o.serializeDate:Xp.serializeDate,skipNulls:typeof o.skipNulls=="boolean"?o.skipNulls:Xp.skipNulls,sort:typeof o.sort=="function"?o.sort:null,strictNullHandling:typeof o.strictNullHandling=="boolean"?o.strictNullHandling:Xp.strictNullHandling}}function ADn(o,h={}){let b=o;const k=CDn(h);let O,P;typeof k.filter=="function"?(P=k.filter,b=P("",b)):c6(k.filter)&&(P=k.filter,O=P);const B=[];if(typeof b!="object"||b===null)return"";const G=z7e[k.arrayFormat],J=G==="comma"&&k.commaRoundTrip;O||(O=Object.keys(b)),k.sort&&O.sort(k.sort);const U=new WeakMap;for(let tt=0;tt<O.length;++tt){const st=O[tt];k.skipNulls&&b[st]===null||U7e(B,G7e(b[st],st,G,J,k.allowEmptyArrays,k.strictNullHandling,k.skipNulls,k.encodeDotInKeys,k.encode?k.encoder:null,k.filter,k.sort,k.allowDots,k.serializeDate,k.format,k.formatter,k.encodeValuesOnly,k.charset,U))}const nt=B.join(k.delimiter);let et=k.addQueryPrefix===!0?"?":"";return k.charsetSentinel&&(k.charset==="iso-8859-1"?et+="utf8=%26%2310003%3B&":et+="utf8=%E2%9C%93&"),nt.length>0?et+nt:""}const kj="4.91.1";let Q8e=!1,fX,q7e,W7e,gBt,K7e,Y7e,V7e,J7e,X7e;function ODn(o,h={auto:!1}){if(Q8e)throw new Error(`you must \`import 'openai/shims/${o.kind}'\` before importing anything else from openai`);if(fX)throw new Error(`can't \`import 'openai/shims/${o.kind}'\` after \`import 'openai/shims/${fX}'\``);Q8e=h.auto,fX=o.kind,q7e=o.fetch,W7e=o.FormData,gBt=o.File,K7e=o.ReadableStream,Y7e=o.getMultipartRequestOptions,V7e=o.getDefaultAgent,J7e=o.fileFromPath,X7e=o.isFsReadStream}class NDn{constructor(h){this.body=h}get[Symbol.toStringTag](){return"MultipartBody"}}function PDn({manuallyImported:o}={}){const h=o?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let b,k,O,P;try{b=fetch,k=Request,O=Response,P=Headers}catch(B){throw new Error(`this environment is missing the following Web Fetch API type: ${B.message}. ${h}`)}return{kind:"web",fetch:b,Request:k,Response:O,Headers:P,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${h}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${h}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${h}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${h}`)}},getMultipartRequestOptions:async(B,G)=>({...G,body:new NDn(B)}),getDefaultAgent:B=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:B=>!1}}const Q7e=()=>{fX||ODn(PDn(),{auto:!0})};Q7e();class Cs extends Error{}class Ig extends Cs{constructor(h,b,k,O){super(`${Ig.makeMessage(h,b,k)}`),this.status=h,this.headers=O,this.request_id=O==null?void 0:O["x-request-id"],this.error=b;const P=b;this.code=P==null?void 0:P.code,this.param=P==null?void 0:P.param,this.type=P==null?void 0:P.type}static makeMessage(h,b,k){const O=b!=null&&b.message?typeof b.message=="string"?b.message:JSON.stringify(b.message):b?JSON.stringify(b):k;return h&&O?`${h} ${O}`:h?`${h} status code (no body)`:O||"(no status code or body)"}static generate(h,b,k,O){if(!h||!O)return new hbt({message:k,cause:bBt(b)});const P=b==null?void 0:b.error;return h===400?new Z7e(h,P,k,O):h===401?new t9e(h,P,k,O):h===403?new e9e(h,P,k,O):h===404?new n9e(h,P,k,O):h===409?new r9e(h,P,k,O):h===422?new i9e(h,P,k,O):h===429?new a9e(h,P,k,O):h>=500?new o9e(h,P,k,O):new Ig(h,P,k,O)}}class x3 extends Ig{constructor({message:h}={}){super(void 0,void 0,h||"Request was aborted.",void 0)}}class hbt extends Ig{constructor({message:h,cause:b}){super(void 0,void 0,h||"Connection error.",void 0),b&&(this.cause=b)}}class ujt extends hbt{constructor({message:h}={}){super({message:h??"Request timed out."})}}class Z7e extends Ig{}class t9e extends Ig{}class e9e extends Ig{}class n9e extends Ig{}class r9e extends Ig{}class i9e extends Ig{}class a9e extends Ig{}class o9e extends Ig{}class s9e extends Cs{constructor(){super("Could not parse response content as the length limit was reached")}}class c9e extends Cs{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var umt=function(o,h,b,k,O){if(k==="m")throw new TypeError("Private method is not writable");if(k==="a"&&!O)throw new TypeError("Private accessor was defined without a setter");if(typeof h=="function"?o!==h||!O:!h.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return k==="a"?O.call(o,b):O?O.value=b:h.set(o,b),b},jN=function(o,h,b,k){if(b==="a"&&!k)throw new TypeError("Private accessor was defined without a getter");if(typeof h=="function"?o!==h||!k:!h.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return b==="m"?k:b==="a"?k.call(o):k?k.value:h.get(o)},gw;class fbt{constructor(){gw.set(this,void 0),this.buffer=new Uint8Array,umt(this,gw,null,"f")}decode(h){if(h==null)return[];const b=h instanceof ArrayBuffer?new Uint8Array(h):typeof h=="string"?new TextEncoder().encode(h):h;let k=new Uint8Array(this.buffer.length+b.length);k.set(this.buffer),k.set(b,this.buffer.length),this.buffer=k;const O=[];let P;for(;(P=LDn(this.buffer,jN(this,gw,"f")))!=null;){if(P.carriage&&jN(this,gw,"f")==null){umt(this,gw,P.index,"f");continue}if(jN(this,gw,"f")!=null&&(P.index!==jN(this,gw,"f")+1||P.carriage)){O.push(this.decodeText(this.buffer.slice(0,jN(this,gw,"f")-1))),this.buffer=this.buffer.slice(jN(this,gw,"f")),umt(this,gw,null,"f");continue}const B=jN(this,gw,"f")!==null?P.preceding-1:P.preceding,G=this.decodeText(this.buffer.slice(0,B));O.push(G),this.buffer=this.buffer.slice(P.index),umt(this,gw,null,"f")}return O}decodeText(h){if(h==null)return"";if(typeof h=="string")return h;if(typeof Buffer<"u"){if(h instanceof Buffer)return h.toString();if(h instanceof Uint8Array)return Buffer.from(h).toString();throw new Cs(`Unexpected: received non-Uint8Array (${h.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(h instanceof Uint8Array||h instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(h);throw new Cs(`Unexpected: received non-Uint8Array/ArrayBuffer (${h.constructor.name}) in a web platform. Please report this error.`)}throw new Cs("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
3199
+ `)}]).flat()}function bDn(o){return async h=>{const b=[];if(h.ready()===!1){if((o==null?void 0:o.initialize)!==!0&&typeof(o==null?void 0:o.initialize)!="function")await h.initialize();else if(b.push(...await(typeof(o==null?void 0:o.initialize)=="function"?o.initialize:dDn)(h)),h.ready()===!1)return b}if(h.stack.length!==0&&b.push(...await((o==null?void 0:o.cancel)??cDn)(h)),b.push(...await((o==null?void 0:o.select)??gDn)(h)),h.stack.length===0)return b;for(;;){const k=await((o==null?void 0:o.call)??ZMn)(h,h.stack.map(P=>P.operation));b.push(...k);const O=k.filter(P=>P.type==="execute");if((o==null?void 0:o.describe)!==null&&(o==null?void 0:o.describe)!==!1&&b.push(...await(typeof(o==null?void 0:o.describe)=="function"?o.describe:fDn)(h,O)),O.length===0||h.stack.length===0)break}return b}}function yDn(o){if(o.history.type==="text")return B7e({history:o.history});if(o.history.type==="select")return j7e({operations:o.operations,history:o.history});if(o.history.type==="cancel")return F7e({operations:o.operations,history:o.history});if(o.history.type==="execute")return sjt({operations:o.operations,history:o.history});if(o.history.type==="describe")return $7e({operations:o.operations,history:o.history});throw new Error("Invalid prompt type.")}function B7e(o){return LX(o.history)}function j7e(o){return sbt({id:o.history.id,selections:o.history.selections.map(h=>Wj({operation:cjt({operations:o.operations,input:h.operation}),reason:h.reason}))})}function F7e(o){return cbt({id:o.history.id,selections:o.history.selections.map(h=>Wj({operation:cjt({operations:o.operations,input:h.operation}),reason:h.reason}))})}function sjt(o){return eT({id:o.history.id,operation:cjt({operations:o.operations,input:o.history.operation}),arguments:o.history.arguments,value:o.history.value})}function $7e(o){return S7e({text:o.history.text,executes:o.history.executes.map(h=>sjt({operations:o.operations,history:h}))})}function cjt(o){var b;const h=(b=o.operations.get(o.input.controller))==null?void 0:b.get(o.input.function);if(h===void 0)throw new Error(`No operation found: (controller: ${o.input.controller}, function: ${o.input.function})`);return h}const wDn={transform:yDn,transformText:B7e,transformSelect:j7e,transformCancel:F7e,transformExecute:sjt,transformDescribe:$7e};class H7e{constructor(h){var b,k;this.props=h,this.operations_=pLn.compose({controllers:h.controllers,config:h.config}),this.stack_=[],this.listeners_=new Map,this.histories_=(h.histories??[]).map(O=>wDn.transform({operations:this.operations_.group,history:O})),this.token_usage_=hX.zero(),this.ready_=!1,this.executor_=typeof((b=h.config)==null?void 0:b.executor)=="function"?h.config.executor:bDn(((k=h.config)==null?void 0:k.executor)??null)}clone(){var h;return new H7e({...this.props,histories:(h=this.props.histories)==null?void 0:h.slice()})}async conversate(h){const b=LX({role:"user",text:h});this.dispatch(ubt({role:"user",stream:ajt(h),done:()=>!0,get:()=>h,join:async()=>Promise.resolve(h)})).catch(()=>{});const k=await this.executor_(this.getContext({prompt:b,usage:this.token_usage_}));return this.histories_.push(b,...k),[b,...k]}getConfig(){return this.props.config}getVendor(){return this.props.vendor}getControllers(){return this.props.controllers}getOperations(){return this.operations_.array}getHistories(){return this.histories_}getTokenUsage(){return this.token_usage_}getContext(h){const b=async k=>this.dispatch(k);return{operations:this.operations_,config:this.props.config,histories:this.histories_,stack:this.stack_,ready:()=>this.ready_,prompt:h.prompt,dispatch:async k=>this.dispatch(k),request:async(k,O)=>{const P=SLn({source:k,body:{...O,model:this.props.vendor.model,stream:!0,stream_options:{include_usage:!0}},options:this.props.vendor.options});await b(P);const B=await this.props.vendor.api.chat.completions.create(P.body,P.options),[G,J]=Z8.transform(B.toReadableStream(),st=>p6.transformCompletionChunk(st)).tee(),[U,nt]=J.tee();(async()=>{const st=U.getReader();for(;;){const it=await st.read();if(it.done)break;it.value.usage!=null&&mLn.aggregate({kind:k,completionUsage:it.value.usage,usage:h.usage})}})().catch(()=>{});const[et,tt]=G.tee();return await b({type:"response",source:k,stream:lbt(et.getReader()),body:P.body,options:P.options,join:async()=>{const st=await Z8.readAll(tt);return p6.merge(st)}}),nt},initialize:async()=>{this.ready_=!0,await b(xLn())}}}on(h,b){return T7e(this.listeners_,h,()=>new Set).add(b),this}off(h,b){const k=this.listeners_.get(h);return k!==void 0&&(k.delete(b),k.size===0&&this.listeners_.delete(h)),this}async dispatch(h){const b=this.listeners_.get(h.type);b!==void 0&&await Promise.all(Array.from(b).map(async k=>{try{await k(h)}catch{}}))}}const dBt="RFC3986",pBt={RFC1738:o=>String(o).replace(/%20/g,"+"),RFC3986:o=>String(o)},vDn="RFC1738",xDn=Array.isArray,o6=(()=>{const o=[];for(let h=0;h<256;++h)o.push("%"+((h<16?"0":"")+h.toString(16)).toUpperCase());return o})(),iRt=1024,kDn=(o,h,b,k,O)=>{if(o.length===0)return o;let P=o;if(typeof o=="symbol"?P=Symbol.prototype.toString.call(o):typeof o!="string"&&(P=String(o)),b==="iso-8859-1")return escape(P).replace(/%u[0-9a-f]{4}/gi,function(G){return"%26%23"+parseInt(G.slice(2),16)+"%3B"});let B="";for(let G=0;G<P.length;G+=iRt){const J=P.length>=iRt?P.slice(G,G+iRt):P,U=[];for(let nt=0;nt<J.length;++nt){let et=J.charCodeAt(nt);if(et===45||et===46||et===95||et===126||et>=48&&et<=57||et>=65&&et<=90||et>=97&&et<=122||O===vDn&&(et===40||et===41)){U[U.length]=J.charAt(nt);continue}if(et<128){U[U.length]=o6[et];continue}if(et<2048){U[U.length]=o6[192|et>>6]+o6[128|et&63];continue}if(et<55296||et>=57344){U[U.length]=o6[224|et>>12]+o6[128|et>>6&63]+o6[128|et&63];continue}nt+=1,et=65536+((et&1023)<<10|J.charCodeAt(nt)&1023),U[U.length]=o6[240|et>>18]+o6[128|et>>12&63]+o6[128|et>>6&63]+o6[128|et&63]}B+=U.join("")}return B};function _Dn(o){return!o||typeof o!="object"?!1:!!(o.constructor&&o.constructor.isBuffer&&o.constructor.isBuffer(o))}function X8e(o,h){if(xDn(o)){const b=[];for(let k=0;k<o.length;k+=1)b.push(h(o[k]));return b}return h(o)}const EDn=Object.prototype.hasOwnProperty,z7e={brackets(o){return String(o)+"[]"},comma:"comma",indices(o,h){return String(o)+"["+h+"]"},repeat(o){return String(o)}},c6=Array.isArray,TDn=Array.prototype.push,U7e=function(o,h){TDn.apply(o,c6(h)?h:[h])},SDn=Date.prototype.toISOString,Xp={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:kDn,encodeValuesOnly:!1,format:dBt,formatter:pBt[dBt],indices:!1,serializeDate(o){return SDn.call(o)},skipNulls:!1,strictNullHandling:!1};function IDn(o){return typeof o=="string"||typeof o=="number"||typeof o=="boolean"||typeof o=="symbol"||typeof o=="bigint"}const aRt={};function G7e(o,h,b,k,O,P,B,G,J,U,nt,et,tt,st,it,At,Dt,Ot){let oe=o,re=Ot,Pe=0,mn=!1;for(;(re=re.get(aRt))!==void 0&&!mn;){const Gn=re.get(o);if(Pe+=1,typeof Gn<"u"){if(Gn===Pe)throw new RangeError("Cyclic object value");mn=!0}typeof re.get(aRt)>"u"&&(Pe=0)}if(typeof U=="function"?oe=U(h,oe):oe instanceof Date?oe=tt==null?void 0:tt(oe):b==="comma"&&c6(oe)&&(oe=X8e(oe,function(Gn){return Gn instanceof Date?tt==null?void 0:tt(Gn):Gn})),oe===null){if(P)return J&&!At?J(h,Xp.encoder,Dt,"key",st):h;oe=""}if(IDn(oe)||_Dn(oe)){if(J){const Gn=At?h:J(h,Xp.encoder,Dt,"key",st);return[(it==null?void 0:it(Gn))+"="+(it==null?void 0:it(J(oe,Xp.encoder,Dt,"value",st)))]}return[(it==null?void 0:it(h))+"="+(it==null?void 0:it(String(oe)))]}const ge=[];if(typeof oe>"u")return ge;let Ln;if(b==="comma"&&c6(oe))At&&J&&(oe=X8e(oe,J)),Ln=[{value:oe.length>0?oe.join(",")||null:void 0}];else if(c6(U))Ln=U;else{const Gn=Object.keys(oe);Ln=nt?Gn.sort(nt):Gn}const Kn=G?String(h).replace(/\./g,"%2E"):String(h),Bn=k&&c6(oe)&&oe.length===1?Kn+"[]":Kn;if(O&&c6(oe)&&oe.length===0)return Bn+"[]";for(let Gn=0;Gn<Ln.length;++Gn){const Vn=Ln[Gn],lr=typeof Vn=="object"&&typeof Vn.value<"u"?Vn.value:oe[Vn];if(B&&lr===null)continue;const hi=et&&G?Vn.replace(/\./g,"%2E"):Vn,$n=c6(oe)?typeof b=="function"?b(Bn,hi):Bn:Bn+(et?"."+hi:"["+hi+"]");Ot.set(o,Pe);const Kt=new WeakMap;Kt.set(aRt,Ot),U7e(ge,G7e(lr,$n,b,k,O,P,B,G,b==="comma"&&At&&c6(oe)?null:J,U,nt,et,tt,st,it,At,Dt,Kt))}return ge}function CDn(o=Xp){if(typeof o.allowEmptyArrays<"u"&&typeof o.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof o.encodeDotInKeys<"u"&&typeof o.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(o.encoder!==null&&typeof o.encoder<"u"&&typeof o.encoder!="function")throw new TypeError("Encoder has to be a function.");const h=o.charset||Xp.charset;if(typeof o.charset<"u"&&o.charset!=="utf-8"&&o.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let b=dBt;if(typeof o.format<"u"){if(!EDn.call(pBt,o.format))throw new TypeError("Unknown format option provided.");b=o.format}const k=pBt[b];let O=Xp.filter;(typeof o.filter=="function"||c6(o.filter))&&(O=o.filter);let P;if(o.arrayFormat&&o.arrayFormat in z7e?P=o.arrayFormat:"indices"in o?P=o.indices?"indices":"repeat":P=Xp.arrayFormat,"commaRoundTrip"in o&&typeof o.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const B=typeof o.allowDots>"u"?o.encodeDotInKeys?!0:Xp.allowDots:!!o.allowDots;return{addQueryPrefix:typeof o.addQueryPrefix=="boolean"?o.addQueryPrefix:Xp.addQueryPrefix,allowDots:B,allowEmptyArrays:typeof o.allowEmptyArrays=="boolean"?!!o.allowEmptyArrays:Xp.allowEmptyArrays,arrayFormat:P,charset:h,charsetSentinel:typeof o.charsetSentinel=="boolean"?o.charsetSentinel:Xp.charsetSentinel,commaRoundTrip:!!o.commaRoundTrip,delimiter:typeof o.delimiter>"u"?Xp.delimiter:o.delimiter,encode:typeof o.encode=="boolean"?o.encode:Xp.encode,encodeDotInKeys:typeof o.encodeDotInKeys=="boolean"?o.encodeDotInKeys:Xp.encodeDotInKeys,encoder:typeof o.encoder=="function"?o.encoder:Xp.encoder,encodeValuesOnly:typeof o.encodeValuesOnly=="boolean"?o.encodeValuesOnly:Xp.encodeValuesOnly,filter:O,format:b,formatter:k,serializeDate:typeof o.serializeDate=="function"?o.serializeDate:Xp.serializeDate,skipNulls:typeof o.skipNulls=="boolean"?o.skipNulls:Xp.skipNulls,sort:typeof o.sort=="function"?o.sort:null,strictNullHandling:typeof o.strictNullHandling=="boolean"?o.strictNullHandling:Xp.strictNullHandling}}function ADn(o,h={}){let b=o;const k=CDn(h);let O,P;typeof k.filter=="function"?(P=k.filter,b=P("",b)):c6(k.filter)&&(P=k.filter,O=P);const B=[];if(typeof b!="object"||b===null)return"";const G=z7e[k.arrayFormat],J=G==="comma"&&k.commaRoundTrip;O||(O=Object.keys(b)),k.sort&&O.sort(k.sort);const U=new WeakMap;for(let tt=0;tt<O.length;++tt){const st=O[tt];k.skipNulls&&b[st]===null||U7e(B,G7e(b[st],st,G,J,k.allowEmptyArrays,k.strictNullHandling,k.skipNulls,k.encodeDotInKeys,k.encode?k.encoder:null,k.filter,k.sort,k.allowDots,k.serializeDate,k.format,k.formatter,k.encodeValuesOnly,k.charset,U))}const nt=B.join(k.delimiter);let et=k.addQueryPrefix===!0?"?":"";return k.charsetSentinel&&(k.charset==="iso-8859-1"?et+="utf8=%26%2310003%3B&":et+="utf8=%E2%9C%93&"),nt.length>0?et+nt:""}const kj="4.91.1";let Q8e=!1,fX,q7e,W7e,gBt,K7e,Y7e,V7e,J7e,X7e;function ODn(o,h={auto:!1}){if(Q8e)throw new Error(`you must \`import 'openai/shims/${o.kind}'\` before importing anything else from openai`);if(fX)throw new Error(`can't \`import 'openai/shims/${o.kind}'\` after \`import 'openai/shims/${fX}'\``);Q8e=h.auto,fX=o.kind,q7e=o.fetch,W7e=o.FormData,gBt=o.File,K7e=o.ReadableStream,Y7e=o.getMultipartRequestOptions,V7e=o.getDefaultAgent,J7e=o.fileFromPath,X7e=o.isFsReadStream}class NDn{constructor(h){this.body=h}get[Symbol.toStringTag](){return"MultipartBody"}}function PDn({manuallyImported:o}={}){const h=o?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let b,k,O,P;try{b=fetch,k=Request,O=Response,P=Headers}catch(B){throw new Error(`this environment is missing the following Web Fetch API type: ${B.message}. ${h}`)}return{kind:"web",fetch:b,Request:k,Response:O,Headers:P,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${h}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${h}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${h}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${h}`)}},getMultipartRequestOptions:async(B,G)=>({...G,body:new NDn(B)}),getDefaultAgent:B=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:B=>!1}}const Q7e=()=>{fX||ODn(PDn(),{auto:!0})};Q7e();class Cs extends Error{}class Ig extends Cs{constructor(h,b,k,O){super(`${Ig.makeMessage(h,b,k)}`),this.status=h,this.headers=O,this.request_id=O==null?void 0:O["x-request-id"],this.error=b;const P=b;this.code=P==null?void 0:P.code,this.param=P==null?void 0:P.param,this.type=P==null?void 0:P.type}static makeMessage(h,b,k){const O=b!=null&&b.message?typeof b.message=="string"?b.message:JSON.stringify(b.message):b?JSON.stringify(b):k;return h&&O?`${h} ${O}`:h?`${h} status code (no body)`:O||"(no status code or body)"}static generate(h,b,k,O){if(!h||!O)return new hbt({message:k,cause:bBt(b)});const P=b==null?void 0:b.error;return h===400?new Z7e(h,P,k,O):h===401?new t9e(h,P,k,O):h===403?new e9e(h,P,k,O):h===404?new n9e(h,P,k,O):h===409?new r9e(h,P,k,O):h===422?new i9e(h,P,k,O):h===429?new a9e(h,P,k,O):h>=500?new o9e(h,P,k,O):new Ig(h,P,k,O)}}class x3 extends Ig{constructor({message:h}={}){super(void 0,void 0,h||"Request was aborted.",void 0)}}class hbt extends Ig{constructor({message:h,cause:b}){super(void 0,void 0,h||"Connection error.",void 0),b&&(this.cause=b)}}class ujt extends hbt{constructor({message:h}={}){super({message:h??"Request timed out."})}}class Z7e extends Ig{}class t9e extends Ig{}class e9e extends Ig{}class n9e extends Ig{}class r9e extends Ig{}class i9e extends Ig{}class a9e extends Ig{}class o9e extends Ig{}class s9e extends Cs{constructor(){super("Could not parse response content as the length limit was reached")}}class c9e extends Cs{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var umt=function(o,h,b,k,O){if(k==="m")throw new TypeError("Private method is not writable");if(k==="a"&&!O)throw new TypeError("Private accessor was defined without a setter");if(typeof h=="function"?o!==h||!O:!h.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return k==="a"?O.call(o,b):O?O.value=b:h.set(o,b),b},jN=function(o,h,b,k){if(b==="a"&&!k)throw new TypeError("Private accessor was defined without a getter");if(typeof h=="function"?o!==h||!k:!h.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return b==="m"?k:b==="a"?k.call(o):k?k.value:h.get(o)},gw;class fbt{constructor(){gw.set(this,void 0),this.buffer=new Uint8Array,umt(this,gw,null,"f")}decode(h){if(h==null)return[];const b=h instanceof ArrayBuffer?new Uint8Array(h):typeof h=="string"?new TextEncoder().encode(h):h;let k=new Uint8Array(this.buffer.length+b.length);k.set(this.buffer),k.set(b,this.buffer.length),this.buffer=k;const O=[];let P;for(;(P=LDn(this.buffer,jN(this,gw,"f")))!=null;){if(P.carriage&&jN(this,gw,"f")==null){umt(this,gw,P.index,"f");continue}if(jN(this,gw,"f")!=null&&(P.index!==jN(this,gw,"f")+1||P.carriage)){O.push(this.decodeText(this.buffer.slice(0,jN(this,gw,"f")-1))),this.buffer=this.buffer.slice(jN(this,gw,"f")),umt(this,gw,null,"f");continue}const B=jN(this,gw,"f")!==null?P.preceding-1:P.preceding,G=this.decodeText(this.buffer.slice(0,B));O.push(G),this.buffer=this.buffer.slice(P.index),umt(this,gw,null,"f")}return O}decodeText(h){if(h==null)return"";if(typeof h=="string")return h;if(typeof Buffer<"u"){if(h instanceof Buffer)return h.toString();if(h instanceof Uint8Array)return Buffer.from(h).toString();throw new Cs(`Unexpected: received non-Uint8Array (${h.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(h instanceof Uint8Array||h instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(h);throw new Cs(`Unexpected: received non-Uint8Array/ArrayBuffer (${h.constructor.name}) in a web platform. Please report this error.`)}throw new Cs("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
3200
3200
  `):[]}}gw=new WeakMap;fbt.NEWLINE_CHARS=new Set([`
3201
3201
  `,"\r"]);fbt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function LDn(o,h){for(let O=h??0;O<o.length;O++){if(o[O]===10)return{preceding:O,index:O+1,carriage:!1};if(o[O]===13)return{preceding:O,index:O+1,carriage:!0}}return null}function MDn(o){for(let k=0;k<o.length-1;k++){if(o[k]===10&&o[k+1]===10||o[k]===13&&o[k+1]===13)return k+2;if(o[k]===13&&o[k+1]===10&&k+3<o.length&&o[k+2]===13&&o[k+3]===10)return k+4}return-1}function u9e(o){if(o[Symbol.asyncIterator])return o;const h=o.getReader();return{async next(){try{const b=await h.read();return b!=null&&b.done&&h.releaseLock(),b}catch(b){throw h.releaseLock(),b}},async return(){const b=h.cancel();return h.releaseLock(),await b,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}class f6{constructor(h,b){this.iterator=h,this.controller=b}static fromSSEResponse(h,b){let k=!1;async function*O(){if(k)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");k=!0;let P=!1;try{for await(const B of DDn(h,b))if(!P){if(B.data.startsWith("[DONE]")){P=!0;continue}if(B.event===null||B.event.startsWith("response.")||B.event.startsWith("transcript.")){let G;try{G=JSON.parse(B.data)}catch(J){throw console.error("Could not parse message into JSON:",B.data),console.error("From chunk:",B.raw),J}if(G&&G.error)throw new Ig(void 0,G.error,void 0,m9e(h.headers));yield G}else{let G;try{G=JSON.parse(B.data)}catch(J){throw console.error("Could not parse message into JSON:",B.data),console.error("From chunk:",B.raw),J}if(B.event=="error")throw new Ig(void 0,G.error,G.message,void 0);yield{event:B.event,data:G}}}P=!0}catch(B){if(B instanceof Error&&B.name==="AbortError")return;throw B}finally{P||b.abort()}}return new f6(O,b)}static fromReadableStream(h,b){let k=!1;async function*O(){const B=new fbt,G=u9e(h);for await(const J of G)for(const U of B.decode(J))yield U;for(const J of B.flush())yield J}async function*P(){if(k)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");k=!0;let B=!1;try{for await(const G of O())B||G&&(yield JSON.parse(G));B=!0}catch(G){if(G instanceof Error&&G.name==="AbortError")return;throw G}finally{B||b.abort()}}return new f6(P,b)}[Symbol.asyncIterator](){return this.iterator()}tee(){const h=[],b=[],k=this.iterator(),O=P=>({next:()=>{if(P.length===0){const B=k.next();h.push(B),b.push(B)}return P.shift()}});return[new f6(()=>O(h),this.controller),new f6(()=>O(b),this.controller)]}toReadableStream(){const h=this;let b;const k=new TextEncoder;return new K7e({async start(){b=h[Symbol.asyncIterator]()},async pull(O){try{const{value:P,done:B}=await b.next();if(B)return O.close();const G=k.encode(JSON.stringify(P)+`
3202
3202
  `);O.enqueue(G)}catch(P){O.error(P)}},async cancel(){var O;await((O=b.return)==null?void 0:O.call(b))}})}}async function*DDn(o,h){if(!o.body)throw h.abort(),new Cs("Attempted to iterate over a response with no body");const b=new BDn,k=new fbt,O=u9e(o.body);for await(const P of RDn(O))for(const B of k.decode(P)){const G=b.decode(B);G&&(yield G)}for(const P of k.flush()){const B=b.decode(P);B&&(yield B)}}async function*RDn(o){let h=new Uint8Array;for await(const b of o){if(b==null)continue;const k=b instanceof ArrayBuffer?new Uint8Array(b):typeof b=="string"?new TextEncoder().encode(b):b;let O=new Uint8Array(h.length+k.length);O.set(h),O.set(k,h.length),h=O;let P;for(;(P=MDn(h))!==-1;)yield h.slice(0,P),h=h.slice(P)}h.length>0&&(yield h)}class BDn{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(h){if(h.endsWith("\r")&&(h=h.substring(0,h.length-1)),!h){if(!this.event&&!this.data.length)return null;const P={event:this.event,data:this.data.join(`
@@ -1,4 +1,4 @@
1
- import{j as y,o as v,r as f,T as b}from"../client-B3aq8qpT.js";import{v as I,A as B,d as T,_ as m,V as g,c as C,F as A,T as j,B as w}from"../VendorConfigurationMovie-DpMbpY09.js";import{a as u,_ as p}from"../_isFormatUri-YqTfGpHo.js";import{D as x}from"../Divider-DX1xhf0M.js";class R{constructor(){this.articles=[]}index(){return this.articles}create(c){const d={id:I(),title:c.input.title,body:c.input.body,thumbnail:c.input.thumbnail,created_at:new Date().toISOString(),updated_at:new Date().toISOString()};return this.articles.push(d),d}update(c){const d=this.articles.find(s=>s.id===c.id);if(d===void 0)throw new Error("Unable to find the matched article.");c.input.title!==void 0&&(d.title=c.input.title),c.input.body!==void 0&&(d.body=c.input.body),c.input.thumbnail!==void 0&&(d.thumbnail=c.input.thumbnail),d.updated_at=new Date().toISOString()}erase(c){const d=this.articles.findIndex(s=>s.id===c.id);if(d===-1)throw new Error("Unable to find the matched article.");this.articles.splice(d,1)}}const U={chatgpt:{model:"chatgpt",options:{reference:!1,strict:!1,separate:null},functions:[{name:"index",parameters:{type:"object",properties:{},additionalProperties:!1,required:[],$defs:{}},output:{description:"List of every articles",type:"array",items:{description:`Description of the current {@link IBbsArticle} type:
1
+ import{j as y,o as v,r as f,T as b}from"../client-B3aq8qpT.js";import{v as I,A as B,d as T,_ as m,V as g,c as C,F as A,T as j,B as w}from"../VendorConfigurationMovie-DACdW8dX.js";import{a as u,_ as p}from"../_isFormatUri-YqTfGpHo.js";import{D as x}from"../Divider-DX1xhf0M.js";class R{constructor(){this.articles=[]}index(){return this.articles}create(c){const d={id:I(),title:c.input.title,body:c.input.body,thumbnail:c.input.thumbnail,created_at:new Date().toISOString(),updated_at:new Date().toISOString()};return this.articles.push(d),d}update(c){const d=this.articles.find(s=>s.id===c.id);if(d===void 0)throw new Error("Unable to find the matched article.");c.input.title!==void 0&&(d.title=c.input.title),c.input.body!==void 0&&(d.body=c.input.body),c.input.thumbnail!==void 0&&(d.thumbnail=c.input.thumbnail),d.updated_at=new Date().toISOString()}erase(c){const d=this.articles.findIndex(s=>s.id===c.id);if(d===-1)throw new Error("Unable to find the matched article.");this.articles.splice(d,1)}}const U={chatgpt:{model:"chatgpt",options:{reference:!1,strict:!1,separate:null},functions:[{name:"index",parameters:{type:"object",properties:{},additionalProperties:!1,required:[],$defs:{}},output:{description:"List of every articles",type:"array",items:{description:`Description of the current {@link IBbsArticle} type:
2
2
 
3
3
  > Article entity.
4
4
  >