import OpenAI from "openai"; import { ResponseToChatStreamConverter } from "./response-to-chat-stream-converter"; /** * Direct Response API to Chat Completion chunk conversion example */ async function directResponseToChat() { const openai = new OpenAI({ apiKey: "[OPENAI_API_KEY]", }); console.log( "=== Converting Response API stream to Chat Completion chunks ===" ); // Create response stream directly const stream = await openai.responses.create({ // ...params, model: "gpt-5-nano", reasoning: { effort: "low", summary: "auto" }, input: [ { role: "user", content: "Use the get_time tool for the city=San Francisco, and NYC.", }, ], include: ["reasoning.encrypted_content"], store: false, stream: true, tools: [ { type: "function", name: "get_time", description: "Get the current local time in a city.", strict: true, parameters: { type: "object", properties: { city: { type: "string", description: "City name, e.g. San Francisco", }, }, required: ["city"], additionalProperties: false, }, }, ], tool_choice: "auto", }); // Create converter const converter = new ResponseToChatStreamConverter("gpt-5-nano"); // Process each event and print converted chunks for await (const event of stream as any) { const chunks = converter.convertEvent(event); for (const chunk of chunks) { const toolCalls = chunk.choices[0].delta.tool_calls; if (toolCalls) { console.log(toolCalls); } else { console.log(chunk.choices[0].delta); } const usage = chunk.usage; if (usage) { console.log(usage); } const encryptedReasoning = chunk.encrypted_reasoning; if (encryptedReasoning) { console.log(encryptedReasoning); } } } console.log("\nStream conversion completed!"); } // Run example if this file is executed directly console.log("Running stream conversion example...\n"); directResponseToChat() .then(() => { console.log("\nExample completed!"); }) .catch((error) => { console.error("Example error:", error); });