UNPKG

aiwrapper

Version:

A Universal AI Wrapper for JavaScript & TypeScript

162 lines (161 loc) 6.58 kB
var __defProp = Object.defineProperty; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); import { LanguageProvider } from "../../language-provider.js"; import { LangMessage, LangMessages } from "../../messages.js"; import { prepareBodyPartForOpenAIResponsesAPI } from "./openai-responses-messages.js"; import { processServerEvents } from "../../../process-server-events.js"; import { OpenAIResponseStreamHandler } from "./openai-responses-stream-handler.js"; import { isZodSchema, validateAgainstSchema, zodToJsonSchema } from "../../schema/schema-utils.js"; import { models } from "aimodels"; import { httpRequestWithRetry as fetch } from "../../../http-request.js"; class OpenAIResponsesLang extends LanguageProvider { constructor(options) { var _a; super("OpenAI Responses"); __publicField(this, "model"); __publicField(this, "apiKey"); __publicField(this, "baseURL", "https://api.openai.com/v1"); __publicField(this, "reasoningEffort"); __publicField(this, "showReasoningSummary"); this.model = options.model; this.apiKey = options.apiKey; this.reasoningEffort = (_a = options.reasoningEffort) != null ? _a : "medium"; this.showReasoningSummary = options.showReasoningSummary !== void 0 ? options.showReasoningSummary : true; } async ask(prompt, options) { const messages = new LangMessages(); messages.push(new LangMessage("user", prompt)); return this.chat(messages, options); } async chat(messages, options) { const msgCollection = messages instanceof LangMessages ? messages : new LangMessages(messages); await this.sendToApi(msgCollection, options); return msgCollection; } buildStructuredOutput(schema) { if (!schema) { return void 0; } if (isZodSchema(schema)) { const jsonSchema = zodToJsonSchema(schema); return { text: { format: { type: "json_schema", name: "response_schema", schema: jsonSchema } } }; } else { return { type: "json_schema", json_schema: schema }; } } buildRequestBody(msgCollection, options) { const structuredOutput = this.buildStructuredOutput(options == null ? void 0 : options.schema); const bodyPart = prepareBodyPartForOpenAIResponsesAPI(msgCollection); const body = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({ model: this.model }, { stream: true }), bodyPart), { truncation: "auto" }), structuredOutput), options == null ? void 0 : options.providerSpecificBody); const modelInfo = models.id(this.model); if (modelInfo == null ? void 0 : modelInfo.canReason()) { body.reasoning = __spreadValues({ effort: this.reasoningEffort }, this.showReasoningSummary ? { summary: "auto" } : {}); } return body; } async sendToApi(msgCollection, options) { const abortSignal = options == null ? void 0 : options.signal; if (msgCollection.availableTools) { const tools = msgCollection.availableTools; const usesApplyPatch = tools.some((t) => t.name === "apply_patch"); if (usesApplyPatch) { const hasHandler = tools.some((t) => t.name === "apply_patch" && "handler" in t); if (!hasHandler) { throw new Error( "The apply_patch tool requires a handler. Please provide a handler function when defining the tool." ); } } } const body = this.buildRequestBody(msgCollection, options); const req = { method: "POST", headers: __spreadValues({ "Content-Type": "application/json", "Accept": "text/event-stream", Authorization: `Bearer ${this.apiKey}` }, options == null ? void 0 : options.providerSpecificHeaders), body: JSON.stringify(body), signal: abortSignal, on400Error: async (res, _error, reqOptions) => { var _a, _b, _c; const data = await res.text(); const dataObj = JSON.parse(data); if ((_b = (_a = dataObj.error) == null ? void 0 : _a.code) == null ? void 0 : _b.includes("previous_response_not_found")) { let lastMessageWithResponseId; for (let i = msgCollection.length - 1; i >= 0; i--) { if ((_c = msgCollection[i].meta) == null ? void 0 : _c.openaiResponseId) { lastMessageWithResponseId = msgCollection[i]; break; } } if (lastMessageWithResponseId) { delete lastMessageWithResponseId.meta.openaiResponseId; const newBody = this.buildRequestBody(msgCollection, options); reqOptions.body = JSON.stringify(newBody); } return { retry: true }; } throw new Error(data); } }; const streamHander = new OpenAIResponseStreamHandler(msgCollection, options == null ? void 0 : options.onResult); try { const response = await fetch(`${this.baseURL}/responses`, req); await processServerEvents(response, (data) => streamHander.handleEvent(data), abortSignal); } catch (error) { if ((error == null ? void 0 : error.name) === "AbortError") { msgCollection.aborted = true; error.partialResult = msgCollection; } throw error; } if (options == null ? void 0 : options.schema) { const validation = validateAgainstSchema(msgCollection.object, options.schema); if (!validation.valid) { throw new Error(`Schema validation failed: ${validation.errors.join(", ")}`); } } msgCollection.finished = true; const toolResults = await msgCollection.executeRequestedTools(); if ((options == null ? void 0 : options.onResult) && toolResults) { options.onResult(toolResults); } } } export { OpenAIResponsesLang }; //# sourceMappingURL=openai-responses-lang.js.map