openai-response-assembler.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import type { OpenAiMessage } from "./types.js";
  2. interface ToolCallAccumulator {
  3. function?: {
  4. arguments?: string;
  5. name?: string;
  6. };
  7. id?: string;
  8. type?: string;
  9. }
  10. export function assembleNonStreamingAssistantMessage(body: unknown): OpenAiMessage | null {
  11. const message = firstChoiceMessage(body);
  12. if (!message) return responseOutputMessage(body);
  13. return ensureAssistantRole(message);
  14. }
  15. export function assembleStreamingAssistantMessage(chunks: readonly (string | Uint8Array)[]): OpenAiMessage | null {
  16. const text = chunks
  17. .map((chunk) => (typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk)))
  18. .join("");
  19. let role = "assistant";
  20. let content = "";
  21. let reasoningContent = "";
  22. const toolCalls = new Map<number, ToolCallAccumulator>();
  23. for (const payload of parseSseDataPayloads(text)) {
  24. if (payload === "[DONE]") continue;
  25. const parsed = parseJson(payload);
  26. if (!parsed) continue;
  27. const delta = firstChoiceDelta(parsed);
  28. if (!delta) continue;
  29. if (typeof delta.role === "string") {
  30. role = delta.role;
  31. }
  32. if (typeof delta.content === "string") {
  33. content += delta.content;
  34. }
  35. if (typeof delta.reasoning_content === "string") {
  36. reasoningContent += delta.reasoning_content;
  37. }
  38. mergeToolCallDeltas(toolCalls, delta.tool_calls);
  39. }
  40. const message: OpenAiMessage = { role };
  41. if (content.length > 0 || toolCalls.size > 0) {
  42. message.content = content;
  43. }
  44. if (reasoningContent.length > 0) {
  45. message.reasoning_content = reasoningContent;
  46. }
  47. if (toolCalls.size > 0) {
  48. message.tool_calls = [...toolCalls.entries()]
  49. .sort(([left], [right]) => left - right)
  50. .map(([, toolCall]) => normalizeToolCall(toolCall));
  51. }
  52. return Object.keys(message).length > 1 || role === "assistant" ? message : null;
  53. }
  54. function firstChoiceMessage(body: unknown): OpenAiMessage | null {
  55. if (!body || typeof body !== "object") return null;
  56. const choices = (body as { choices?: unknown }).choices;
  57. if (!Array.isArray(choices)) return null;
  58. const first = choices[0];
  59. if (!first || typeof first !== "object") return null;
  60. const message = (first as { message?: unknown }).message;
  61. if (!message || typeof message !== "object" || Array.isArray(message)) return null;
  62. return message as OpenAiMessage;
  63. }
  64. function responseOutputMessage(body: unknown): OpenAiMessage | null {
  65. if (!body || typeof body !== "object") return null;
  66. const output = (body as { output?: unknown }).output;
  67. if (!Array.isArray(output)) return null;
  68. const functionCall = output.find(
  69. (item) =>
  70. item &&
  71. typeof item === "object" &&
  72. !Array.isArray(item) &&
  73. (item as { type?: unknown }).type === "function_call",
  74. ) as Record<string, unknown> | undefined;
  75. if (functionCall) {
  76. return {
  77. content: "",
  78. role: "assistant",
  79. tool_calls: [
  80. {
  81. id: typeof functionCall.call_id === "string" ? functionCall.call_id : undefined,
  82. type: "function",
  83. function: {
  84. arguments:
  85. typeof functionCall.arguments === "string" ? functionCall.arguments : "",
  86. name: typeof functionCall.name === "string" ? functionCall.name : "",
  87. },
  88. },
  89. ],
  90. };
  91. }
  92. const message = output.find(
  93. (item) =>
  94. item &&
  95. typeof item === "object" &&
  96. !Array.isArray(item) &&
  97. (item as { type?: unknown }).type === "message",
  98. ) as Record<string, unknown> | undefined;
  99. if (!message) return null;
  100. const content = Array.isArray(message.content)
  101. ? message.content
  102. .map((item) =>
  103. item &&
  104. typeof item === "object" &&
  105. !Array.isArray(item) &&
  106. typeof (item as { text?: unknown }).text === "string"
  107. ? ((item as { text: string }).text)
  108. : "",
  109. )
  110. .join("")
  111. : "";
  112. return {
  113. content,
  114. role: "assistant",
  115. };
  116. }
  117. function ensureAssistantRole(message: OpenAiMessage): OpenAiMessage {
  118. return {
  119. ...JSON.parse(JSON.stringify(message)),
  120. role: typeof message.role === "string" ? message.role : "assistant",
  121. };
  122. }
  123. function firstChoiceDelta(body: unknown): Record<string, unknown> | null {
  124. if (!body || typeof body !== "object") return null;
  125. const choices = (body as { choices?: unknown }).choices;
  126. if (!Array.isArray(choices)) return null;
  127. const first = choices[0];
  128. if (!first || typeof first !== "object") return null;
  129. const delta = (first as { delta?: unknown }).delta;
  130. if (!delta || typeof delta !== "object" || Array.isArray(delta)) return null;
  131. return delta as Record<string, unknown>;
  132. }
  133. function parseSseDataPayloads(text: string): string[] {
  134. return text
  135. .split(/\r?\n/u)
  136. .map((line) => line.trim())
  137. .filter((line) => line.startsWith("data:"))
  138. .map((line) => line.slice("data:".length).trim())
  139. .filter((payload) => payload.length > 0);
  140. }
  141. function parseJson(payload: string): unknown {
  142. try {
  143. return JSON.parse(payload);
  144. } catch {
  145. return null;
  146. }
  147. }
  148. function mergeToolCallDeltas(
  149. toolCalls: Map<number, ToolCallAccumulator>,
  150. deltas: unknown,
  151. ): void {
  152. if (!Array.isArray(deltas)) return;
  153. for (const delta of deltas) {
  154. if (!delta || typeof delta !== "object") continue;
  155. const record = delta as {
  156. function?: {
  157. arguments?: unknown;
  158. name?: unknown;
  159. };
  160. id?: unknown;
  161. index?: unknown;
  162. type?: unknown;
  163. };
  164. const index = typeof record.index === "number" ? record.index : toolCalls.size;
  165. const current = toolCalls.get(index) ?? {};
  166. if (typeof record.id === "string") {
  167. current.id = record.id;
  168. }
  169. if (typeof record.type === "string") {
  170. current.type = record.type;
  171. }
  172. if (record.function && typeof record.function === "object") {
  173. current.function = current.function ?? {};
  174. if (typeof record.function.name === "string") {
  175. current.function.name = `${current.function.name ?? ""}${record.function.name}`;
  176. }
  177. if (typeof record.function.arguments === "string") {
  178. current.function.arguments = `${current.function.arguments ?? ""}${record.function.arguments}`;
  179. }
  180. }
  181. toolCalls.set(index, current);
  182. }
  183. }
  184. function normalizeToolCall(toolCall: ToolCallAccumulator): Record<string, unknown> {
  185. return {
  186. ...(toolCall.id ? { id: toolCall.id } : {}),
  187. type: toolCall.type ?? "function",
  188. function: {
  189. name: toolCall.function?.name ?? "",
  190. arguments: toolCall.function?.arguments ?? "",
  191. },
  192. };
  193. }