0
Create thread and run
One script reply has been approved by the moderators Verified

Create a thread and run it in one request.

Created by hugo697 156 days ago Viewed 5611 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 156 days ago
1
type Openai = {
2
  api_key: string;
3
  organization_id: string;
4
};
5
/**
6
 * Create thread and run
7
 * Create a thread and run it in one request.
8
 */
9
export async function main(
10
  auth: Openai,
11
  body: {
12
    assistant_id: string;
13
    thread?: {
14
      messages?: {
15
        role: "user";
16
        content: string;
17
        file_ids?: string[];
18
        metadata?: { [k: string]: unknown };
19
      }[];
20
      metadata?: { [k: string]: unknown };
21
    };
22
    model?: string;
23
    instructions?: string;
24
    tools?: (
25
      | { type: "code_interpreter"; [k: string]: unknown }
26
      | { type: "retrieval"; [k: string]: unknown }
27
      | {
28
          type: "function";
29
          function: {
30
            description?: string;
31
            name: string;
32
            parameters?: { [k: string]: unknown };
33
            [k: string]: unknown;
34
          };
35
          [k: string]: unknown;
36
        }
37
    )[];
38
    metadata?: { [k: string]: unknown };
39
  }
40
) {
41
  const url = new URL(`https://api.openai.com/v1/threads/runs`);
42

43
  const response = await fetch(url, {
44
    method: "POST",
45
    headers: {
46
      "OpenAI-Organization": auth.organization_id,
47
      "Content-Type": "application/json",
48
      Authorization: "Bearer " + auth.api_key,
49
    },
50
    body: JSON.stringify(body),
51
  });
52
  if (!response.ok) {
53
    const text = await response.text();
54
    throw new Error(`${response.status} ${text}`);
55
  }
56
  return await response.json();
57
}
58