ChatCompletionStream.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. "use strict";
  2. var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
  3. if (kind === "m") throw new TypeError("Private method is not writable");
  4. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  5. if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  6. return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
  7. };
  8. var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
  9. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  10. if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  11. return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
  12. };
  13. var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion;
  14. Object.defineProperty(exports, "__esModule", { value: true });
  15. exports.ChatCompletionStream = void 0;
  16. const error_1 = require("../error.js");
  17. const AbstractChatCompletionRunner_1 = require("./AbstractChatCompletionRunner.js");
  18. const streaming_1 = require("../streaming.js");
  19. const parser_1 = require("../lib/parser.js");
  20. const parser_2 = require("../_vendor/partial-json-parser/parser.js");
  21. class ChatCompletionStream extends AbstractChatCompletionRunner_1.AbstractChatCompletionRunner {
  22. constructor(params) {
  23. super();
  24. _ChatCompletionStream_instances.add(this);
  25. _ChatCompletionStream_params.set(this, void 0);
  26. _ChatCompletionStream_choiceEventStates.set(this, void 0);
  27. _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0);
  28. __classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f");
  29. __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
  30. }
  31. get currentChatCompletionSnapshot() {
  32. return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
  33. }
  34. /**
  35. * Intended for use on the frontend, consuming a stream produced with
  36. * `.toReadableStream()` on the backend.
  37. *
  38. * Note that messages sent to the model do not appear in `.on('message')`
  39. * in this context.
  40. */
  41. static fromReadableStream(stream) {
  42. const runner = new ChatCompletionStream(null);
  43. runner._run(() => runner._fromReadableStream(stream));
  44. return runner;
  45. }
  46. static createChatCompletion(client, params, options) {
  47. const runner = new ChatCompletionStream(params);
  48. runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } }));
  49. return runner;
  50. }
  51. async _createChatCompletion(client, params, options) {
  52. super._createChatCompletion;
  53. const signal = options?.signal;
  54. if (signal) {
  55. if (signal.aborted)
  56. this.controller.abort();
  57. signal.addEventListener('abort', () => this.controller.abort());
  58. }
  59. __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
  60. const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
  61. this._connected();
  62. for await (const chunk of stream) {
  63. __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
  64. }
  65. if (stream.controller.signal?.aborted) {
  66. throw new error_1.APIUserAbortError();
  67. }
  68. return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
  69. }
  70. async _fromReadableStream(readableStream, options) {
  71. const signal = options?.signal;
  72. if (signal) {
  73. if (signal.aborted)
  74. this.controller.abort();
  75. signal.addEventListener('abort', () => this.controller.abort());
  76. }
  77. __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
  78. this._connected();
  79. const stream = streaming_1.Stream.fromReadableStream(readableStream, this.controller);
  80. let chatId;
  81. for await (const chunk of stream) {
  82. if (chatId && chatId !== chunk.id) {
  83. // A new request has been made.
  84. this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
  85. }
  86. __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
  87. chatId = chunk.id;
  88. }
  89. if (stream.controller.signal?.aborted) {
  90. throw new error_1.APIUserAbortError();
  91. }
  92. return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
  93. }
  94. [(_ChatCompletionStream_params = new WeakMap(), _ChatCompletionStream_choiceEventStates = new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() {
  95. if (this.ended)
  96. return;
  97. __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
  98. }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) {
  99. let state = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
  100. if (state) {
  101. return state;
  102. }
  103. state = {
  104. content_done: false,
  105. refusal_done: false,
  106. logprobs_content_done: false,
  107. logprobs_refusal_done: false,
  108. done_tool_calls: new Set(),
  109. current_tool_call_index: null,
  110. };
  111. __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state;
  112. return state;
  113. }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) {
  114. if (this.ended)
  115. return;
  116. const completion = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk);
  117. this._emit('chunk', chunk, completion);
  118. for (const choice of chunk.choices) {
  119. const choiceSnapshot = completion.choices[choice.index];
  120. if (choice.delta.content != null &&
  121. choiceSnapshot.message?.role === 'assistant' &&
  122. choiceSnapshot.message?.content) {
  123. this._emit('content', choice.delta.content, choiceSnapshot.message.content);
  124. this._emit('content.delta', {
  125. delta: choice.delta.content,
  126. snapshot: choiceSnapshot.message.content,
  127. parsed: choiceSnapshot.message.parsed,
  128. });
  129. }
  130. if (choice.delta.refusal != null &&
  131. choiceSnapshot.message?.role === 'assistant' &&
  132. choiceSnapshot.message?.refusal) {
  133. this._emit('refusal.delta', {
  134. delta: choice.delta.refusal,
  135. snapshot: choiceSnapshot.message.refusal,
  136. });
  137. }
  138. if (choice.logprobs?.content != null && choiceSnapshot.message?.role === 'assistant') {
  139. this._emit('logprobs.content.delta', {
  140. content: choice.logprobs?.content,
  141. snapshot: choiceSnapshot.logprobs?.content ?? [],
  142. });
  143. }
  144. if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === 'assistant') {
  145. this._emit('logprobs.refusal.delta', {
  146. refusal: choice.logprobs?.refusal,
  147. snapshot: choiceSnapshot.logprobs?.refusal ?? [],
  148. });
  149. }
  150. const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
  151. if (choiceSnapshot.finish_reason) {
  152. __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
  153. if (state.current_tool_call_index != null) {
  154. __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
  155. }
  156. }
  157. for (const toolCall of choice.delta.tool_calls ?? []) {
  158. if (state.current_tool_call_index !== toolCall.index) {
  159. __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
  160. // new tool call started, the previous one is done
  161. if (state.current_tool_call_index != null) {
  162. __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
  163. }
  164. }
  165. state.current_tool_call_index = toolCall.index;
  166. }
  167. for (const toolCallDelta of choice.delta.tool_calls ?? []) {
  168. const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index];
  169. if (!toolCallSnapshot?.type) {
  170. continue;
  171. }
  172. if (toolCallSnapshot?.type === 'function') {
  173. this._emit('tool_calls.function.arguments.delta', {
  174. name: toolCallSnapshot.function?.name,
  175. index: toolCallDelta.index,
  176. arguments: toolCallSnapshot.function.arguments,
  177. parsed_arguments: toolCallSnapshot.function.parsed_arguments,
  178. arguments_delta: toolCallDelta.function?.arguments ?? '',
  179. });
  180. }
  181. else {
  182. assertNever(toolCallSnapshot?.type);
  183. }
  184. }
  185. }
  186. }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) {
  187. const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
  188. if (state.done_tool_calls.has(toolCallIndex)) {
  189. // we've already fired the done event
  190. return;
  191. }
  192. const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex];
  193. if (!toolCallSnapshot) {
  194. throw new Error('no tool call snapshot');
  195. }
  196. if (!toolCallSnapshot.type) {
  197. throw new Error('tool call snapshot missing `type`');
  198. }
  199. if (toolCallSnapshot.type === 'function') {
  200. const inputTool = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => tool.type === 'function' && tool.function.name === toolCallSnapshot.function.name);
  201. this._emit('tool_calls.function.arguments.done', {
  202. name: toolCallSnapshot.function.name,
  203. index: toolCallIndex,
  204. arguments: toolCallSnapshot.function.arguments,
  205. parsed_arguments: (0, parser_1.isAutoParsableTool)(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments)
  206. : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments)
  207. : null,
  208. });
  209. }
  210. else {
  211. assertNever(toolCallSnapshot.type);
  212. }
  213. }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) {
  214. const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
  215. if (choiceSnapshot.message.content && !state.content_done) {
  216. state.content_done = true;
  217. const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this);
  218. this._emit('content.done', {
  219. content: choiceSnapshot.message.content,
  220. parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null,
  221. });
  222. }
  223. if (choiceSnapshot.message.refusal && !state.refusal_done) {
  224. state.refusal_done = true;
  225. this._emit('refusal.done', { refusal: choiceSnapshot.message.refusal });
  226. }
  227. if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) {
  228. state.logprobs_content_done = true;
  229. this._emit('logprobs.content.done', { content: choiceSnapshot.logprobs.content });
  230. }
  231. if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) {
  232. state.logprobs_refusal_done = true;
  233. this._emit('logprobs.refusal.done', { refusal: choiceSnapshot.logprobs.refusal });
  234. }
  235. }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() {
  236. if (this.ended) {
  237. throw new error_1.OpenAIError(`stream has ended, this shouldn't happen`);
  238. }
  239. const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
  240. if (!snapshot) {
  241. throw new error_1.OpenAIError(`request ended without sending any chunks`);
  242. }
  243. __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
  244. __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
  245. return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, "f"));
  246. }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() {
  247. const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format;
  248. if ((0, parser_1.isAutoParsableResponseFormat)(responseFormat)) {
  249. return responseFormat;
  250. }
  251. return null;
  252. }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) {
  253. var _a, _b, _c, _d;
  254. let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
  255. const { choices, ...rest } = chunk;
  256. if (!snapshot) {
  257. snapshot = __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, {
  258. ...rest,
  259. choices: [],
  260. }, "f");
  261. }
  262. else {
  263. Object.assign(snapshot, rest);
  264. }
  265. for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) {
  266. let choice = snapshot.choices[index];
  267. if (!choice) {
  268. choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other };
  269. }
  270. if (logprobs) {
  271. if (!choice.logprobs) {
  272. choice.logprobs = Object.assign({}, logprobs);
  273. }
  274. else {
  275. const { content, refusal, ...rest } = logprobs;
  276. assertIsEmpty(rest);
  277. Object.assign(choice.logprobs, rest);
  278. if (content) {
  279. (_a = choice.logprobs).content ?? (_a.content = []);
  280. choice.logprobs.content.push(...content);
  281. }
  282. if (refusal) {
  283. (_b = choice.logprobs).refusal ?? (_b.refusal = []);
  284. choice.logprobs.refusal.push(...refusal);
  285. }
  286. }
  287. }
  288. if (finish_reason) {
  289. choice.finish_reason = finish_reason;
  290. if (__classPrivateFieldGet(this, _ChatCompletionStream_params, "f") && (0, parser_1.hasAutoParseableInput)(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"))) {
  291. if (finish_reason === 'length') {
  292. throw new error_1.LengthFinishReasonError();
  293. }
  294. if (finish_reason === 'content_filter') {
  295. throw new error_1.ContentFilterFinishReasonError();
  296. }
  297. }
  298. }
  299. Object.assign(choice, other);
  300. if (!delta)
  301. continue; // Shouldn't happen; just in case.
  302. const { content, refusal, function_call, role, tool_calls, ...rest } = delta;
  303. assertIsEmpty(rest);
  304. Object.assign(choice.message, rest);
  305. if (refusal) {
  306. choice.message.refusal = (choice.message.refusal || '') + refusal;
  307. }
  308. if (role)
  309. choice.message.role = role;
  310. if (function_call) {
  311. if (!choice.message.function_call) {
  312. choice.message.function_call = function_call;
  313. }
  314. else {
  315. if (function_call.name)
  316. choice.message.function_call.name = function_call.name;
  317. if (function_call.arguments) {
  318. (_c = choice.message.function_call).arguments ?? (_c.arguments = '');
  319. choice.message.function_call.arguments += function_call.arguments;
  320. }
  321. }
  322. }
  323. if (content) {
  324. choice.message.content = (choice.message.content || '') + content;
  325. if (!choice.message.refusal && __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {
  326. choice.message.parsed = (0, parser_2.partialParse)(choice.message.content);
  327. }
  328. }
  329. if (tool_calls) {
  330. if (!choice.message.tool_calls)
  331. choice.message.tool_calls = [];
  332. for (const { index, id, type, function: fn, ...rest } of tool_calls) {
  333. const tool_call = ((_d = choice.message.tool_calls)[index] ?? (_d[index] = {}));
  334. Object.assign(tool_call, rest);
  335. if (id)
  336. tool_call.id = id;
  337. if (type)
  338. tool_call.type = type;
  339. if (fn)
  340. tool_call.function ?? (tool_call.function = { name: fn.name ?? '', arguments: '' });
  341. if (fn?.name)
  342. tool_call.function.name = fn.name;
  343. if (fn?.arguments) {
  344. tool_call.function.arguments += fn.arguments;
  345. if ((0, parser_1.shouldParseToolCall)(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), tool_call)) {
  346. tool_call.function.parsed_arguments = (0, parser_2.partialParse)(tool_call.function.arguments);
  347. }
  348. }
  349. }
  350. }
  351. }
  352. return snapshot;
  353. }, Symbol.asyncIterator)]() {
  354. const pushQueue = [];
  355. const readQueue = [];
  356. let done = false;
  357. this.on('chunk', (chunk) => {
  358. const reader = readQueue.shift();
  359. if (reader) {
  360. reader.resolve(chunk);
  361. }
  362. else {
  363. pushQueue.push(chunk);
  364. }
  365. });
  366. this.on('end', () => {
  367. done = true;
  368. for (const reader of readQueue) {
  369. reader.resolve(undefined);
  370. }
  371. readQueue.length = 0;
  372. });
  373. this.on('abort', (err) => {
  374. done = true;
  375. for (const reader of readQueue) {
  376. reader.reject(err);
  377. }
  378. readQueue.length = 0;
  379. });
  380. this.on('error', (err) => {
  381. done = true;
  382. for (const reader of readQueue) {
  383. reader.reject(err);
  384. }
  385. readQueue.length = 0;
  386. });
  387. return {
  388. next: async () => {
  389. if (!pushQueue.length) {
  390. if (done) {
  391. return { value: undefined, done: true };
  392. }
  393. return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));
  394. }
  395. const chunk = pushQueue.shift();
  396. return { value: chunk, done: false };
  397. },
  398. return: async () => {
  399. this.abort();
  400. return { value: undefined, done: true };
  401. },
  402. };
  403. }
  404. toReadableStream() {
  405. const stream = new streaming_1.Stream(this[Symbol.asyncIterator].bind(this), this.controller);
  406. return stream.toReadableStream();
  407. }
  408. }
  409. exports.ChatCompletionStream = ChatCompletionStream;
  410. function finalizeChatCompletion(snapshot, params) {
  411. const { id, choices, created, model, system_fingerprint, ...rest } = snapshot;
  412. const completion = {
  413. ...rest,
  414. id,
  415. choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => {
  416. if (!finish_reason) {
  417. throw new error_1.OpenAIError(`missing finish_reason for choice ${index}`);
  418. }
  419. const { content = null, function_call, tool_calls, ...messageRest } = message;
  420. const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine.
  421. if (!role) {
  422. throw new error_1.OpenAIError(`missing role for choice ${index}`);
  423. }
  424. if (function_call) {
  425. const { arguments: args, name } = function_call;
  426. if (args == null) {
  427. throw new error_1.OpenAIError(`missing function_call.arguments for choice ${index}`);
  428. }
  429. if (!name) {
  430. throw new error_1.OpenAIError(`missing function_call.name for choice ${index}`);
  431. }
  432. return {
  433. ...choiceRest,
  434. message: {
  435. content,
  436. function_call: { arguments: args, name },
  437. role,
  438. refusal: message.refusal ?? null,
  439. },
  440. finish_reason,
  441. index,
  442. logprobs,
  443. };
  444. }
  445. if (tool_calls) {
  446. return {
  447. ...choiceRest,
  448. index,
  449. finish_reason,
  450. logprobs,
  451. message: {
  452. ...messageRest,
  453. role,
  454. content,
  455. refusal: message.refusal ?? null,
  456. tool_calls: tool_calls.map((tool_call, i) => {
  457. const { function: fn, type, id, ...toolRest } = tool_call;
  458. const { arguments: args, name, ...fnRest } = fn || {};
  459. if (id == null) {
  460. throw new error_1.OpenAIError(`missing choices[${index}].tool_calls[${i}].id\n${str(snapshot)}`);
  461. }
  462. if (type == null) {
  463. throw new error_1.OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`);
  464. }
  465. if (name == null) {
  466. throw new error_1.OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`);
  467. }
  468. if (args == null) {
  469. throw new error_1.OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`);
  470. }
  471. return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } };
  472. }),
  473. },
  474. };
  475. }
  476. return {
  477. ...choiceRest,
  478. message: { ...messageRest, content, role, refusal: message.refusal ?? null },
  479. finish_reason,
  480. index,
  481. logprobs,
  482. };
  483. }),
  484. created,
  485. model,
  486. object: 'chat.completion',
  487. ...(system_fingerprint ? { system_fingerprint } : {}),
  488. };
  489. return (0, parser_1.maybeParseChatCompletion)(completion, params);
  490. }
  491. function str(x) {
  492. return JSON.stringify(x);
  493. }
  494. /**
  495. * Ensures the given argument is an empty object, useful for
  496. * asserting that all known properties on an object have been
  497. * destructured.
  498. */
  499. function assertIsEmpty(obj) {
  500. return;
  501. }
  502. function assertNever(_x) { }
  503. //# sourceMappingURL=ChatCompletionStream.js.map