drizzle-cube 0.4.20 → 0.4.21
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/dist/adapters/anthropic-BTkjgFpT.cjs +1 -0
- package/dist/adapters/anthropic-CTu9E801.js +126 -0
- package/dist/adapters/express/index.cjs +6 -6
- package/dist/adapters/express/index.js +119 -116
- package/dist/adapters/fastify/index.cjs +6 -6
- package/dist/adapters/fastify/index.js +113 -110
- package/dist/adapters/google-BAK9pnQf.cjs +2 -0
- package/dist/adapters/google-DficVAsJ.js +146 -0
- package/dist/adapters/{handler-CbDMdSY5.js → handler-9Rdn7zM2.js} +534 -461
- package/dist/adapters/handler-B-tEntiU.cjs +39 -0
- package/dist/adapters/hono/index.cjs +6 -6
- package/dist/adapters/hono/index.js +199 -196
- package/dist/adapters/index-BIMhF5KZ.cjs +23 -0
- package/dist/adapters/index-BgCeQBuN.cjs +2 -0
- package/dist/adapters/index-C45_meK_.js +719 -0
- package/dist/adapters/index-CFEJ62GJ.js +5337 -0
- package/dist/adapters/nextjs/index.cjs +5 -5
- package/dist/adapters/nextjs/index.js +245 -242
- package/dist/adapters/openai-CUSRuKTk.js +131 -0
- package/dist/adapters/openai-mLo2MCat.cjs +1 -0
- package/dist/client/components/AgenticNotebook/AgentChatPanel.d.ts +3 -0
- package/dist/client/components/AgenticNotebook/index.d.ts +6 -0
- package/dist/client/hooks/useAgentChat.d.ts +6 -0
- package/dist/client/index.js +730 -697
- package/dist/client/index.js.map +1 -1
- package/dist/client/styles.css +1 -1
- package/dist/client-bundle-stats.html +1 -1
- package/dist/server/anthropic-BTkjgFpT.cjs +1 -0
- package/dist/server/anthropic-CTu9E801.js +126 -0
- package/dist/server/google-BAK9pnQf.cjs +2 -0
- package/dist/server/google-DficVAsJ.js +146 -0
- package/dist/server/index-BIMhF5KZ.cjs +23 -0
- package/dist/server/index-BgCeQBuN.cjs +2 -0
- package/dist/server/index-C45_meK_.js +719 -0
- package/dist/server/index-CFEJ62GJ.js +5337 -0
- package/dist/server/index.cjs +48 -46
- package/dist/server/index.d.ts +37 -10
- package/dist/server/index.js +1974 -1901
- package/dist/server/openai-CUSRuKTk.js +131 -0
- package/dist/server/openai-mLo2MCat.cjs +1 -0
- package/package.json +12 -2
- package/dist/adapters/handler-DtdjM1Vx.cjs +0 -37
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var l=Object.create;var i=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var p=Object.getPrototypeOf,d=Object.prototype.hasOwnProperty;var y=(o,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of u(e))!d.call(o,t)&&t!==r&&i(o,t,{get:()=>e[t],enumerable:!(s=c(e,t))||s.enumerable});return o};var m=(o,e,r)=>(r=o!=null?l(p(o)):{},y(e||!o||!o.__esModule?i(r,"default",{value:o,enumerable:!0}):r,o));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class _{client;constructor(e){this.apiKey=e}apiKey;initialized=!1;async ensureClient(){if(this.initialized)return;let e;try{const r=await import("@anthropic-ai/sdk");e=r.default||r.Anthropic||r}catch{throw new Error("@anthropic-ai/sdk is required for the Anthropic provider. Install it with: npm install @anthropic-ai/sdk")}this.client=new e({apiKey:this.apiKey}),this.initialized=!0}async createStream(e){await this.ensureClient();const{messages:r,system:s}=this.formatMessages(e.messages,e.system);return this.client.messages.create({model:e.model,max_tokens:e.maxTokens,system:s,tools:this.formatTools(e.tools),messages:r,stream:!0})}async*parseStreamEvents(e){for await(const r of e){const s=r;switch(s.type){case"content_block_start":{const t=s.content_block;t.type==="tool_use"&&(yield{type:"tool_use_start",id:t.id,name:t.name});break}case"content_block_delta":{const t=s.delta;t.type==="text_delta"&&t.text?yield{type:"text_delta",text:t.text}:t.type==="input_json_delta"&&t.partial_json&&(yield{type:"tool_input_delta",json:t.partial_json});break}case"content_block_stop":{yield{type:"tool_use_end"};break}case"message_start":{const t=s.message;t?.usage?.input_tokens!=null&&(yield{type:"message_meta",inputTokens:t.usage.input_tokens,stopReason:""});break}case"message_delta":{const t=s.usage,a=s.delta?.stop_reason||"";yield{type:"message_meta",outputTokens:t?.output_tokens,stopReason:a};break}}}}formatTools(e){return e.map(r=>({name:r.name,description:r.description,input_schema:r.parameters}))}formatMessages(e,r){return{messages:e.map(t=>t.role==="tool_result"?{role:"user",content:t.content}:{role:t.role,content:t.content}),system:r}}formatToolResults(e){return{role:"user",content:e.map(r=>({type:"tool_result",tool_use_id:r.toolUseId,content:r.content,...r.isError?{is_error:!0}:{}}))}}shouldContinue(e){return e==="tool_use"}formatError(e){if(!e||!(e instanceof Error))return"Something went wrong. Please try again.";const r=e.message||"",s={overloaded_error:"The AI service is temporarily overloaded. Please try again in a moment.",rate_limit_error:"Too many requests. Please wait a moment and try again.",api_error:"The AI service encountered an error. Please try again.",authentication_error:"Authentication failed. Please check your API key configuration.",invalid_request_error:"There was a problem with the request. Please try again."},t=e;if(t.status||t.type){const a=t.error?.type||t.type||"";if(s[a])return s[a]}if(r.startsWith("{")||r.startsWith("Error: {")){try{const a=JSON.parse(r.replace(/^Error:\s*/,"")),n=a.error?.type||a.type||"";if(s[n])return s[n]}catch{}return"The AI service encountered an error. Please try again."}return r}}exports.AnthropicProvider=_;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
class i {
|
|
2
|
+
client;
|
|
3
|
+
constructor(e) {
|
|
4
|
+
this.apiKey = e;
|
|
5
|
+
}
|
|
6
|
+
apiKey;
|
|
7
|
+
initialized = !1;
|
|
8
|
+
async ensureClient() {
|
|
9
|
+
if (this.initialized) return;
|
|
10
|
+
let e;
|
|
11
|
+
try {
|
|
12
|
+
const r = await import(
|
|
13
|
+
/* webpackIgnore: true */
|
|
14
|
+
"@anthropic-ai/sdk"
|
|
15
|
+
);
|
|
16
|
+
e = r.default || r.Anthropic || r;
|
|
17
|
+
} catch {
|
|
18
|
+
throw new Error("@anthropic-ai/sdk is required for the Anthropic provider. Install it with: npm install @anthropic-ai/sdk");
|
|
19
|
+
}
|
|
20
|
+
this.client = new e({ apiKey: this.apiKey }), this.initialized = !0;
|
|
21
|
+
}
|
|
22
|
+
async createStream(e) {
|
|
23
|
+
await this.ensureClient();
|
|
24
|
+
const { messages: r, system: s } = this.formatMessages(e.messages, e.system);
|
|
25
|
+
return this.client.messages.create({
|
|
26
|
+
model: e.model,
|
|
27
|
+
max_tokens: e.maxTokens,
|
|
28
|
+
system: s,
|
|
29
|
+
tools: this.formatTools(e.tools),
|
|
30
|
+
messages: r,
|
|
31
|
+
stream: !0
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
async *parseStreamEvents(e) {
|
|
35
|
+
for await (const r of e) {
|
|
36
|
+
const s = r;
|
|
37
|
+
switch (s.type) {
|
|
38
|
+
case "content_block_start": {
|
|
39
|
+
const t = s.content_block;
|
|
40
|
+
t.type === "tool_use" && (yield { type: "tool_use_start", id: t.id, name: t.name });
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
case "content_block_delta": {
|
|
44
|
+
const t = s.delta;
|
|
45
|
+
t.type === "text_delta" && t.text ? yield { type: "text_delta", text: t.text } : t.type === "input_json_delta" && t.partial_json && (yield { type: "tool_input_delta", json: t.partial_json });
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
case "content_block_stop": {
|
|
49
|
+
yield { type: "tool_use_end" };
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
case "message_start": {
|
|
53
|
+
const t = s.message;
|
|
54
|
+
t?.usage?.input_tokens != null && (yield {
|
|
55
|
+
type: "message_meta",
|
|
56
|
+
inputTokens: t.usage.input_tokens,
|
|
57
|
+
stopReason: ""
|
|
58
|
+
});
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
case "message_delta": {
|
|
62
|
+
const t = s.usage, o = s.delta?.stop_reason || "";
|
|
63
|
+
yield {
|
|
64
|
+
type: "message_meta",
|
|
65
|
+
outputTokens: t?.output_tokens,
|
|
66
|
+
stopReason: o
|
|
67
|
+
};
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
formatTools(e) {
|
|
74
|
+
return e.map((r) => ({
|
|
75
|
+
name: r.name,
|
|
76
|
+
description: r.description,
|
|
77
|
+
input_schema: r.parameters
|
|
78
|
+
}));
|
|
79
|
+
}
|
|
80
|
+
formatMessages(e, r) {
|
|
81
|
+
return { messages: e.map((t) => t.role === "tool_result" ? { role: "user", content: t.content } : { role: t.role, content: t.content }), system: r };
|
|
82
|
+
}
|
|
83
|
+
formatToolResults(e) {
|
|
84
|
+
return {
|
|
85
|
+
role: "user",
|
|
86
|
+
content: e.map((r) => ({
|
|
87
|
+
type: "tool_result",
|
|
88
|
+
tool_use_id: r.toolUseId,
|
|
89
|
+
content: r.content,
|
|
90
|
+
...r.isError ? { is_error: !0 } : {}
|
|
91
|
+
}))
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
shouldContinue(e) {
|
|
95
|
+
return e === "tool_use";
|
|
96
|
+
}
|
|
97
|
+
formatError(e) {
|
|
98
|
+
if (!e || !(e instanceof Error))
|
|
99
|
+
return "Something went wrong. Please try again.";
|
|
100
|
+
const r = e.message || "", s = {
|
|
101
|
+
overloaded_error: "The AI service is temporarily overloaded. Please try again in a moment.",
|
|
102
|
+
rate_limit_error: "Too many requests. Please wait a moment and try again.",
|
|
103
|
+
api_error: "The AI service encountered an error. Please try again.",
|
|
104
|
+
authentication_error: "Authentication failed. Please check your API key configuration.",
|
|
105
|
+
invalid_request_error: "There was a problem with the request. Please try again."
|
|
106
|
+
}, t = e;
|
|
107
|
+
if (t.status || t.type) {
|
|
108
|
+
const o = t.error?.type || t.type || "";
|
|
109
|
+
if (s[o])
|
|
110
|
+
return s[o];
|
|
111
|
+
}
|
|
112
|
+
if (r.startsWith("{") || r.startsWith("Error: {")) {
|
|
113
|
+
try {
|
|
114
|
+
const o = JSON.parse(r.replace(/^Error:\s*/, "")), a = o.error?.type || o.type || "";
|
|
115
|
+
if (s[a])
|
|
116
|
+
return s[a];
|
|
117
|
+
} catch {
|
|
118
|
+
}
|
|
119
|
+
return "The AI service encountered an error. Please try again.";
|
|
120
|
+
}
|
|
121
|
+
return r;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
export {
|
|
125
|
+
i as AnthropicProvider
|
|
126
|
+
};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function l(u){const e={};for(const[t,s]of Object.entries(u))if(t==="type"&&typeof s=="string")e[t]=s.toUpperCase();else if(t==="properties"&&typeof s=="object"&&s!==null){const n={};for(const[a,o]of Object.entries(s))typeof o=="object"&&o!==null?n[a]=l(o):n[a]=o;e[t]=n}else t==="items"&&typeof s=="object"&&s!==null?e[t]=l(s):e[t]=s;return e}class p{apiKey;sdk;initialized=!1;constructor(e){this.apiKey=e}async ensureSDK(){if(!this.initialized){try{this.sdk=await Promise.resolve().then(()=>require("./index-BgCeQBuN.cjs"))}catch{throw new Error("@google/generative-ai is required for the Google provider. Install it with: npm install @google/generative-ai")}this.initialized=!0}}async createStream(e){await this.ensureSDK();const{GoogleGenerativeAI:t}=this.sdk,n=new t(this.apiKey).getGenerativeModel({model:e.model,systemInstruction:e.system,generationConfig:{maxOutputTokens:e.maxTokens}}),{messages:a}=this.formatMessages(e.messages,e.system),o=this.formatTools(e.tools);return(await n.generateContentStream({contents:a,tools:o.length>0?[{functionDeclarations:o}]:void 0})).stream}async*parseStreamEvents(e){let t="stop",s=!1;for await(const n of e){const a=n;a.usageMetadata&&(yield{type:"message_meta",inputTokens:a.usageMetadata.promptTokenCount,outputTokens:a.usageMetadata.candidatesTokenCount,stopReason:""});const o=a.candidates?.[0];if(!o)continue;o.finishReason&&(o.finishReason==="STOP"?t="stop":o.finishReason==="MAX_TOKENS"?t="max_tokens":t=o.finishReason);const i=o.content?.parts;if(i){for(const r of i)if(r.text&&!r.thought&&(yield{type:"text_delta",text:r.text}),r.functionCall){s=!0;const f=`gemini-tc-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,c=r.thoughtSignature?{thoughtSignature:r.thoughtSignature}:void 0;yield{type:"tool_use_start",id:f,name:r.functionCall.name,...c?{metadata:c}:{}},yield{type:"tool_input_delta",json:JSON.stringify(r.functionCall.args||{})},yield{type:"tool_use_end"}}}}yield{type:"message_meta",stopReason:s?"tool_use":t}}formatTools(e){return e.map(t=>({name:t.name,description:t.description,parameters:l(t.parameters)}))}formatMessages(e,t){const s=[];for(const n of e)if(n.role==="tool_result"){const a=n._toolResults;if(a&&a.length>0)s.push({role:"user",parts:a.map(o=>({functionResponse:{name:o.toolName||o.toolUseId,response:{content:o.content,isError:o.isError||!1}}}))});else{const o=typeof n.content=="string"?n.content:JSON.stringify(n.content);o&&s.push({role:"user",parts:[{text:o}]})}}else if(n.role==="user"){const a=typeof n.content=="string"?n.content:JSON.stringify(n.content);s.push({role:"user",parts:[{text:a}]})}else if(n.role==="assistant")if(typeof n.content=="string")s.push({role:"model",parts:[{text:n.content}]});else{const a=n.content,o=[];for(const i of a)if(i.type==="text"&&i.text)o.push({text:i.text});else if(i.type==="tool_use"){const r={functionCall:{name:i.name,args:i.input||{}}};i.metadata?.thoughtSignature&&(r.thoughtSignature=i.metadata.thoughtSignature),o.push(r)}o.length>0&&s.push({role:"model",parts:o})}return{messages:s}}formatToolResults(e){return{role:"tool_result",content:e.map(t=>`${t.toolName||t.toolUseId}: ${t.content}`).join(`
|
|
2
|
+
`),_toolResults:e}}shouldContinue(e){return e==="tool_use"}formatError(e){if(!e||!(e instanceof Error))return"Something went wrong. Please try again.";const t=e.message||"",s=e;return s.status===429?"Too many requests. Please wait a moment and try again.":s.status===403||s.status===401?"Authentication failed. Please check your API key configuration.":s.status===503||s.status===500?"The AI service is temporarily unavailable. Please try again in a moment.":t.includes("SAFETY")?"The request was blocked by safety filters. Please rephrase your request.":t.includes("RECITATION")?"The response was blocked due to recitation concerns. Please try a different query.":t.startsWith("{")||t.startsWith("[")?"The AI service encountered an error. Please try again.":t}}exports.GoogleProvider=p;
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
function l(u) {
|
|
2
|
+
const t = {};
|
|
3
|
+
for (const [e, s] of Object.entries(u))
|
|
4
|
+
if (e === "type" && typeof s == "string")
|
|
5
|
+
t[e] = s.toUpperCase();
|
|
6
|
+
else if (e === "properties" && typeof s == "object" && s !== null) {
|
|
7
|
+
const n = {};
|
|
8
|
+
for (const [a, o] of Object.entries(s))
|
|
9
|
+
typeof o == "object" && o !== null ? n[a] = l(o) : n[a] = o;
|
|
10
|
+
t[e] = n;
|
|
11
|
+
} else e === "items" && typeof s == "object" && s !== null ? t[e] = l(s) : t[e] = s;
|
|
12
|
+
return t;
|
|
13
|
+
}
|
|
14
|
+
class p {
|
|
15
|
+
apiKey;
|
|
16
|
+
sdk;
|
|
17
|
+
initialized = !1;
|
|
18
|
+
constructor(t) {
|
|
19
|
+
this.apiKey = t;
|
|
20
|
+
}
|
|
21
|
+
async ensureSDK() {
|
|
22
|
+
if (!this.initialized) {
|
|
23
|
+
try {
|
|
24
|
+
this.sdk = await import(
|
|
25
|
+
/* webpackIgnore: true */
|
|
26
|
+
"./index-C45_meK_.js"
|
|
27
|
+
);
|
|
28
|
+
} catch {
|
|
29
|
+
throw new Error("@google/generative-ai is required for the Google provider. Install it with: npm install @google/generative-ai");
|
|
30
|
+
}
|
|
31
|
+
this.initialized = !0;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async createStream(t) {
|
|
35
|
+
await this.ensureSDK();
|
|
36
|
+
const { GoogleGenerativeAI: e } = this.sdk, n = new e(this.apiKey).getGenerativeModel({
|
|
37
|
+
model: t.model,
|
|
38
|
+
systemInstruction: t.system,
|
|
39
|
+
generationConfig: {
|
|
40
|
+
maxOutputTokens: t.maxTokens
|
|
41
|
+
}
|
|
42
|
+
}), { messages: a } = this.formatMessages(t.messages, t.system), o = this.formatTools(t.tools);
|
|
43
|
+
return (await n.generateContentStream({
|
|
44
|
+
contents: a,
|
|
45
|
+
tools: o.length > 0 ? [{ functionDeclarations: o }] : void 0
|
|
46
|
+
})).stream;
|
|
47
|
+
}
|
|
48
|
+
async *parseStreamEvents(t) {
|
|
49
|
+
let e = "stop", s = !1;
|
|
50
|
+
for await (const n of t) {
|
|
51
|
+
const a = n;
|
|
52
|
+
a.usageMetadata && (yield {
|
|
53
|
+
type: "message_meta",
|
|
54
|
+
inputTokens: a.usageMetadata.promptTokenCount,
|
|
55
|
+
outputTokens: a.usageMetadata.candidatesTokenCount,
|
|
56
|
+
stopReason: ""
|
|
57
|
+
});
|
|
58
|
+
const o = a.candidates?.[0];
|
|
59
|
+
if (!o) continue;
|
|
60
|
+
o.finishReason && (o.finishReason === "STOP" ? e = "stop" : o.finishReason === "MAX_TOKENS" ? e = "max_tokens" : e = o.finishReason);
|
|
61
|
+
const i = o.content?.parts;
|
|
62
|
+
if (i) {
|
|
63
|
+
for (const r of i)
|
|
64
|
+
if (r.text && !r.thought && (yield { type: "text_delta", text: r.text }), r.functionCall) {
|
|
65
|
+
s = !0;
|
|
66
|
+
const f = `gemini-tc-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`, c = r.thoughtSignature ? { thoughtSignature: r.thoughtSignature } : void 0;
|
|
67
|
+
yield { type: "tool_use_start", id: f, name: r.functionCall.name, ...c ? { metadata: c } : {} }, yield { type: "tool_input_delta", json: JSON.stringify(r.functionCall.args || {}) }, yield { type: "tool_use_end" };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
yield {
|
|
72
|
+
type: "message_meta",
|
|
73
|
+
stopReason: s ? "tool_use" : e
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
formatTools(t) {
|
|
77
|
+
return t.map((e) => ({
|
|
78
|
+
name: e.name,
|
|
79
|
+
description: e.description,
|
|
80
|
+
parameters: l(e.parameters)
|
|
81
|
+
}));
|
|
82
|
+
}
|
|
83
|
+
formatMessages(t, e) {
|
|
84
|
+
const s = [];
|
|
85
|
+
for (const n of t)
|
|
86
|
+
if (n.role === "tool_result") {
|
|
87
|
+
const a = n._toolResults;
|
|
88
|
+
if (a && a.length > 0)
|
|
89
|
+
s.push({
|
|
90
|
+
role: "user",
|
|
91
|
+
parts: a.map((o) => ({
|
|
92
|
+
functionResponse: {
|
|
93
|
+
name: o.toolName || o.toolUseId,
|
|
94
|
+
response: { content: o.content, isError: o.isError || !1 }
|
|
95
|
+
}
|
|
96
|
+
}))
|
|
97
|
+
});
|
|
98
|
+
else {
|
|
99
|
+
const o = typeof n.content == "string" ? n.content : JSON.stringify(n.content);
|
|
100
|
+
o && s.push({ role: "user", parts: [{ text: o }] });
|
|
101
|
+
}
|
|
102
|
+
} else if (n.role === "user") {
|
|
103
|
+
const a = typeof n.content == "string" ? n.content : JSON.stringify(n.content);
|
|
104
|
+
s.push({ role: "user", parts: [{ text: a }] });
|
|
105
|
+
} else if (n.role === "assistant")
|
|
106
|
+
if (typeof n.content == "string")
|
|
107
|
+
s.push({ role: "model", parts: [{ text: n.content }] });
|
|
108
|
+
else {
|
|
109
|
+
const a = n.content, o = [];
|
|
110
|
+
for (const i of a)
|
|
111
|
+
if (i.type === "text" && i.text)
|
|
112
|
+
o.push({ text: i.text });
|
|
113
|
+
else if (i.type === "tool_use") {
|
|
114
|
+
const r = {
|
|
115
|
+
functionCall: {
|
|
116
|
+
name: i.name,
|
|
117
|
+
args: i.input || {}
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
i.metadata?.thoughtSignature && (r.thoughtSignature = i.metadata.thoughtSignature), o.push(r);
|
|
121
|
+
}
|
|
122
|
+
o.length > 0 && s.push({ role: "model", parts: o });
|
|
123
|
+
}
|
|
124
|
+
return { messages: s };
|
|
125
|
+
}
|
|
126
|
+
formatToolResults(t) {
|
|
127
|
+
return {
|
|
128
|
+
role: "tool_result",
|
|
129
|
+
content: t.map((e) => `${e.toolName || e.toolUseId}: ${e.content}`).join(`
|
|
130
|
+
`),
|
|
131
|
+
_toolResults: t
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
shouldContinue(t) {
|
|
135
|
+
return t === "tool_use";
|
|
136
|
+
}
|
|
137
|
+
formatError(t) {
|
|
138
|
+
if (!t || !(t instanceof Error))
|
|
139
|
+
return "Something went wrong. Please try again.";
|
|
140
|
+
const e = t.message || "", s = t;
|
|
141
|
+
return s.status === 429 ? "Too many requests. Please wait a moment and try again." : s.status === 403 || s.status === 401 ? "Authentication failed. Please check your API key configuration." : s.status === 503 || s.status === 500 ? "The AI service is temporarily unavailable. Please try again in a moment." : e.includes("SAFETY") ? "The request was blocked by safety filters. Please rephrase your request." : e.includes("RECITATION") ? "The response was blocked due to recitation concerns. Please try a different query." : e.startsWith("{") || e.startsWith("[") ? "The AI service encountered an error. Please try again." : e;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
export {
|
|
145
|
+
p as GoogleProvider
|
|
146
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function S(n,e,t,s,r){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function o(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)}let Xs=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return Xs=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^t()&15>>+s/4).toString(16))};function It(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const $t=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class _ extends Error{}class F extends _{constructor(e,t,s,r){super(`${F.makeMessage(e,t,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=t;const i=t;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,t,s){const r=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,s,r){if(!e||!r)return new Oe({message:s,cause:$t(t)});const i=t?.error;return e===400?new Ut(e,i,s,r):e===401?new Wt(e,i,s,r):e===403?new qt(e,i,s,r):e===404?new jt(e,i,s,r):e===409?new Ht(e,i,s,r):e===422?new Jt(e,i,s,r):e===429?new Xt(e,i,s,r):e>=500?new Kt(e,i,s,r):new F(e,i,s,r)}}class X extends F{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Oe extends F{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class lt extends Oe{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ut extends F{}class Wt extends F{}class qt extends F{}class jt extends F{}class Ht extends F{}class Jt extends F{}class Xt extends F{}class Kt extends F{}class Ks extends _{constructor(){super("Could not parse response content as the length limit was reached")}}class Vs extends _{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class de extends Error{constructor(e){super(e)}}const Ar=/^[a-z][a-z0-9+.-]*:/i,xr=n=>Ar.test(n);let q=n=>(q=Array.isArray,q(n)),ws=q;function zs(n){return typeof n!="object"?{}:n??{}}function Rr(n){if(!n)return!0;for(const e in n)return!1;return!0}function Cr(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function je(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}const Ir=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new _(`${n} must be an integer`);if(e<0)throw new _(`${n} must be a positive integer`);return e},$r=n=>{try{return JSON.parse(n)}catch{return}},Pe=n=>new Promise(e=>setTimeout(e,n)),ce="6.25.0",vr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Er(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const kr=()=>{const n=Er();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":Ss(Deno.build.os),"X-Stainless-Arch":bs(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":Ss(globalThis.process.platform??"unknown"),"X-Stainless-Arch":bs(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=Or();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Or(){if(typeof navigator>"u"||!navigator)return null;const n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of n){const s=t.exec(navigator.userAgent);if(s){const r=s[1]||0,i=s[2]||0,a=s[3]||0;return{browser:e,version:`${r}.${i}.${a}`}}}return null}const bs=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",Ss=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let As;const Pr=()=>As??(As=kr());function Tr(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Qs(...n){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function Gs(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return Qs({start(){},async pull(t){const{done:s,value:r}=await e.next();s?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}function Ys(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Nr(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const Mr=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),Zs="RFC3986",en=n=>String(n),xs={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:en},Fr="RFC1738";let vt=(n,e)=>(vt=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),vt(n,e));const z=(()=>{const n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})(),wt=1024,Lr=(n,e,t,s,r)=>{if(n.length===0)return n;let i=n;if(typeof n=="symbol"?i=Symbol.prototype.toString.call(n):typeof n!="string"&&(i=String(n)),t==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let a="";for(let l=0;l<i.length;l+=wt){const h=i.length>=wt?i.slice(l,l+wt):i,f=[];for(let m=0;m<h.length;++m){let d=h.charCodeAt(m);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||r===Fr&&(d===40||d===41)){f[f.length]=h.charAt(m);continue}if(d<128){f[f.length]=z[d];continue}if(d<2048){f[f.length]=z[192|d>>6]+z[128|d&63];continue}if(d<55296||d>=57344){f[f.length]=z[224|d>>12]+z[128|d>>6&63]+z[128|d&63];continue}m+=1,d=65536+((d&1023)<<10|h.charCodeAt(m)&1023),f[f.length]=z[240|d>>18]+z[128|d>>12&63]+z[128|d>>6&63]+z[128|d&63]}a+=f.join("")}return a};function Br(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function Rs(n,e){if(q(n)){const t=[];for(let s=0;s<n.length;s+=1)t.push(e(n[s]));return t}return e(n)}const tn={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},sn=function(n,e){Array.prototype.push.apply(n,q(e)?e:[e])};let Cs;const P={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Lr,encodeValuesOnly:!1,format:Zs,formatter:en,indices:!1,serializeDate(n){return(Cs??(Cs=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function Dr(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const bt={};function nn(n,e,t,s,r,i,a,l,h,f,m,d,y,u,x,b,v,R){let w=n,T=R,C=0,K=!1;for(;(T=T.get(bt))!==void 0&&!K;){const E=T.get(n);if(C+=1,typeof E<"u"){if(E===C)throw new RangeError("Cyclic object value");K=!0}typeof T.get(bt)>"u"&&(C=0)}if(typeof f=="function"?w=f(e,w):w instanceof Date?w=y?.(w):t==="comma"&&q(w)&&(w=Rs(w,function(E){return E instanceof Date?y?.(E):E})),w===null){if(i)return h&&!b?h(e,P.encoder,v,"key",u):e;w=""}if(Dr(w)||Br(w)){if(h){const E=b?e:h(e,P.encoder,v,"key",u);return[x?.(E)+"="+x?.(h(w,P.encoder,v,"value",u))]}return[x?.(e)+"="+x?.(String(w))]}const U=[];if(typeof w>"u")return U;let $;if(t==="comma"&&q(w))b&&h&&(w=Rs(w,h)),$=[{value:w.length>0?w.join(",")||null:void 0}];else if(q(f))$=f;else{const E=Object.keys(w);$=m?E.sort(m):E}const L=l?String(e).replace(/\./g,"%2E"):String(e),N=s&&q(w)&&w.length===1?L+"[]":L;if(r&&q(w)&&w.length===0)return N+"[]";for(let E=0;E<$.length;++E){const k=$[E],gs=typeof k=="object"&&typeof k.value<"u"?k.value:w[k];if(a&&gs===null)continue;const yt=d&&l?k.replace(/\./g,"%2E"):k,Sr=q(w)?typeof t=="function"?t(N,yt):N:N+(d?"."+yt:"["+yt+"]");R.set(n,C);const ys=new WeakMap;ys.set(bt,R),sn(U,nn(gs,Sr,t,s,r,i,a,l,t==="comma"&&b&&q(w)?null:h,f,m,d,y,u,x,b,v,ys))}return U}function Ur(n=P){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=n.charset||P.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Zs;if(typeof n.format<"u"){if(!vt(xs,n.format))throw new TypeError("Unknown format option provided.");t=n.format}const s=xs[t];let r=P.filter;(typeof n.filter=="function"||q(n.filter))&&(r=n.filter);let i;if(n.arrayFormat&&n.arrayFormat in tn?i=n.arrayFormat:"indices"in n?i=n.indices?"indices":"repeat":i=P.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:P.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:P.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:P.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:P.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?P.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:P.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:P.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:P.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:P.encodeValuesOnly,filter:r,format:t,formatter:s,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:P.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:P.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:P.strictNullHandling}}function Wr(n,e={}){let t=n;const s=Ur(e);let r,i;typeof s.filter=="function"?(i=s.filter,t=i("",t)):q(s.filter)&&(i=s.filter,r=i);const a=[];if(typeof t!="object"||t===null)return"";const l=tn[s.arrayFormat],h=l==="comma"&&s.commaRoundTrip;r||(r=Object.keys(t)),s.sort&&r.sort(s.sort);const f=new WeakMap;for(let y=0;y<r.length;++y){const u=r[y];s.skipNulls&&t[u]===null||sn(a,nn(t[u],u,l,h,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,f))}const m=a.join(s.delimiter);let d=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),m.length>0?d+m:""}function qr(n){let e=0;for(const r of n)e+=r.length;const t=new Uint8Array(e);let s=0;for(const r of n)t.set(r,s),s+=r.length;return t}let Is;function Vt(n){let e;return(Is??(e=new globalThis.TextEncoder,Is=e.encode.bind(e)))(n)}let $s;function vs(n){let e;return($s??(e=new globalThis.TextDecoder,$s=e.decode.bind(e)))(n)}var j,H;class ct{constructor(){j.set(this,void 0),H.set(this,void 0),S(this,j,new Uint8Array),S(this,H,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Vt(e):e;S(this,j,qr([o(this,j,"f"),t]));const s=[];let r;for(;(r=jr(o(this,j,"f"),o(this,H,"f")))!=null;){if(r.carriage&&o(this,H,"f")==null){S(this,H,r.index);continue}if(o(this,H,"f")!=null&&(r.index!==o(this,H,"f")+1||r.carriage)){s.push(vs(o(this,j,"f").subarray(0,o(this,H,"f")-1))),S(this,j,o(this,j,"f").subarray(o(this,H,"f"))),S(this,H,null);continue}const i=o(this,H,"f")!==null?r.preceding-1:r.preceding,a=vs(o(this,j,"f").subarray(0,i));s.push(a),S(this,j,o(this,j,"f").subarray(r.index)),S(this,H,null)}return s}flush(){return o(this,j,"f").length?this.decode(`
|
|
2
|
+
`):[]}}j=new WeakMap,H=new WeakMap;ct.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,"\r"]);ct.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function jr(n,e){for(let r=e??0;r<n.length;r++){if(n[r]===10)return{preceding:r,index:r+1,carriage:!1};if(n[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function Hr(n){for(let s=0;s<n.length-1;s++){if(n[s]===10&&n[s+1]===10||n[s]===13&&n[s+1]===13)return s+2;if(n[s]===13&&n[s+1]===10&&s+3<n.length&&n[s+2]===13&&n[s+3]===10)return s+4}return-1}const Ze={off:0,error:200,warn:300,info:400,debug:500},Es=(n,e,t)=>{if(n){if(Cr(Ze,n))return n;B(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Ze))}`)}};function ye(){}function Fe(n,e,t){return!e||Ze[n]>Ze[t]?ye:e[n].bind(e)}const Jr={error:ye,warn:ye,info:ye,debug:ye};let ks=new WeakMap;function B(n){const e=n.logger,t=n.logLevel??"off";if(!e)return Jr;const s=ks.get(e);if(s&&s[0]===t)return s[1];const r={error:Fe("error",e,t),warn:Fe("warn",e,t),info:Fe("info",e,t),debug:Fe("debug",e,t)};return ks.set(e,[t,r]),r}const ne=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var ge;class G{constructor(e,t,s){this.iterator=e,ge.set(this,void 0),this.controller=t,S(this,ge,s)}static fromSSEResponse(e,t,s,r){let i=!1;const a=s?B(s):console;async function*l(){if(i)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let h=!1;try{for await(const f of Xr(e,t))if(!h){if(f.data.startsWith("[DONE]")){h=!0;continue}if(f.event===null||!f.event.startsWith("thread.")){let m;try{m=JSON.parse(f.data)}catch(d){throw a.error("Could not parse message into JSON:",f.data),a.error("From chunk:",f.raw),d}if(m&&m.error)throw new F(void 0,m.error,void 0,e.headers);yield r?{event:f.event,data:m}:m}else{let m;try{m=JSON.parse(f.data)}catch(d){throw console.error("Could not parse message into JSON:",f.data),console.error("From chunk:",f.raw),d}if(f.event=="error")throw new F(void 0,m.error,m.message,void 0);yield{event:f.event,data:m}}}h=!0}catch(f){if(It(f))return;throw f}finally{h||t.abort()}}return new G(l,t,s)}static fromReadableStream(e,t,s){let r=!1;async function*i(){const l=new ct,h=Ys(e);for await(const f of h)for(const m of l.decode(f))yield m;for(const f of l.flush())yield f}async function*a(){if(r)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let l=!1;try{for await(const h of i())l||h&&(yield JSON.parse(h));l=!0}catch(h){if(It(h))return;throw h}finally{l||t.abort()}}return new G(a,t,s)}[(ge=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),r=i=>({next:()=>{if(i.length===0){const a=s.next();e.push(a),t.push(a)}return i.shift()}});return[new G(()=>r(e),this.controller,o(this,ge,"f")),new G(()=>r(t),this.controller,o(this,ge,"f"))]}toReadableStream(){const e=this;let t;return Qs({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:r,done:i}=await t.next();if(i)return s.close();const a=Vt(JSON.stringify(r)+`
|
|
4
|
+
`);s.enqueue(a)}catch(r){s.error(r)}},async cancel(){await t.return?.()}})}}async function*Xr(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new _("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new _("Attempted to iterate over a response with no body");const t=new Vr,s=new ct,r=Ys(n.body);for await(const i of Kr(r))for(const a of s.decode(i)){const l=t.decode(a);l&&(yield l)}for(const i of s.flush()){const a=t.decode(i);a&&(yield a)}}async function*Kr(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Vt(t):t;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let i;for(;(i=Hr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}class Vr{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,r]=zr(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function zr(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function rn(n,e){const{response:t,requestLogID:s,retryOfRequestLogID:r,startTime:i}=e,a=await(async()=>{if(e.options.stream)return B(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n,e.options.__synthesizeEventData):G.fromSSEResponse(t,e.controller,n,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const h=t.headers.get("content-type")?.split(";")[0]?.trim();if(h?.includes("application/json")||h?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;const y=await t.json();return an(y,t)}return await t.text()})();return B(n).debug(`[${s}] response parsed`,ne({retryOfRequestLogID:r,url:t.url,status:t.status,body:a,durationMs:Date.now()-i})),a}function an(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var we;class Te extends Promise{constructor(e,t,s=rn){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=s,we.set(this,void 0),S(this,we,e)}_thenUnwrap(e){return new Te(o(this,we,"f"),this.responsePromise,async(t,s)=>an(e(await this.parseResponse(t,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(o(this,we,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}we=new WeakMap;var Le;class zt{constructor(e,t,s,r){Le.set(this,void 0),S(this,Le,e),this.options=r,this.response=t,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new _("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await o(this,Le,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Le=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class on extends Te{constructor(e,t,s){super(e,t,async(r,i)=>new s(r,i.response,await rn(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class ut extends zt{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class I extends zt{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...zs(this.options.query),after:t}}:null}}class et extends zt{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...zs(this.options.query),after:e}}:null}}const ln=()=>{if(typeof File>"u"){const{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ie(n,e,t){return ln(),new File(n,e??"unknown_file",t)}function He(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}const Qt=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",Ee=async(n,e)=>Et(n.body)?{...n,body:await cn(n.body,e)}:n,pe=async(n,e)=>({...n,body:await cn(n.body,e)}),Os=new WeakMap;function Qr(n){const e=typeof n=="function"?n:n.fetch,t=Os.get(e);if(t)return t;const s=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new r(i).text()}catch{return!0}})();return Os.set(e,s),s}const cn=async(n,e)=>{if(!await Qr(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(n||{}).map(([s,r])=>kt(t,s,r))),t},un=n=>n instanceof Blob&&"name"in n,Gr=n=>typeof n=="object"&&n!==null&&(n instanceof Response||Qt(n)||un(n)),Et=n=>{if(Gr(n))return!0;if(Array.isArray(n))return n.some(Et);if(n&&typeof n=="object"){for(const e in n)if(Et(n[e]))return!0}return!1},kt=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,Ie([await t.blob()],He(t)));else if(Qt(t))n.append(e,Ie([await new Response(Gs(t)).blob()],He(t)));else if(un(t))n.append(e,t,He(t));else if(Array.isArray(t))await Promise.all(t.map(s=>kt(n,e+"[]",s)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,r])=>kt(n,`${e}[${s}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},hn=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Yr=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&hn(n),Zr=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function dn(n,e,t){if(ln(),n=await n,Yr(n))return n instanceof File?n:Ie([await n.arrayBuffer()],n.name);if(Zr(n)){const r=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),Ie(await Ot(r),e,t)}const s=await Ot(n);if(e||(e=He(n)),!t?.type){const r=s.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof r=="string"&&(t={...t,type:r})}return Ie(s,e,t)}async function Ot(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(hn(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(Qt(n))for await(const t of n)e.push(...await Ot(t));else{const t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${ei(n)}`)}return e}function ei(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}class g{constructor(e){this._client=e}}function fn(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Ps=Object.freeze(Object.create(null)),ti=(n=fn)=>function(t,...s){if(t.length===1)return t[0];let r=!1;const i=[],a=t.reduce((m,d,y)=>{/[?#]/.test(d)&&(r=!0);const u=s[y];let x=(r?encodeURIComponent:n)(""+u);return y!==s.length&&(u==null||typeof u=="object"&&u.toString===Object.getPrototypeOf(Object.getPrototypeOf(u.hasOwnProperty??Ps)??Ps)?.toString)&&(x=u+"",i.push({start:m.length+d.length,length:x.length,error:`Value of type ${Object.prototype.toString.call(u).slice(8,-1)} is not a valid path parameter`})),m+d+(y===s.length?"":x)},""),l=a.split(/[?#]/,1)[0],h=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let f;for(;(f=h.exec(l))!==null;)i.push({start:f.index,length:f[0].length,error:`Value "${f[0]}" can't be safely passed as a path parameter`});if(i.sort((m,d)=>m.start-d.start),i.length>0){let m=0;const d=i.reduce((y,u)=>{const x=" ".repeat(u.start-m),b="^".repeat(u.length);return m=u.start+u.length,y+x+b},"");throw new _(`Path parameters result in path with invalid segments:
|
|
6
|
+
${i.map(y=>y.error).join(`
|
|
7
|
+
`)}
|
|
8
|
+
${a}
|
|
9
|
+
${d}`)}return a},c=ti(fn);let pn=class extends g{list(e,t={},s){return this._client.getAPIList(c`/chat/completions/${e}/messages`,I,{query:t,...s})}};function tt(n){return n!==void 0&&"function"in n&&n.function!==void 0}function Gt(n){return n?.$brand==="auto-parseable-response-format"}function Ne(n){return n?.$brand==="auto-parseable-tool"}function si(n,e){return!e||!mn(e)?{...n,choices:n.choices.map(t=>(_n(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Yt(n,e)}function Yt(n,e){const t=n.choices.map(s=>{if(s.finish_reason==="length")throw new Ks;if(s.finish_reason==="content_filter")throw new Vs;return _n(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(r=>ri(e,r))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?ni(e,s.message.content):null}}});return{...n,choices:t}}function ni(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function ri(n,e){const t=n.tools?.find(s=>tt(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ne(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function ii(n,e){if(!n||!("tools"in n)||!n.tools)return!1;const t=n.tools?.find(s=>tt(s)&&s.function?.name===e.function.name);return tt(t)&&(Ne(t)||t?.function.strict||!1)}function mn(n){return Gt(n.response_format)?!0:n.tools?.some(e=>Ne(e)||e.type==="function"&&e.function.strict===!0)??!1}function _n(n){for(const e of n||[])if(e.type!=="function")throw new _(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function ai(n){for(const e of n??[]){if(e.type!=="function")throw new _(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new _(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const st=n=>n?.role==="assistant",gn=n=>n?.role==="tool";var Pt,Je,Xe,be,Se,Ke,Ae,Z,xe,nt,rt,ue,yn;class Zt{constructor(){Pt.add(this),this.controller=new AbortController,Je.set(this,void 0),Xe.set(this,()=>{}),be.set(this,()=>{}),Se.set(this,void 0),Ke.set(this,()=>{}),Ae.set(this,()=>{}),Z.set(this,{}),xe.set(this,!1),nt.set(this,!1),rt.set(this,!1),ue.set(this,!1),S(this,Je,new Promise((e,t)=>{S(this,Xe,e,"f"),S(this,be,t,"f")})),S(this,Se,new Promise((e,t)=>{S(this,Ke,e,"f"),S(this,Ae,t,"f")})),o(this,Je,"f").catch(()=>{}),o(this,Se,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},o(this,Pt,"m",yn).bind(this))},0)}_connected(){this.ended||(o(this,Xe,"f").call(this),this._emit("connect"))}get ended(){return o(this,xe,"f")}get errored(){return o(this,nt,"f")}get aborted(){return o(this,rt,"f")}abort(){this.controller.abort()}on(e,t){return(o(this,Z,"f")[e]||(o(this,Z,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=o(this,Z,"f")[e];if(!s)return this;const r=s.findIndex(i=>i.listener===t);return r>=0&&s.splice(r,1),this}once(e,t){return(o(this,Z,"f")[e]||(o(this,Z,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{S(this,ue,!0),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){S(this,ue,!0),await o(this,Se,"f")}_emit(e,...t){if(o(this,xe,"f"))return;e==="end"&&(S(this,xe,!0),o(this,Ke,"f").call(this));const s=o(this,Z,"f")[e];if(s&&(o(this,Z,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!o(this,ue,"f")&&!s?.length&&Promise.reject(r),o(this,be,"f").call(this,r),o(this,Ae,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!o(this,ue,"f")&&!s?.length&&Promise.reject(r),o(this,be,"f").call(this,r),o(this,Ae,"f").call(this,r),this._emit("end")}}_emitFinal(){}}Je=new WeakMap,Xe=new WeakMap,be=new WeakMap,Se=new WeakMap,Ke=new WeakMap,Ae=new WeakMap,Z=new WeakMap,xe=new WeakMap,nt=new WeakMap,rt=new WeakMap,ue=new WeakMap,Pt=new WeakSet,yn=function(e){if(S(this,nt,!0),e instanceof Error&&e.name==="AbortError"&&(e=new X),e instanceof X)return S(this,rt,!0),this._emit("abort",e);if(e instanceof _)return this._emit("error",e);if(e instanceof Error){const t=new _(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new _(String(e)))};function oi(n){return typeof n.parse=="function"}var W,Tt,it,Nt,Mt,Ft,wn,bn;const li=10;class Sn extends Zt{constructor(){super(...arguments),W.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),gn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(st(e)&&e.tool_calls)for(const s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new _("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),o(this,W,"m",Tt).call(this)}async finalMessage(){return await this.done(),o(this,W,"m",it).call(this)}async finalFunctionToolCall(){return await this.done(),o(this,W,"m",Nt).call(this)}async finalFunctionToolCallResult(){return await this.done(),o(this,W,"m",Mt).call(this)}async totalUsage(){return await this.done(),o(this,W,"m",Ft).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=o(this,W,"m",it).call(this);t&&this._emit("finalMessage",t);const s=o(this,W,"m",Tt).call(this);s&&this._emit("finalContent",s);const r=o(this,W,"m",Nt).call(this);r&&this._emit("finalFunctionToolCall",r);const i=o(this,W,"m",Mt).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",o(this,W,"m",Ft).call(this))}async _createChatCompletion(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),o(this,W,"m",wn).call(this,t);const i=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Yt(i,t))}async _runChatCompletion(e,t,s){for(const r of t.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,t,s)}async _runTools(e,t,s){const r="tool",{tool_choice:i="auto",stream:a,...l}=t,h=typeof i!="string"&&i.type==="function"&&i?.function?.name,{maxChatCompletions:f=li}=s||{},m=t.tools.map(u=>{if(Ne(u)){if(!u.$callback)throw new _("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:u.$callback,name:u.function.name,description:u.function.description||"",parameters:u.function.parameters,parse:u.$parseRaw,strict:!0}}}return u}),d={};for(const u of m)u.type==="function"&&(d[u.function.name||u.function.function.name]=u.function);const y="tools"in t?m.map(u=>u.type==="function"?{type:"function",function:{name:u.function.name||u.function.function.name,parameters:u.function.parameters,description:u.function.description,strict:u.function.strict}}:u):void 0;for(const u of t.messages)this._addMessage(u,!1);for(let u=0;u<f;++u){const b=(await this._createChatCompletion(e,{...l,tool_choice:i,tools:y,messages:[...this.messages]},s)).choices[0]?.message;if(!b)throw new _("missing message in ChatCompletion response");if(!b.tool_calls?.length)return;for(const v of b.tool_calls){if(v.type!=="function")continue;const R=v.id,{name:w,arguments:T}=v.function,C=d[w];if(C){if(h&&h!==w){const L=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(h)} requested. Please try again`;this._addMessage({role:r,tool_call_id:R,content:L});continue}}else{const L=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(d).map(N=>JSON.stringify(N)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:R,content:L});continue}let K;try{K=oi(C)?await C.parse(T):T}catch(L){const N=L instanceof Error?L.message:String(L);this._addMessage({role:r,tool_call_id:R,content:N});continue}const U=await C.function(K,this),$=o(this,W,"m",bn).call(this,U);if(this._addMessage({role:r,tool_call_id:R,content:$}),h)return}}}}W=new WeakSet,Tt=function(){return o(this,W,"m",it).call(this).content??null},it=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(st(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new _("stream ended without producing a ChatCompletionMessage with role=assistant")},Nt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(st(t)&&t?.tool_calls?.length)return t.tool_calls.filter(s=>s.type==="function").at(-1)?.function}},Mt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(gn(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(r=>r.type==="function"&&r.id===t.tool_call_id)))return t.content}},Ft=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},wn=function(e){if(e.n!=null&&e.n>1)throw new _("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},bn=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class es extends Sn{static runTools(e,t,s){const r=new es,i={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,i)),r}_addMessage(e,t=!0){super._addMessage(e,t),st(e)&&e.content&&this._emit("content",e.content)}}const An=1,xn=2,Rn=4,Cn=8,In=16,$n=32,vn=64,En=128,kn=256,On=En|kn,Pn=In|$n|On|vn,Tn=An|xn|Pn,Nn=Rn|Cn,ci=Tn|Nn,M={STR:An,NUM:xn,ARR:Rn,OBJ:Cn,NULL:In,BOOL:$n,NAN:vn,INFINITY:En,MINUS_INFINITY:kn,INF:On,SPECIAL:Pn,ATOM:Tn,COLLECTION:Nn,ALL:ci};class ui extends Error{}class hi extends Error{}function di(n,e=M.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return fi(n.trim(),e)}const fi=(n,e)=>{const t=n.length;let s=0;const r=y=>{throw new ui(`${y} at position ${s}`)},i=y=>{throw new hi(`${y} at position ${s}`)},a=()=>(d(),s>=t&&r("Unexpected end of input"),n[s]==='"'?l():n[s]==="{"?h():n[s]==="["?f():n.substring(s,s+4)==="null"||M.NULL&e&&t-s<4&&"null".startsWith(n.substring(s))?(s+=4,null):n.substring(s,s+4)==="true"||M.BOOL&e&&t-s<4&&"true".startsWith(n.substring(s))?(s+=4,!0):n.substring(s,s+5)==="false"||M.BOOL&e&&t-s<5&&"false".startsWith(n.substring(s))?(s+=5,!1):n.substring(s,s+8)==="Infinity"||M.INFINITY&e&&t-s<8&&"Infinity".startsWith(n.substring(s))?(s+=8,1/0):n.substring(s,s+9)==="-Infinity"||M.MINUS_INFINITY&e&&1<t-s&&t-s<9&&"-Infinity".startsWith(n.substring(s))?(s+=9,-1/0):n.substring(s,s+3)==="NaN"||M.NAN&e&&t-s<3&&"NaN".startsWith(n.substring(s))?(s+=3,NaN):m()),l=()=>{const y=s;let u=!1;for(s++;s<t&&(n[s]!=='"'||u&&n[s-1]==="\\");)u=n[s]==="\\"?!u:!1,s++;if(n.charAt(s)=='"')try{return JSON.parse(n.substring(y,++s-Number(u)))}catch(x){i(String(x))}else if(M.STR&e)try{return JSON.parse(n.substring(y,s-Number(u))+'"')}catch{return JSON.parse(n.substring(y,n.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},h=()=>{s++,d();const y={};try{for(;n[s]!=="}";){if(d(),s>=t&&M.OBJ&e)return y;const u=l();d(),s++;try{const x=a();Object.defineProperty(y,u,{value:x,writable:!0,enumerable:!0,configurable:!0})}catch(x){if(M.OBJ&e)return y;throw x}d(),n[s]===","&&s++}}catch{if(M.OBJ&e)return y;r("Expected '}' at end of object")}return s++,y},f=()=>{s++;const y=[];try{for(;n[s]!=="]";)y.push(a()),d(),n[s]===","&&s++}catch{if(M.ARR&e)return y;r("Expected ']' at end of array")}return s++,y},m=()=>{if(s===0){n==="-"&&M.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(n)}catch(u){if(M.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}i(String(u))}}const y=s;for(n[s]==="-"&&s++;n[s]&&!",]}".includes(n[s]);)s++;s==t&&!(M.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(n.substring(y,s))}catch{n.substring(y,s)==="-"&&M.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(n.substring(y,n.lastIndexOf("e")))}catch(x){i(String(x))}}},d=()=>{for(;s<t&&`
|
|
10
|
+
\r `.includes(n[s]);)s++};return a()},Ts=n=>di(n,M.ALL^M.NUM);var O,Y,oe,te,St,Be,At,xt,Rt,De,Ct,Ns;class ke extends Sn{constructor(e){super(),O.add(this),Y.set(this,void 0),oe.set(this,void 0),te.set(this,void 0),S(this,Y,e),S(this,oe,[])}get currentChatCompletionSnapshot(){return o(this,te,"f")}static fromReadableStream(e){const t=new ke(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,s){const r=new ke(t);return r._run(()=>r._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,t,s){super._createChatCompletion;const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),o(this,O,"m",St).call(this);const i=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const a of i)o(this,O,"m",At).call(this,a);if(i.controller.signal?.aborted)throw new X;return this._addChatCompletion(o(this,O,"m",De).call(this))}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),o(this,O,"m",St).call(this),this._connected();const r=G.fromReadableStream(e,this.controller);let i;for await(const a of r)i&&i!==a.id&&this._addChatCompletion(o(this,O,"m",De).call(this)),o(this,O,"m",At).call(this,a),i=a.id;if(r.controller.signal?.aborted)throw new X;return this._addChatCompletion(o(this,O,"m",De).call(this))}[(Y=new WeakMap,oe=new WeakMap,te=new WeakMap,O=new WeakSet,St=function(){this.ended||S(this,te,void 0)},Be=function(t){let s=o(this,oe,"f")[t.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},o(this,oe,"f")[t.index]=s,s)},At=function(t){if(this.ended)return;const s=o(this,O,"m",Ns).call(this,t);this._emit("chunk",t,s);for(const r of t.choices){const i=s.choices[r.index];r.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",r.delta.content,i.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),r.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:i.message.refusal}),r.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:i.logprobs?.content??[]}),r.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});const a=o(this,O,"m",Be).call(this,i);i.finish_reason&&(o(this,O,"m",Rt).call(this,i),a.current_tool_call_index!=null&&o(this,O,"m",xt).call(this,i,a.current_tool_call_index));for(const l of r.delta.tool_calls??[])a.current_tool_call_index!==l.index&&(o(this,O,"m",Rt).call(this,i),a.current_tool_call_index!=null&&o(this,O,"m",xt).call(this,i,a.current_tool_call_index)),a.current_tool_call_index=l.index;for(const l of r.delta.tool_calls??[]){const h=i.message.tool_calls?.[l.index];h?.type&&(h?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:h.function?.name,index:l.index,arguments:h.function.arguments,parsed_arguments:h.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(h?.type,void 0))}}},xt=function(t,s){if(o(this,O,"m",Be).call(this,t).done_tool_calls.has(s))return;const i=t.message.tool_calls?.[s];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){const a=o(this,Y,"f")?.tools?.find(l=>tt(l)&&l.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:s,arguments:i.function.arguments,parsed_arguments:Ne(a)?a.$parseRaw(i.function.arguments):a?.function.strict?JSON.parse(i.function.arguments):null})}else i.type},Rt=function(t){const s=o(this,O,"m",Be).call(this,t);if(t.message.content&&!s.content_done){s.content_done=!0;const r=o(this,O,"m",Ct).call(this);this._emit("content.done",{content:t.message.content,parsed:r?r.$parseRaw(t.message.content):null})}t.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},De=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");const t=o(this,te,"f");if(!t)throw new _("request ended without sending any chunks");return S(this,te,void 0),S(this,oe,[]),pi(t,o(this,Y,"f"))},Ct=function(){const t=o(this,Y,"f")?.response_format;return Gt(t)?t:null},Ns=function(t){var s,r,i,a;let l=o(this,te,"f");const{choices:h,...f}=t;l?Object.assign(l,f):l=S(this,te,{...f,choices:[]});for(const{delta:m,finish_reason:d,index:y,logprobs:u=null,...x}of t.choices){let b=l.choices[y];if(b||(b=l.choices[y]={finish_reason:d,index:y,message:{},logprobs:u,...x}),u)if(!b.logprobs)b.logprobs=Object.assign({},u);else{const{content:U,refusal:$,...L}=u;Object.assign(b.logprobs,L),U&&((s=b.logprobs).content??(s.content=[]),b.logprobs.content.push(...U)),$&&((r=b.logprobs).refusal??(r.refusal=[]),b.logprobs.refusal.push(...$))}if(d&&(b.finish_reason=d,o(this,Y,"f")&&mn(o(this,Y,"f")))){if(d==="length")throw new Ks;if(d==="content_filter")throw new Vs}if(Object.assign(b,x),!m)continue;const{content:v,refusal:R,function_call:w,role:T,tool_calls:C,...K}=m;if(Object.assign(b.message,K),R&&(b.message.refusal=(b.message.refusal||"")+R),T&&(b.message.role=T),w&&(b.message.function_call?(w.name&&(b.message.function_call.name=w.name),w.arguments&&((i=b.message.function_call).arguments??(i.arguments=""),b.message.function_call.arguments+=w.arguments)):b.message.function_call=w),v&&(b.message.content=(b.message.content||"")+v,!b.message.refusal&&o(this,O,"m",Ct).call(this)&&(b.message.parsed=Ts(b.message.content))),C){b.message.tool_calls||(b.message.tool_calls=[]);for(const{index:U,id:$,type:L,function:N,...E}of C){const k=(a=b.message.tool_calls)[U]??(a[U]={});Object.assign(k,E),$&&(k.id=$),L&&(k.type=L),N&&(k.function??(k.function={name:N.name??"",arguments:""})),N?.name&&(k.function.name=N.name),N?.arguments&&(k.function.arguments+=N.arguments,ii(o(this,Y,"f"),k)&&(k.function.parsed_arguments=Ts(k.function.arguments)))}}}return l},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("chunk",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new G(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function pi(n,e){const{id:t,choices:s,created:r,model:i,system_fingerprint:a,...l}=n,h={...l,id:t,choices:s.map(({message:f,finish_reason:m,index:d,logprobs:y,...u})=>{if(!m)throw new _(`missing finish_reason for choice ${d}`);const{content:x=null,function_call:b,tool_calls:v,...R}=f,w=f.role;if(!w)throw new _(`missing role for choice ${d}`);if(b){const{arguments:T,name:C}=b;if(T==null)throw new _(`missing function_call.arguments for choice ${d}`);if(!C)throw new _(`missing function_call.name for choice ${d}`);return{...u,message:{content:x,function_call:{arguments:T,name:C},role:w,refusal:f.refusal??null},finish_reason:m,index:d,logprobs:y}}return v?{...u,index:d,finish_reason:m,logprobs:y,message:{...R,role:w,content:x,refusal:f.refusal??null,tool_calls:v.map((T,C)=>{const{function:K,type:U,id:$,...L}=T,{arguments:N,name:E,...k}=K||{};if($==null)throw new _(`missing choices[${d}].tool_calls[${C}].id
|
|
11
|
+
${Ue(n)}`);if(U==null)throw new _(`missing choices[${d}].tool_calls[${C}].type
|
|
12
|
+
${Ue(n)}`);if(E==null)throw new _(`missing choices[${d}].tool_calls[${C}].function.name
|
|
13
|
+
${Ue(n)}`);if(N==null)throw new _(`missing choices[${d}].tool_calls[${C}].function.arguments
|
|
14
|
+
${Ue(n)}`);return{...L,id:$,type:U,function:{...k,name:E,arguments:N}}})}}:{...u,message:{...R,content:x,role:w,refusal:f.refusal??null},finish_reason:m,index:d,logprobs:y}}),created:r,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return si(h,e)}function Ue(n){return JSON.stringify(n)}class at extends ke{static fromReadableStream(e){const t=new at(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,s){const r=new at(t),i={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,i)),r}}let ts=class extends g{constructor(){super(...arguments),this.messages=new pn(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(c`/chat/completions/${e}`,t)}update(e,t,s){return this._client.post(c`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/chat/completions",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/chat/completions/${e}`,t)}parse(e,t){return ai(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>Yt(s,e))}runTools(e,t){return e.stream?at.runTools(this._client,e,t):es.runTools(this._client,e,t)}stream(e,t){return ke.createChatCompletion(this._client,e,t)}};ts.Messages=pn;class ss extends g{constructor(){super(...arguments),this.completions=new ts(this._client)}}ss.Completions=ts;const Mn=Symbol("brand.privateNullableHeaders");function*mi(n){if(!n)return;if(Mn in n){const{values:s,nulls:r}=n;yield*s.entries();for(const i of r)yield[i,null];return}let e=!1,t;n instanceof Headers?t=n.entries():ws(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let s of t){const r=s[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const i=ws(s[1])?s[1]:[s[1]];let a=!1;for(const l of i)l!==void 0&&(e&&!a&&(a=!0,yield[r,null]),yield[r,l])}}const p=n=>{const e=new Headers,t=new Set;for(const s of n){const r=new Set;for(const[i,a]of mi(s)){const l=i.toLowerCase();r.has(l)||(e.delete(i),r.add(l)),a===null?(e.delete(i),t.add(l)):(e.append(i,a),t.delete(l))}}return{[Mn]:!0,values:e,nulls:t}};class Fn extends g{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:p([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Ln extends g{create(e,t){return this._client.post("/audio/transcriptions",pe({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class Bn extends g{create(e,t){return this._client.post("/audio/translations",pe({body:e,...t,__metadata:{model:e.model}},this._client))}}class Me extends g{constructor(){super(...arguments),this.transcriptions=new Ln(this._client),this.translations=new Bn(this._client),this.speech=new Fn(this._client)}}Me.Transcriptions=Ln;Me.Translations=Bn;Me.Speech=Fn;class Dn extends g{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(c`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",I,{query:e,...t})}cancel(e,t){return this._client.post(c`/batches/${e}/cancel`,t)}}class Un extends g{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(c`/assistants/${e}`,{body:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",I,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let Wn=class extends g{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};class qn extends g{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let ht=class extends g{constructor(){super(...arguments),this.sessions=new Wn(this._client),this.transcriptionSessions=new qn(this._client)}};ht.Sessions=Wn;ht.TranscriptionSessions=qn;class jn extends g{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(c`/chatkit/sessions/${e}/cancel`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}let Hn=class extends g{retrieve(e,t){return this._client.get(c`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",et,{query:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(c`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},s){return this._client.getAPIList(c`/chatkit/threads/${e}/items`,et,{query:t,...s,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers])})}};class dt extends g{constructor(){super(...arguments),this.sessions=new jn(this._client),this.threads=new Hn(this._client)}}dt.Sessions=jn;dt.Threads=Hn;class Jn extends g{create(e,t,s){return this._client.post(c`/threads/${e}/messages`,{body:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{thread_id:r}=t;return this._client.get(c`/threads/${r}/messages/${e}`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:r,...i}=t;return this._client.post(c`/threads/${r}/messages/${e}`,{body:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(c`/threads/${e}/messages`,I,{query:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{thread_id:r}=t;return this._client.delete(c`/threads/${r}/messages/${e}`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class Xn extends g{retrieve(e,t,s){const{thread_id:r,run_id:i,...a}=t;return this._client.get(c`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t,s){const{thread_id:r,...i}=t;return this._client.getAPIList(c`/threads/${r}/runs/${e}/steps`,I,{query:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}const _i=n=>{if(typeof Buffer<"u"){const e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(n),t=e.length,s=new Uint8Array(t);for(let r=0;r<t;r++)s[r]=e.charCodeAt(r);return Array.from(new Float32Array(s.buffer))}},ee=n=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var D,ie,Lt,Q,Ve,V,ae,fe,re,ot,J,ze,Qe,$e,Re,Ce,Ms,Fs,Ls,Bs,Ds,Us,Ws;class ve extends Zt{constructor(){super(...arguments),D.add(this),Lt.set(this,[]),Q.set(this,{}),Ve.set(this,{}),V.set(this,void 0),ae.set(this,void 0),fe.set(this,void 0),re.set(this,void 0),ot.set(this,void 0),J.set(this,void 0),ze.set(this,void 0),Qe.set(this,void 0),$e.set(this,void 0)}[(Lt=new WeakMap,Q=new WeakMap,Ve=new WeakMap,V=new WeakMap,ae=new WeakMap,fe=new WeakMap,re=new WeakMap,ot=new WeakMap,J=new WeakMap,ze=new WeakMap,Qe=new WeakMap,$e=new WeakMap,D=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new ie;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=G.fromReadableStream(e,this.controller);for await(const i of r)o(this,D,"m",Re).call(this,i);if(r.controller.signal?.aborted)throw new X;return this._addRun(o(this,D,"m",Ce).call(this))}toReadableStream(){return new G(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,r){const i=new ie;return i._run(()=>i._runToolAssistantStream(e,t,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,s,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},l=await e.submitToolOutputs(t,a,{...r,signal:this.controller.signal});this._connected();for await(const h of l)o(this,D,"m",Re).call(this,h);if(l.controller.signal?.aborted)throw new X;return this._addRun(o(this,D,"m",Ce).call(this))}static createThreadAssistantStream(e,t,s){const r=new ie;return r._run(()=>r._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,t,s,r){const i=new ie;return i._run(()=>i._runAssistantStream(e,t,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return o(this,ze,"f")}currentRun(){return o(this,Qe,"f")}currentMessageSnapshot(){return o(this,V,"f")}currentRunStepSnapshot(){return o(this,$e,"f")}async finalRunSteps(){return await this.done(),Object.values(o(this,Q,"f"))}async finalMessages(){return await this.done(),Object.values(o(this,Ve,"f"))}async finalRun(){if(await this.done(),!o(this,ae,"f"))throw Error("Final run was not received.");return o(this,ae,"f")}async _createThreadAssistantStream(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const i={...t,stream:!0},a=await e.createAndRun(i,{...s,signal:this.controller.signal});this._connected();for await(const l of a)o(this,D,"m",Re).call(this,l);if(a.controller.signal?.aborted)throw new X;return this._addRun(o(this,D,"m",Ce).call(this))}async _createAssistantStream(e,t,s,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},l=await e.create(t,a,{...r,signal:this.controller.signal});this._connected();for await(const h of l)o(this,D,"m",Re).call(this,h);if(l.controller.signal?.aborted)throw new X;return this._addRun(o(this,D,"m",Ce).call(this))}static accumulateDelta(e,t){for(const[s,r]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=r;continue}let i=e[s];if(i==null){e[s]=r;continue}if(s==="index"||s==="type"){e[s]=r;continue}if(typeof i=="string"&&typeof r=="string")i+=r;else if(typeof i=="number"&&typeof r=="number")i+=r;else if(je(i)&&je(r))i=this.accumulateDelta(i,r);else if(Array.isArray(i)&&Array.isArray(r)){if(i.every(a=>typeof a=="string"||typeof a=="number")){i.push(...r);continue}for(const a of r){if(!je(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);const l=a.index;if(l==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const h=i[l];h==null?i.push(a):i[l]=this.accumulateDelta(h,a)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${r}, accValue: ${i}`);e[s]=i}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,r){return await this._createAssistantStream(t,e,s,r)}async _runToolAssistantStream(e,t,s,r){return await this._createToolAssistantStream(t,e,s,r)}}ie=ve,Re=function(e){if(!this.ended)switch(S(this,ze,e),o(this,D,"m",Ls).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":o(this,D,"m",Ws).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":o(this,D,"m",Fs).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":o(this,D,"m",Ms).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ce=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");if(!o(this,ae,"f"))throw Error("Final run has not been received");return o(this,ae,"f")},Ms=function(e){const[t,s]=o(this,D,"m",Ds).call(this,e,o(this,V,"f"));S(this,V,t),o(this,Ve,"f")[t.id]=t;for(const r of s){const i=t.content[r.index];i?.type=="text"&&this._emit("textCreated",i.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const r of e.data.delta.content){if(r.type=="text"&&r.text){let i=r.text,a=t.content[r.index];if(a&&a.type=="text")this._emit("textDelta",i,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=o(this,fe,"f")){if(o(this,re,"f"))switch(o(this,re,"f").type){case"text":this._emit("textDone",o(this,re,"f").text,o(this,V,"f"));break;case"image_file":this._emit("imageFileDone",o(this,re,"f").image_file,o(this,V,"f"));break}S(this,fe,r.index)}S(this,re,t.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(o(this,fe,"f")!==void 0){const r=e.data.content[o(this,fe,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,o(this,V,"f"));break;case"text":this._emit("textDone",r.text,o(this,V,"f"));break}}o(this,V,"f")&&this._emit("messageDone",e.data),S(this,V,void 0)}},Fs=function(e){const t=o(this,D,"m",Bs).call(this,e);switch(S(this,$e,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const i of s.step_details.tool_calls)i.index==o(this,ot,"f")?this._emit("toolCallDelta",i,t.step_details.tool_calls[i.index]):(o(this,J,"f")&&this._emit("toolCallDone",o(this,J,"f")),S(this,ot,i.index),S(this,J,t.step_details.tool_calls[i.index]),o(this,J,"f")&&this._emit("toolCallCreated",o(this,J,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":S(this,$e,void 0),e.data.step_details.type=="tool_calls"&&o(this,J,"f")&&(this._emit("toolCallDone",o(this,J,"f")),S(this,J,void 0)),this._emit("runStepDone",e.data,t);break}},Ls=function(e){o(this,Lt,"f").push(e),this._emit("event",e)},Bs=function(e){switch(e.event){case"thread.run.step.created":return o(this,Q,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=o(this,Q,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const r=ie.accumulateDelta(t,s.delta);o(this,Q,"f")[e.data.id]=r}return o(this,Q,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":o(this,Q,"f")[e.data.id]=e.data;break}if(o(this,Q,"f")[e.data.id])return o(this,Q,"f")[e.data.id];throw new Error("No snapshot available")},Ds=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let r=e.data;if(r.delta.content)for(const i of r.delta.content)if(i.index in t.content){let a=t.content[i.index];t.content[i.index]=o(this,D,"m",Us).call(this,i,a)}else t.content[i.index]=i,s.push(i);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Us=function(e,t){return ie.accumulateDelta(t,e)},Ws=function(e){switch(S(this,Qe,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":S(this,ae,e.data),o(this,J,"f")&&(this._emit("toolCallDone",o(this,J,"f")),S(this,J,void 0));break}};let ns=class extends g{constructor(){super(...arguments),this.steps=new Xn(this._client)}create(e,t,s){const{include:r,...i}=t;return this._client.post(c`/threads/${e}/runs`,{query:{include:r},body:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,s){const{thread_id:r}=t;return this._client.get(c`/threads/${r}/runs/${e}`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:r,...i}=t;return this._client.post(c`/threads/${r}/runs/${e}`,{body:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(c`/threads/${e}/runs`,I,{query:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{thread_id:r}=t;return this._client.post(c`/threads/${r}/runs/${e}/cancel`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const r=await this.create(e,t,s);return await this.poll(r.id,{thread_id:e},s)}createAndStream(e,t,s){return ve.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const r=p([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:i,response:a}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...r}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{const h=a.headers.get("openai-poll-after-ms");if(h){const f=parseInt(h);isNaN(f)||(l=f)}}await Pe(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,s){return ve.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){const{thread_id:r,...i}=t;return this._client.post(c`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,s){const r=await this.submitToolOutputs(e,t,s);return await this.poll(r.id,t,s)}submitToolOutputsStream(e,t,s){return ve.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}};ns.Steps=Xn;class ft extends g{constructor(){super(...arguments),this.runs=new ns(this._client),this.messages=new Jn(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(c`/threads/${e}`,{body:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t){return this._client.delete(c`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){const s=await this.createAndRun(e,t);return await this.runs.poll(s.id,{thread_id:s.thread_id},t)}createAndRunStream(e,t){return ve.createThreadAssistantStream(e,this._client.beta.threads,t)}}ft.Runs=ns;ft.Messages=Jn;class me extends g{constructor(){super(...arguments),this.realtime=new ht(this._client),this.chatkit=new dt(this._client),this.assistants=new Un(this._client),this.threads=new ft(this._client)}}me.Realtime=ht;me.ChatKit=dt;me.Assistants=Un;me.Threads=ft;class Kn extends g{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}let Vn=class extends g{retrieve(e,t,s){const{container_id:r}=t;return this._client.get(c`/containers/${r}/files/${e}/content`,{...s,headers:p([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}},rs=class extends g{constructor(){super(...arguments),this.content=new Vn(this._client)}create(e,t,s){return this._client.post(c`/containers/${e}/files`,Ee({body:t,...s},this._client))}retrieve(e,t,s){const{container_id:r}=t;return this._client.get(c`/containers/${r}/files/${e}`,s)}list(e,t={},s){return this._client.getAPIList(c`/containers/${e}/files`,I,{query:t,...s})}delete(e,t,s){const{container_id:r}=t;return this._client.delete(c`/containers/${r}/files/${e}`,{...s,headers:p([{Accept:"*/*"},s?.headers])})}};rs.Content=Vn;class is extends g{constructor(){super(...arguments),this.files=new rs(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(c`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/containers/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers])})}}is.Files=rs;class zn extends g{create(e,t,s){const{include:r,...i}=t;return this._client.post(c`/conversations/${e}/items`,{query:{include:r},body:i,...s})}retrieve(e,t,s){const{conversation_id:r,...i}=t;return this._client.get(c`/conversations/${r}/items/${e}`,{query:i,...s})}list(e,t={},s){return this._client.getAPIList(c`/conversations/${e}/items`,et,{query:t,...s})}delete(e,t,s){const{conversation_id:r}=t;return this._client.delete(c`/conversations/${r}/items/${e}`,s)}}class as extends g{constructor(){super(...arguments),this.items=new zn(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(c`/conversations/${e}`,t)}update(e,t,s){return this._client.post(c`/conversations/${e}`,{body:t,...s})}delete(e,t){return this._client.delete(c`/conversations/${e}`,t)}}as.Items=zn;class Qn extends g{create(e,t){const s=!!e.encoding_format;let r=s?e.encoding_format:"base64";s&&B(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const i=this._client.post("/embeddings",{body:{...e,encoding_format:r},...t});return s?i:(B(this._client).debug("embeddings/decoding base64 embeddings from base64"),i._thenUnwrap(a=>(a&&a.data&&a.data.forEach(l=>{const h=l.embedding;l.embedding=_i(h)}),a)))}}class Gn extends g{retrieve(e,t,s){const{eval_id:r,run_id:i}=t;return this._client.get(c`/evals/${r}/runs/${i}/output_items/${e}`,s)}list(e,t,s){const{eval_id:r,...i}=t;return this._client.getAPIList(c`/evals/${r}/runs/${e}/output_items`,I,{query:i,...s})}}class os extends g{constructor(){super(...arguments),this.outputItems=new Gn(this._client)}create(e,t,s){return this._client.post(c`/evals/${e}/runs`,{body:t,...s})}retrieve(e,t,s){const{eval_id:r}=t;return this._client.get(c`/evals/${r}/runs/${e}`,s)}list(e,t={},s){return this._client.getAPIList(c`/evals/${e}/runs`,I,{query:t,...s})}delete(e,t,s){const{eval_id:r}=t;return this._client.delete(c`/evals/${r}/runs/${e}`,s)}cancel(e,t,s){const{eval_id:r}=t;return this._client.post(c`/evals/${r}/runs/${e}`,s)}}os.OutputItems=Gn;class ls extends g{constructor(){super(...arguments),this.runs=new os(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(c`/evals/${e}`,t)}update(e,t,s){return this._client.post(c`/evals/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/evals",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/evals/${e}`,t)}}ls.Runs=os;let Yn=class extends g{create(e,t){return this._client.post("/files",pe({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/files/${e}`,t)}content(e,t){return this._client.get(c`/files/${e}/content`,{...t,headers:p([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=1800*1e3}={}){const r=new Set(["processed","error","deleted"]),i=Date.now();let a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await Pe(t),a=await this.retrieve(e),Date.now()-i>s)throw new lt({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return a}};class Zn extends g{}let er=class extends g{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class cs extends g{constructor(){super(...arguments),this.graders=new er(this._client)}}cs.Graders=er;class tr extends g{create(e,t,s){return this._client.getAPIList(c`/fine_tuning/checkpoints/${e}/permissions`,ut,{body:t,method:"post",...s})}retrieve(e,t={},s){return this._client.get(c`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s})}delete(e,t,s){const{fine_tuned_model_checkpoint:r}=t;return this._client.delete(c`/fine_tuning/checkpoints/${r}/permissions/${e}`,s)}}let us=class extends g{constructor(){super(...arguments),this.permissions=new tr(this._client)}};us.Permissions=tr;class sr extends g{list(e,t={},s){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/checkpoints`,I,{query:t,...s})}}class hs extends g{constructor(){super(...arguments),this.checkpoints=new sr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(c`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",I,{query:e,...t})}cancel(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/events`,I,{query:t,...s})}pause(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/resume`,t)}}hs.Checkpoints=sr;class _e extends g{constructor(){super(...arguments),this.methods=new Zn(this._client),this.jobs=new hs(this._client),this.checkpoints=new us(this._client),this.alpha=new cs(this._client)}}_e.Methods=Zn;_e.Jobs=hs;_e.Checkpoints=us;_e.Alpha=cs;class nr extends g{}class ds extends g{constructor(){super(...arguments),this.graderModels=new nr(this._client)}}ds.GraderModels=nr;class rr extends g{createVariation(e,t){return this._client.post("/images/variations",pe({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",pe({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class ir extends g{retrieve(e,t){return this._client.get(c`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ut,e)}delete(e,t){return this._client.delete(c`/models/${e}`,t)}}class ar extends g{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class or extends g{accept(e,t,s){return this._client.post(c`/realtime/calls/${e}/accept`,{body:t,...s,headers:p([{Accept:"*/*"},s?.headers])})}hangup(e,t){return this._client.post(c`/realtime/calls/${e}/hangup`,{...t,headers:p([{Accept:"*/*"},t?.headers])})}refer(e,t,s){return this._client.post(c`/realtime/calls/${e}/refer`,{body:t,...s,headers:p([{Accept:"*/*"},s?.headers])})}reject(e,t={},s){return this._client.post(c`/realtime/calls/${e}/reject`,{body:t,...s,headers:p([{Accept:"*/*"},s?.headers])})}}class lr extends g{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class pt extends g{constructor(){super(...arguments),this.clientSecrets=new lr(this._client),this.calls=new or(this._client)}}pt.ClientSecrets=lr;pt.Calls=or;function gi(n,e){return!e||!wi(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(s=>({...s,parsed:null}))}:t)}:cr(n,e)}function cr(n,e){const t=n.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:Ai(e,r)};if(r.type==="message"){const i=r.content.map(a=>a.type==="output_text"?{...a,parsed:yi(e,a.text)}:a);return{...r,content:i}}return r}),s=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Bt(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const r of s.output)if(r.type==="message"){for(const i of r.content)if(i.type==="output_text"&&i.parsed!==null)return i.parsed}return null}}),s}function yi(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function wi(n){return!!Gt(n.text?.format)}function bi(n){return n?.$brand==="auto-parseable-tool"}function Si(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function Ai(n,e){const t=Si(n.tools??[],e.name);return{...e,...e,parsed_arguments:bi(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Bt(n){const e=[];for(const t of n.output)if(t.type==="message")for(const s of t.content)s.type==="output_text"&&e.push(s.text);n.output_text=e.join("")}var le,We,se,qe,qs,js,Hs,Js;class fs extends Zt{constructor(e){super(),le.add(this),We.set(this,void 0),se.set(this,void 0),qe.set(this,void 0),S(this,We,e)}static createResponse(e,t,s){const r=new fs(t);return r._run(()=>r._createOrRetrieveResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),o(this,le,"m",qs).call(this);let i,a=null;"response_id"in t?(i=await e.responses.retrieve(t.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):i=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const l of i)o(this,le,"m",js).call(this,l,a);if(i.controller.signal?.aborted)throw new X;return o(this,le,"m",Hs).call(this)}[(We=new WeakMap,se=new WeakMap,qe=new WeakMap,le=new WeakSet,qs=function(){this.ended||S(this,se,void 0)},js=function(t,s){if(this.ended)return;const r=(a,l)=>{(s==null||l.sequence_number>s)&&this._emit(a,l)},i=o(this,le,"m",Js).call(this,t);switch(r("event",t),t.type){case"response.output_text.delta":{const a=i.output[t.output_index];if(!a)throw new _(`missing output at index ${t.output_index}`);if(a.type==="message"){const l=a.content[t.content_index];if(!l)throw new _(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new _(`expected content to be 'output_text', got ${l.type}`);r("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{const a=i.output[t.output_index];if(!a)throw new _(`missing output at index ${t.output_index}`);a.type==="function_call"&&r("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:r(t.type,t);break}},Hs=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");const t=o(this,se,"f");if(!t)throw new _("request ended without sending any events");S(this,se,void 0);const s=xi(t,o(this,We,"f"));return S(this,qe,s),s},Js=function(t){let s=o(this,se,"f");if(!s){if(t.type!=="response.created")throw new _(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return s=S(this,se,t.response),s}switch(t.type){case"response.output_item.added":{s.output.push(t.item);break}case"response.content_part.added":{const r=s.output[t.output_index];if(!r)throw new _(`missing output at index ${t.output_index}`);const i=r.type,a=t.part;i==="message"&&a.type!=="reasoning_text"?r.content.push(a):i==="reasoning"&&a.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(a));break}case"response.output_text.delta":{const r=s.output[t.output_index];if(!r)throw new _(`missing output at index ${t.output_index}`);if(r.type==="message"){const i=r.content[t.content_index];if(!i)throw new _(`missing content at index ${t.content_index}`);if(i.type!=="output_text")throw new _(`expected content to be 'output_text', got ${i.type}`);i.text+=t.delta}break}case"response.function_call_arguments.delta":{const r=s.output[t.output_index];if(!r)throw new _(`missing output at index ${t.output_index}`);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.reasoning_text.delta":{const r=s.output[t.output_index];if(!r)throw new _(`missing output at index ${t.output_index}`);if(r.type==="reasoning"){const i=r.content?.[t.content_index];if(!i)throw new _(`missing content at index ${t.content_index}`);if(i.type!=="reasoning_text")throw new _(`expected content to be 'reasoning_text', got ${i.type}`);i.text+=t.delta}break}case"response.completed":{S(this,se,t.response);break}}return s},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=o(this,qe,"f");if(!e)throw new _("stream ended without producing a ChatCompletion");return e}}function xi(n,e){return gi(n,e)}class ur extends g{list(e,t={},s){return this._client.getAPIList(c`/responses/${e}/input_items`,I,{query:t,...s})}}class hr extends g{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class mt extends g{constructor(){super(...arguments),this.inputItems=new ur(this._client),this.inputTokens=new hr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Bt(s),s))}retrieve(e,t={},s){return this._client.get(c`/responses/${e}`,{query:t,...s,stream:t?.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Bt(r),r))}delete(e,t){return this._client.delete(c`/responses/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(s=>cr(s,e))}stream(e,t){return fs.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(c`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}}mt.InputItems=ur;mt.InputTokens=hr;let dr=class extends g{retrieve(e,t){return this._client.get(c`/skills/${e}/content`,{...t,headers:p([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}};class fr extends g{retrieve(e,t,s){const{skill_id:r}=t;return this._client.get(c`/skills/${r}/versions/${e}/content`,{...s,headers:p([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}class ps extends g{constructor(){super(...arguments),this.content=new fr(this._client)}create(e,t={},s){return this._client.post(c`/skills/${e}/versions`,Ee({body:t,...s},this._client))}retrieve(e,t,s){const{skill_id:r}=t;return this._client.get(c`/skills/${r}/versions/${e}`,s)}list(e,t={},s){return this._client.getAPIList(c`/skills/${e}/versions`,I,{query:t,...s})}delete(e,t,s){const{skill_id:r}=t;return this._client.delete(c`/skills/${r}/versions/${e}`,s)}}ps.Content=fr;class _t extends g{constructor(){super(...arguments),this.content=new dr(this._client),this.versions=new ps(this._client)}create(e={},t){return this._client.post("/skills",Ee({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/skills/${e}`,t)}update(e,t,s){return this._client.post(c`/skills/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/skills",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/skills/${e}`,t)}}_t.Content=dr;_t.Versions=ps;class pr extends g{create(e,t,s){return this._client.post(c`/uploads/${e}/parts`,pe({body:t,...s},this._client))}}class ms extends g{constructor(){super(...arguments),this.parts=new pr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(c`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(c`/uploads/${e}/complete`,{body:t,...s})}}ms.Parts=pr;const Ri=async n=>{const e=await Promise.allSettled(n),t=e.filter(r=>r.status==="rejected");if(t.length){for(const r of t)console.error(r.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const s=[];for(const r of e)r.status==="fulfilled"&&s.push(r.value);return s};class mr extends g{create(e,t,s){return this._client.post(c`/vector_stores/${e}/file_batches`,{body:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:r}=t;return this._client.get(c`/vector_stores/${r}/file_batches/${e}`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{vector_store_id:r}=t;return this._client.post(c`/vector_stores/${r}/file_batches/${e}/cancel`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const r=await this.create(e,t);return await this.poll(e,r.id,s)}listFiles(e,t,s){const{vector_store_id:r,...i}=t;return this._client.getAPIList(c`/vector_stores/${r}/file_batches/${e}/files`,I,{query:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,t,s){const r=p([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...s,headers:r}).withResponse();switch(i.status){case"in_progress":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{const h=a.headers.get("openai-poll-after-ms");if(h){const f=parseInt(h);isNaN(f)||(l=f)}}await Pe(l);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},r){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const i=r?.maxConcurrency??5,a=Math.min(i,t.length),l=this._client,h=t.values(),f=[...s];async function m(y){for(let u of y){const x=await l.files.create({file:u,purpose:"assistants"},r);f.push(x.id)}}const d=Array(a).fill(h).map(m);return await Ri(d),await this.createAndPoll(e,{file_ids:f})}}class _r extends g{create(e,t,s){return this._client.post(c`/vector_stores/${e}/files`,{body:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:r}=t;return this._client.get(c`/vector_stores/${r}/files/${e}`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{vector_store_id:r,...i}=t;return this._client.post(c`/vector_stores/${r}/files/${e}`,{body:i,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(c`/vector_stores/${e}/files`,I,{query:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{vector_store_id:r}=t;return this._client.delete(c`/vector_stores/${r}/files/${e}`,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const r=await this.create(e,t,s);return await this.poll(e,r.id,s)}async poll(e,t,s){const r=p([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const i=await this.retrieve(t,{vector_store_id:e},{...s,headers:r}).withResponse(),a=i.data;switch(a.status){case"in_progress":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{const h=i.response.headers.get("openai-poll-after-ms");if(h){const f=parseInt(h);isNaN(f)||(l=f)}}await Pe(l);break;case"failed":case"completed":return a}}}async upload(e,t,s){const r=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:r.id},s)}async uploadAndPoll(e,t,s){const r=await this.upload(e,t,s);return await this.poll(e,r.id,s)}content(e,t,s){const{vector_store_id:r}=t;return this._client.getAPIList(c`/vector_stores/${r}/files/${e}/content`,ut,{...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class gt extends g{constructor(){super(...arguments),this.files=new _r(this._client),this.fileBatches=new mr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(c`/vector_stores/${e}`,{body:t,...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",I,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,s){return this._client.getAPIList(c`/vector_stores/${e}/search`,ut,{body:t,method:"post",...s,headers:p([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}gt.Files=_r;gt.FileBatches=mr;class gr extends g{create(e,t){return this._client.post("/videos",Ee({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",et,{query:e,...t})}delete(e,t){return this._client.delete(c`/videos/${e}`,t)}downloadContent(e,t={},s){return this._client.get(c`/videos/${e}/content`,{query:t,...s,headers:p([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}remix(e,t,s){return this._client.post(c`/videos/${e}/remix`,Ee({body:t,...s},this._client))}}var he,yr,Ge;class wr extends g{constructor(){super(...arguments),he.add(this)}async unwrap(e,t,s=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,s,r),JSON.parse(e)}async verifySignature(e,t,s=this._client.webhookSecret,r=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");o(this,he,"m",yr).call(this,s);const i=p([t]).values,a=o(this,he,"m",Ge).call(this,i,"webhook-signature"),l=o(this,he,"m",Ge).call(this,i,"webhook-timestamp"),h=o(this,he,"m",Ge).call(this,i,"webhook-id"),f=parseInt(l,10);if(isNaN(f))throw new de("Invalid webhook timestamp format");const m=Math.floor(Date.now()/1e3);if(m-f>r)throw new de("Webhook timestamp is too old");if(f>m+r)throw new de("Webhook timestamp is too new");const d=a.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),y=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),u=h?`${h}.${l}.${e}`:`${l}.${e}`,x=await crypto.subtle.importKey("raw",y,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const b of d)try{const v=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",x,v,new TextEncoder().encode(u)))return}catch{continue}throw new de("The given webhook signature does not match the expected signature")}}he=new WeakSet,yr=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Ge=function(e,t){if(!e)throw new Error("Headers are required");const s=e.get(t);if(s==null)throw new Error(`Missing required header: ${t}`);return s};var Dt,_s,Ye,br;class A{constructor({baseURL:e=ee("OPENAI_BASE_URL"),apiKey:t=ee("OPENAI_API_KEY"),organization:s=ee("OPENAI_ORG_ID")??null,project:r=ee("OPENAI_PROJECT_ID")??null,webhookSecret:i=ee("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(Dt.add(this),Ye.set(this,void 0),this.completions=new Kn(this),this.chat=new ss(this),this.embeddings=new Qn(this),this.files=new Yn(this),this.images=new rr(this),this.audio=new Me(this),this.moderations=new ar(this),this.models=new ir(this),this.fineTuning=new _e(this),this.graders=new ds(this),this.vectorStores=new gt(this),this.webhooks=new wr(this),this.beta=new me(this),this.batches=new Dn(this),this.uploads=new ms(this),this.responses=new mt(this),this.realtime=new pt(this),this.conversations=new as(this),this.evals=new ls(this),this.containers=new is(this),this.skills=new _t(this),this.videos=new gr(this),t===void 0)throw new _("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const l={apiKey:t,organization:s,project:r,webhookSecret:i,...a,baseURL:e||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&vr())throw new _(`It looks like you're running in a browser-like environment.
|
|
15
|
+
|
|
16
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
17
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
18
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
19
|
+
|
|
20
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
21
|
+
|
|
22
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
23
|
+
`);this.baseURL=l.baseURL,this.timeout=l.timeout??_s.DEFAULT_TIMEOUT,this.logger=l.logger??console;const h="warn";this.logLevel=h,this.logLevel=Es(l.logLevel,"ClientOptions.logLevel",this)??Es(ee("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??h,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??Tr(),S(this,Ye,Mr),this._options=l,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=s,this.project=r,this.webhookSecret=i}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return p([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Wr(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${ce}`}defaultIdempotencyKey(){return`stainless-node-retry-${Xs()}`}makeStatusError(e,t,s,r){return F.generate(e,t,s,r)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(s){throw s instanceof _?s:new _(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof t!="string"||!t)throw new _(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,s){const r=!o(this,Dt,"m",br).call(this)&&s||this.baseURL,i=xr(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return Rr(a)||(t={...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:s}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new Te(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const r=await e,i=r.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(r);const{req:a,url:l,timeout:h}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:l,options:r});const f="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=s===void 0?"":`, retryOf: ${s}`,d=Date.now();if(B(this).debug(`[${f}] sending request`,ne({retryOfRequestLogID:s,method:r.method,url:l,options:r,headers:a.headers})),r.signal?.aborted)throw new X;const y=new AbortController,u=await this.fetchWithTimeout(l,a,h,y).catch($t),x=Date.now();if(u instanceof globalThis.Error){const R=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new X;const w=It(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return B(this).info(`[${f}] connection ${w?"timed out":"failed"} - ${R}`),B(this).debug(`[${f}] connection ${w?"timed out":"failed"} (${R})`,ne({retryOfRequestLogID:s,url:l,durationMs:x-d,message:u.message})),this.retryRequest(r,t,s??f);throw B(this).info(`[${f}] connection ${w?"timed out":"failed"} - error; no more retries left`),B(this).debug(`[${f}] connection ${w?"timed out":"failed"} (error; no more retries left)`,ne({retryOfRequestLogID:s,url:l,durationMs:x-d,message:u.message})),w?new lt:new Oe({cause:u})}const b=[...u.headers.entries()].filter(([R])=>R==="x-request-id").map(([R,w])=>", "+R+": "+JSON.stringify(w)).join(""),v=`[${f}${m}${b}] ${a.method} ${l} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${x-d}ms`;if(!u.ok){const R=await this.shouldRetry(u);if(t&&R){const $=`retrying, ${t} attempts remaining`;return await Nr(u.body),B(this).info(`${v} - ${$}`),B(this).debug(`[${f}] response error (${$})`,ne({retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:x-d})),this.retryRequest(r,t,s??f,u.headers)}const w=R?"error; no more retries left":"error; not retryable";B(this).info(`${v} - ${w}`);const T=await u.text().catch($=>$t($).message),C=$r(T),K=C?void 0:T;throw B(this).debug(`[${f}] response error (${w})`,ne({retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,message:K,durationMs:Date.now()-d})),this.makeStatusError(u.status,C,K,u.headers)}return B(this).info(v),B(this).debug(`[${f}] response start`,ne({retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:x-d})),{response:u,options:r,controller:y,requestLogID:f,retryOfRequestLogID:s,startTime:d}}getAPIList(e,t,s){return this.requestAPIList(t,s&&"then"in s?s.then(r=>({method:"get",path:e,...r})):{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new on(this,s,e)}async fetchWithTimeout(e,t,s,r){const{signal:i,method:a,...l}=t||{},h=this._makeAbort(r);i&&i.addEventListener("abort",h,{once:!0});const f=setTimeout(h,s),m=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,d={signal:r.signal,...m?{duplex:"half"}:{},method:"GET",...l};a&&(d.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(f)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,s,r){let i;const a=r?.get("retry-after-ms");if(a){const h=parseFloat(a);Number.isNaN(h)||(i=h)}const l=r?.get("retry-after");if(l&&!i){const h=parseFloat(l);Number.isNaN(h)?i=Date.parse(l)-Date.now():i=h*1e3}if(!(i&&0<=i&&i<60*1e3)){const h=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,h)}return await Pe(i),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,a=Math.min(.5*Math.pow(2,i),8),l=1-Math.random()*.25;return a*l*1e3}async buildRequest(e,{retryCount:t=0}={}){const s={...e},{method:r,path:i,query:a,defaultBaseURL:l}=s,h=this.buildURL(i,a,l);"timeout"in s&&Ir("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:f,body:m}=this.buildBody({options:s}),d=await this.buildHeaders({options:e,method:r,bodyHeaders:f,retryCount:t});return{req:{method:r,headers:d,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...s.fetchOptions??{}},url:h,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:r}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=p([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Pr(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=p([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Gs(e)}:typeof e=="object"&&s.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:o(this,Ye,"f").call(this,{body:e,headers:s})}}_s=A,Ye=new WeakMap,Dt=new WeakSet,br=function(){return this.baseURL!=="https://api.openai.com/v1"};A.OpenAI=_s;A.DEFAULT_TIMEOUT=6e5;A.OpenAIError=_;A.APIError=F;A.APIConnectionError=Oe;A.APIConnectionTimeoutError=lt;A.APIUserAbortError=X;A.NotFoundError=jt;A.ConflictError=Ht;A.RateLimitError=Xt;A.BadRequestError=Ut;A.AuthenticationError=Wt;A.InternalServerError=Kt;A.PermissionDeniedError=qt;A.UnprocessableEntityError=Jt;A.InvalidWebhookSignatureError=de;A.toFile=dn;A.Completions=Kn;A.Chat=ss;A.Embeddings=Qn;A.Files=Yn;A.Images=rr;A.Audio=Me;A.Moderations=ar;A.Models=ir;A.FineTuning=_e;A.Graders=ds;A.VectorStores=gt;A.Webhooks=wr;A.Beta=me;A.Batches=Dn;A.Uploads=ms;A.Responses=mt;A.Realtime=pt;A.Conversations=as;A.Evals=ls;A.Containers=is;A.Skills=_t;A.Videos=gr;class Ci extends A{constructor({baseURL:e=ee("OPENAI_BASE_URL"),apiKey:t=ee("AZURE_OPENAI_API_KEY"),apiVersion:s=ee("OPENAI_API_VERSION"),endpoint:r,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:l,...h}={}){if(!s)throw new _("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof a=="function"&&(l=!0),!a&&!t)throw new _("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new _("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(h.defaultQuery={...h.defaultQuery,"api-version":s},e){if(r)throw new _("baseURL and endpoint are mutually exclusive")}else{if(r||(r=process.env.AZURE_OPENAI_ENDPOINT),!r)throw new _("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${r}/openai`}super({apiKey:a??t,baseURL:e,...h,...l!==void 0?{dangerouslyAllowBrowser:l}:{}}),this.apiVersion="",this.apiVersion=s,this.deploymentName=i}async buildRequest(e,t={}){if(Ii.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!je(e.body))throw new Error("Expected request body to be an object");const s=this.deploymentName||e.body.model||e.__metadata?.model;s!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${s}${e.path}`)}return super.buildRequest(e,t)}async authHeaders(e){return typeof this._options.apiKey=="string"?p([{"api-key":this.apiKey}]):super.authHeaders(e)}}const Ii=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);exports.APIConnectionError=Oe;exports.APIConnectionTimeoutError=lt;exports.APIError=F;exports.APIPromise=Te;exports.APIUserAbortError=X;exports.AuthenticationError=Wt;exports.AzureOpenAI=Ci;exports.BadRequestError=Ut;exports.ConflictError=Ht;exports.InternalServerError=Kt;exports.InvalidWebhookSignatureError=de;exports.NotFoundError=jt;exports.OpenAI=A;exports.OpenAIError=_;exports.PagePromise=on;exports.PermissionDeniedError=qt;exports.RateLimitError=Xt;exports.UnprocessableEntityError=Jt;exports.default=A;exports.toFile=dn;
|