summaryrefslogtreecommitdiff
path: root/src/generic.ts
blob: ac6b55bec7091484fe4b53219de924b1d43a9d4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import OpenAI from "openai";
import { MAX_TOKENS, RESPONSE_LENGTH } from "./logic/constants";
import type { AIModelAPI, ChatMessage, InputToken, OChoice } from "./types";
import type { AsyncRes } from "sortug";
import type {
  ResponseCreateParamsBase,
  ResponseCreateParamsNonStreaming,
  ResponseCreateParamsStreaming,
  ResponseInput,
} from "openai/resources/responses/responses.mjs";

type Props = {
  baseURL: string;
  apiKey: string;
  model?: string;
  maxTokens?: number;
  tokenizer?: (text: string) => number;
};
export default class OpenAIAPI implements AIModelAPI {
  private apiKey;
  private baseURL;
  private api;
  maxTokens: number = MAX_TOKENS;
  tokenizer: (text: string) => number = (text) => text.length / 3;
  model;

  constructor(props: Props) {
    this.apiKey = props.apiKey;
    this.baseURL = props.baseURL;
    this.api = new OpenAI({ baseURL: this.baseURL, apiKey: this.apiKey });
    this.model = props.model || "";
    if (props.maxTokens) this.maxTokens = props.maxTokens;
    if (props.tokenizer) this.tokenizer = props.tokenizer;
  }
  public setModel(model: string) {
    this.model = model;
  }

  public buildInput(tokens: InputToken[]): ResponseInput {
    return [
      {
        role: "user",
        content: tokens.map((t) =>
          "text" in t
            ? { type: "input_text", text: t.text }
            : "img" in t
              ? { type: "input_image", image_url: t.img, detail: "auto" }
              : { type: "input_text", text: "oy vey" },
        ),
      },
    ];
  }

  // OpenAI SDK has three kinds ReponseInputContent: text image and file
  // images can be URLs or base64 dataurl thingies
  //
  public async send(
    input: string | ResponseInput,
    sys?: string,
  ): AsyncRes<string> {
    const params = sys ? { instructions: sys, input } : { input };
    const res = await this.apiCall(params);
    if ("error" in res) return res;
    else {
      try {
        return { ok: res.ok.output_text };
      } catch (e) {
        return { error: `${e}` };
      }
    }
  }

  public async stream(
    input: string,
    handle: (c: string) => void,
    sys?: string,
  ) {
    const params = sys ? { instructions: sys, input } : { input };
    await this.apiCallStream(params, handle);
  }

  // TODO custom temperature?
  private async apiCall(
    params: ResponseCreateParamsNonStreaming,
  ): AsyncRes<OpenAI.Responses.Response> {
    try {
      const res = await this.api.responses.create({
        ...params,
        // temperature: 1.3,
        model: params.model || this.model,
        input: params.input,
        max_output_tokens: params.max_output_tokens || RESPONSE_LENGTH,
        stream: false,
      });
      // TODO damn there's a lot of stuff here
      return { ok: res };
    } catch (e) {
      console.log(e, "error in openai api");
      return { error: `${e}` };
    }
  }

  private async apiCallStream(
    params: ResponseCreateParamsBase,
    handler: (c: string) => void,
  ) {
    // temperature: 1.3,
    const pms: ResponseCreateParamsStreaming = {
      ...params,
      stream: true,
      model: params.model || this.model,
      input: params.input,
      max_output_tokens: params.max_output_tokens || RESPONSE_LENGTH,
    };
    try {
      const stream = await this.api.responses.create(pms);
      for await (const event of stream) {
        console.log(event);
        switch (event.type) {
          // TODO deal with audio and whatever
          case "response.output_text.delta":
            handler(event.delta);
            break;
          case "response.completed":
            break;
          default:
            break;
        }
        // if (event.type === "response.completed")
        // wtf how do we use this
      }
    } catch (e) {
      console.log(e, "error in openai api");
      return { error: `${e}` };
    }
  }

  // private async apiCallStream(
  //   messages: Message[],
  //   handle: (c: string) => void,
  // ): Promise<void> {
  //   try {
  //     const stream = await this.api.chat.completions.create({
  //       temperature: 1.3,
  //       model: this.model,
  //       messages,
  //       max_tokens: RESPONSE_LENGTH,
  //       stream: true,
  //     });

  //     for await (const chunk of stream) {
  //       for (const choice of chunk.choices) {
  //         console.log({ choice });
  //         if (!choice.delta) continue;
  //         const cont = choice.delta.content;
  //         if (!cont) continue;
  //         handle(cont);
  //       }
  //     }
  //   } catch (e) {
  //     console.log(e, "error in openai api");
  //     handle(`Error streaming OpenAI, ${e}`);
  //   }
  // }
}