( output: OpenAI.Responses.ResponseOutputItem[] )
| 242 | * Converts Responses API output items into input items for subsequent calls. |
| 243 | */ |
| 244 | export function convertResponseOutputToInputItems( |
| 245 | output: OpenAI.Responses.ResponseOutputItem[] |
| 246 | ): ResponsesInputItem[] { |
| 247 | if (!Array.isArray(output)) { |
| 248 | return [] |
| 249 | } |
| 250 | |
| 251 | const items: ResponsesInputItem[] = [] |
| 252 | for (const item of output) { |
| 253 | if (!isRecord(item)) { |
| 254 | continue |
| 255 | } |
| 256 | |
| 257 | if (item.type === 'message') { |
| 258 | const text = extractTextFromMessageItem(item) |
| 259 | if (text) { |
| 260 | items.push({ |
| 261 | role: 'assistant', |
| 262 | content: text, |
| 263 | }) |
| 264 | } |
| 265 | |
| 266 | // Handle Chat Completions-style tool_calls nested under message items |
| 267 | const toolCalls = Array.isArray(item.tool_calls) ? item.tool_calls : [] |
| 268 | for (const toolCall of toolCalls) { |
| 269 | const tc = toolCall as Record<string, unknown> |
| 270 | const fn = tc.function as Record<string, unknown> | undefined |
| 271 | const callId = tc.id as string | undefined |
| 272 | const name = (fn?.name ?? tc.name) as string | undefined |
| 273 | if (!callId || !name) { |
| 274 | continue |
| 275 | } |
| 276 | |
| 277 | const argumentsValue = |
| 278 | typeof fn?.arguments === 'string' ? fn.arguments : JSON.stringify(fn?.arguments ?? {}) |
| 279 | |
| 280 | items.push({ |
| 281 | type: 'function_call', |
| 282 | call_id: callId, |
| 283 | name, |
| 284 | arguments: argumentsValue, |
| 285 | }) |
| 286 | } |
| 287 | |
| 288 | continue |
| 289 | } |
| 290 | |
| 291 | if (item.type === 'function_call') { |
| 292 | const fc = item as OpenAI.Responses.ResponseFunctionToolCall |
| 293 | const callId = fc.call_id ?? (typeof item.id === 'string' ? item.id : undefined) |
| 294 | const name = |
| 295 | fc.name ?? |
| 296 | (isRecord(item.function) && typeof item.function.name === 'string' |
| 297 | ? item.function.name |
| 298 | : undefined) |
| 299 | if (!callId || !name) { |
| 300 | continue |
| 301 | } |
no test coverage detected