Create embedding

Creates an embedding vector representing the input text.

Script openai Verified

by adam186 ยท 12/16/2022

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 376 days ago
1
type Openai = {
2
  api_key: string;
3
  organization_id: string;
4
};
5
/**
6
 * Create embedding
7
 * Creates an embedding vector representing the input text.
8
 */
9
export async function main(
10
  auth: Openai,
11
  body: {
12
    input: string | string[] | number[] | number[][];
13
    model:
14
      | string
15
      | (
16
          | "text-embedding-ada-002"
17
          | "text-embedding-3-small"
18
          | "text-embedding-3-large"
19
        );
20
    encoding_format?: "float" | "base64";
21
    dimensions?: number;
22
    user?: string;
23
  }
24
) {
25
  const url = new URL(`https://api.openai.com/v1/embeddings`);
26

27
  const response = await fetch(url, {
28
    method: "POST",
29
    headers: {
30
      "OpenAI-Organization": auth.organization_id,
31
      "Content-Type": "application/json",
32
      Authorization: "Bearer " + auth.api_key,
33
    },
34
    body: JSON.stringify(body),
35
  });
36
  if (!response.ok) {
37
    const text = await response.text();
38
    throw new Error(`${response.status} ${text}`);
39
  }
40
  return await response.json();
41
}
42

Other submissions
  • Submitted by adam186 Deno
    Created 1009 days ago
    1
    import { Configuration, OpenAIApi } from "npm:[email protected]";
    2
    
    
    3
    type Openai = {
    4
      api_key: string;
    5
      organization_id: string;
    6
    };
    7
    export async function main(
    8
      auth: Openai,
    9
      prompt: string,
    10
      model: string = "text-embedding-ada-002",
    11
    ) {
    12
      const configuration = new Configuration({
    13
        apiKey: auth.api_key,
    14
        organization: auth.organization_id,
    15
      });
    16
      const openai = new OpenAIApi(configuration);
    17
    
    
    18
      const response = await openai.createEmbedding({
    19
        model,
    20
        input: prompt,
    21
      });
    22
      return response.data.data;
    23
    }
    24