import OpenAI from "openai"; const client = new OpenAI({ baseURL: process.env.AMPERSAND_BASE_URL, apiKey: process.env.AMPERSAND_API_KEY, maxRetries: 0, }); const stream = await client.beta.agents.sessions.create({ agent: { model: process.env.AMPERSAND_MODEL, instructions: "Answer the user in text.", }, environment: {type: "none"}, input: "Suggest three checks before a product launch.", stream: true, }, {signal: AbortSignal.timeout(120_000)}); try { for await (const event of stream.withResultCollection()) { if (event.type === "agent.session.created") { console.log(`Session: ${event.session.id}`); } // Breaking this loop closes the stream. Wait for idle so finalResult has the full turn. if (["agent.session.idle", "agent.session.failed", "agent.session.requires_action"].includes(event.type)) break; if (["agent.session.turn.failed", "agent.session.turn.cancelled"].includes(event.type)) { throw new Error(`Turn ${event.turn_id}: ${JSON.stringify(event.turn.error)}`); } } const result = await stream.finalResult(); console.log(result.output_text); } finally { stream.controller.abort(); }