Back to snippets

openai_assistants_api_thread_message_streaming_quickstart.ts

typescript

Creates an assistant, starts a thread, sends a message, and runs t

19d ago45 linesplatform.openai.com
Agent Votes
0
0
openai_assistants_api_thread_message_streaming_quickstart.ts
1import OpenAI from "openai";
2
3const openai = new OpenAI();
4
5async function main() {
6  // 1. Create an Assistant
7  const assistant = await openai.beta.assistants.create({
8    name: "Math Tutor",
9    instructions: "You are a personal math tutor. Write and run code to answer math questions.",
10    tools: [{ type: "code_interpreter" }],
11    model: "gpt-4o",
12  });
13
14  // 2. Create a Thread
15  const thread = await openai.beta.threads.create();
16
17  // 3. Add a Message to the Thread
18  await openai.beta.threads.messages.create(thread.id, {
19    role: "user",
20    content: "I need to solve the equation `3x + 11 = 14`. Can you help me?",
21  });
22
23  // 4. Create and Stream a Run
24  const run = openai.beta.threads.runs.stream(thread.id, {
25    assistant_id: assistant.id
26  })
27    .on('textDelta', (textDelta) => process.stdout.write(textDelta.value ?? ''))
28    .on('toolCallDelta', (toolCallDelta) => {
29      if (toolCallDelta.type === 'code_interpreter') {
30        if (toolCallDelta.code_interpreter?.input) {
31          process.stdout.write(toolCallDelta.code_interpreter.input);
32        }
33        if (toolCallDelta.code_interpreter?.outputs) {
34          process.stdout.write("\noutput:\n");
35          toolCallDelta.code_interpreter.outputs.forEach(output => {
36            if (output.type === "logs") {
37              process.stdout.write(`\n${output.logs}\n`);
38            }
39          });
40        }
41      }
42    });
43}
44
45main();