0
List messages
One script reply has been approved by the moderators Verified

Returns a list of messages for a given thread.

Created by hugo697 387 days ago Viewed 9139 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 387 days ago
1
type Openai = {
2
  api_key: string;
3
  organization_id: string;
4
};
5
/**
6
 * List messages
7
 * Returns a list of messages for a given thread.
8
 */
9
export async function main(
10
  auth: Openai,
11
  thread_id: string,
12
  limit: string | undefined,
13
  order: "asc" | "desc" | undefined,
14
  after: string | undefined,
15
  before: string | undefined
16
) {
17
  const url = new URL(
18
    `https://api.openai.com/v1/threads/${thread_id}/messages`
19
  );
20
  for (const [k, v] of [
21
    ["limit", limit],
22
    ["order", order],
23
    ["after", after],
24
    ["before", before],
25
  ]) {
26
    if (v !== undefined && v !== "") {
27
      url.searchParams.append(k, v);
28
    }
29
  }
30
  const response = await fetch(url, {
31
    method: "GET",
32
    headers: {
33
      "OpenAI-Organization": auth.organization_id,
34
      Authorization: "Bearer " + auth.api_key,
35
    },
36
    body: undefined,
37
  });
38
  if (!response.ok) {
39
    const text = await response.text();
40
    throw new Error(`${response.status} ${text}`);
41
  }
42
  return await response.json();
43
}
44