Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

textGeneratorDrivers.ts

269 lines9.7 KB

1import type { TextGeneratorKind, TextGeneratorModel } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import {
5 FetchHttpClient,
6 HttpClient,
7 HttpClientRequest,
8 type HttpClientResponse,
9} from "effect/http";
10​
11/** Where a text generator is reached, with its key already read from wherever settings keep it. */
12export interface TextGeneratorConnection {
13 readonly baseUrl: string;
14 readonly apiKey: string;
15 /** Names the generator in errors, such as its label or host. */
16 readonly label: string;
18​
19/** Why a model API call failed, worded for the person who configured it. */
20export class TextGeneratorRequestError extends Schema.TaggedError<TextGeneratorRequestError>()(
21 "TextGeneratorRequestError",
22 { detail: Schema.String, cause: Schema.optional(Schema.Defect()) },
23) {}
24​
25export interface TextGeneratorDriver {
26 readonly kind: TextGeneratorKind;
27 readonly generate: (
28 connection: TextGeneratorConnection,
29 model: string,
30 prompt: string,
31 ) => Effect.Effect<string, TextGeneratorRequestError, HttpClient.HttpClient>;
32 readonly listModels: (
33 connection: TextGeneratorConnection,
34 ) => Effect.Effect<
35 ReadonlyArray<TextGeneratorModel>,
36 TextGeneratorRequestError,
37 HttpClient.HttpClient
38 >;
40​
41const GENERATE_TIMEOUT = "2 minutes";
42const LIST_MODELS_TIMEOUT = "25 seconds";
43const MAX_MODEL_PAGES = 10;
44const MAX_ERROR_DETAIL_LENGTH = 300;
45​
46const ApiErrorBody = Schema.Struct({
47 error: Schema.Struct({ message: Schema.String }),
48});
49const decodeApiErrorBody = Schema.decodeUnknownOption(ApiErrorBody);
50​
51const describeStatus = (label: string, status: number, message: string | undefined) => {
52 const reason =
53 status === 401 || status === 403
54 ? "rejected the API key"
55 : status === 404
56 ? "couldn't find that model or endpoint"
57 : status === 429
58 ? "is rate-limiting requests"
59 : `returned HTTP ${status}`;
60 const trimmed = message?.trim();
61 const end =
62 (trimmed?.codePointAt(MAX_ERROR_DETAIL_LENGTH - 1) ?? 0) > 0xffff
63 ? MAX_ERROR_DETAIL_LENGTH - 1
64 : MAX_ERROR_DETAIL_LENGTH;
65 const detail = trimmed?.slice(0, end);
66 return `${label} ${reason}${detail ? `: ${detail}` : "."}`;
67};
68​
69const endpoint = (connection: TextGeneratorConnection, path: string) => {
70 const url = new URL(connection.baseUrl);
71 // The settings schema accepts a trailing empty "?" or "#"; drop them so the path lands in the pathname.
72 url.search = "";
73 url.hash = "";
74 url.pathname = `${url.pathname.replace(/\/+$/, "")}${path}`;
75 return url.toString();
76};
77​
78/** Sends a request and decodes a 2xx JSON body; anything else becomes a readable error. */
79const sendJson = Effect.fn("TextGenerator.sendJson")(function* <S extends Schema.Top>(
80 label: string,
81 request: HttpClientRequest.HttpClientRequest,
82 schema: S,
83) {
84 const http = yield* HttpClient.HttpClient;
85 const response: HttpClientResponse.HttpClientResponse = yield* http.execute(request).pipe(
86 // A redirect could carry the key to another origin.
87 Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }),
88 Effect.provideService(HttpClient.TracerPropagationEnabled, false),
89 Effect.mapError(
90 (cause) =>
91 new TextGeneratorRequestError({
92 detail: `Couldn't reach ${label}. Check the base URL and your connection.`,
93 cause,
94 }),
95 ),
96 );
97 const body = yield* response.json.pipe(Effect.orElseSucceed((): unknown => undefined));
98 if (response.status < 200 || response.status >= 300) {
99 const message = decodeApiErrorBody(body).pipe((option) =>
100 option._tag === "Some" ? option.value.error.message : undefined,
101 );
102 return yield* new TextGeneratorRequestError({
103 detail: describeStatus(label, response.status, message),
104 });
105 }
106 return yield* Schema.decodeUnknownEffect(schema)(body).pipe(
107 Effect.mapError(
108 (cause) =>
109 new TextGeneratorRequestError({
110 detail: `${label} returned a reply T3 Code couldn't read.`,
111 cause,
112 }),
113 ),
114 );
115});
116​
117const withTimeout =
118 (label: string, duration: typeof GENERATE_TIMEOUT | typeof LIST_MODELS_TIMEOUT) =>
119 <A, R>(effect: Effect.Effect<A, TextGeneratorRequestError, R>) =>
120 effect.pipe(
121 Effect.timeoutOrElse({
122 duration,
123 orElse: () =>
124 Effect.fail(
125 new TextGeneratorRequestError({ detail: `${label} took too long to respond.` }),
126 ),
127 }),
128 );
129​
130const sortModels = (models: Iterable<TextGeneratorModel>) =>
131 [...models].sort((left, right) => left.id.localeCompare(right.id));
132​
133const readModel = (entry: { readonly id: string; readonly name?: string | undefined }) => {
134 const id = entry.id.trim();
135 return id ? { id, name: entry.name?.trim() || id } : undefined;
136};
137​
138const ChatCompletion = Schema.Struct({
139 choices: Schema.Array(
140 Schema.Struct({
141 finish_reason: Schema.optional(Schema.NullOr(Schema.String)),
142 message: Schema.Struct({ content: Schema.optional(Schema.NullOr(Schema.String)) }),
143 }),
144 ),
145});
146const OpenAIModelList = Schema.Struct({
147 data: Schema.Array(Schema.Struct({ id: Schema.String, name: Schema.optional(Schema.String) })),
148});
149​
150const openAICompatible: TextGeneratorDriver = {
151 kind: "openaiCompatible",
152 generate: (connection, model, prompt) => {
153 const { label } = connection;
154 let request = HttpClientRequest.post(endpoint(connection, "/chat/completions")).pipe(
155 HttpClientRequest.bodyJsonUnsafe({ model, messages: [{ role: "user", content: prompt }] }),
156 );
157 if (connection.apiKey) request = HttpClientRequest.bearerToken(request, connection.apiKey);
158 return sendJson(label, request, ChatCompletion).pipe(
159 Effect.flatMap((completion) => {
160 const choice = completion.choices[0];
161 const text = choice?.message.content?.trim();
162 if (choice?.finish_reason === "length") {
163 return Effect.fail(
164 new TextGeneratorRequestError({ detail: `${label} reached its output limit.` }),
165 );
166 }
167 return text
168 ? Effect.succeed(text)
169 : Effect.fail(new TextGeneratorRequestError({ detail: `${label} returned no text.` }));
170 }),
171 withTimeout(label, GENERATE_TIMEOUT),
172 );
173 },
174 listModels: (connection) => {
175 const { label } = connection;
176 let request = HttpClientRequest.get(endpoint(connection, "/models"));
177 if (connection.apiKey) request = HttpClientRequest.bearerToken(request, connection.apiKey);
178 return sendJson(label, request, OpenAIModelList).pipe(
179 Effect.map((list) => sortModels(list.data.flatMap((entry) => readModel(entry) ?? []))),
180 withTimeout(label, LIST_MODELS_TIMEOUT),
181 );
182 },
183};
184​
185const ANTHROPIC_VERSION = "2023-06-01";
186const AnthropicMessage = Schema.Struct({
187 stop_reason: Schema.optional(Schema.NullOr(Schema.String)),
188 content: Schema.Array(
189 Schema.Struct({ type: Schema.String, text: Schema.optional(Schema.String) }),
190 ),
191});
192const AnthropicModelPage = Schema.Struct({
193 data: Schema.Array(
194 Schema.Struct({ id: Schema.String, display_name: Schema.optional(Schema.String) }),
195 ),
196 has_more: Schema.optional(Schema.Boolean),
197 last_id: Schema.optional(Schema.NullOr(Schema.String)),
198});
199​
200const anthropicRequest = (request: HttpClientRequest.HttpClientRequest, apiKey: string) =>
201 request.pipe(
202 HttpClientRequest.setHeader("x-api-key", apiKey),
203 HttpClientRequest.setHeader("anthropic-version", ANTHROPIC_VERSION),
204 );
205​
206const anthropic: TextGeneratorDriver = {
207 kind: "anthropic",
208 generate: (connection, model, prompt) => {
209 const { label } = connection;
210 const request = anthropicRequest(
211 HttpClientRequest.post(endpoint(connection, "/messages")).pipe(
212 HttpClientRequest.bodyJsonUnsafe({
213 model,
214 max_tokens: 8192,
215 messages: [{ role: "user", content: prompt }],
216 }),
217 ),
218 connection.apiKey,
219 );
220 return sendJson(label, request, AnthropicMessage).pipe(
221 Effect.flatMap((message) => {
222 if (message.stop_reason === "max_tokens") {
223 return Effect.fail(
224 new TextGeneratorRequestError({ detail: `${label} reached its output limit.` }),
225 );
226 }
227 const text = message.content
228 .flatMap((block) => (block.type === "text" && block.text ? [block.text] : []))
229 .join("")
230 .trim();
231 return text
232 ? Effect.succeed(text)
233 : Effect.fail(new TextGeneratorRequestError({ detail: `${label} returned no text.` }));
234 }),
235 withTimeout(label, GENERATE_TIMEOUT),
236 );
237 },
238 listModels: Effect.fn("TextGenerator.anthropic.listModels")(
239 function* (connection) {
240 const { label } = connection;
241 const models = new Map<string, TextGeneratorModel>();
242 let after: string | undefined;
243 for (let page = 0; page < MAX_MODEL_PAGES; page++) {
244 let request = HttpClientRequest.get(endpoint(connection, "/models")).pipe(
245 HttpClientRequest.setUrlParam("limit", "1000"),
246 );
247 if (after) request = HttpClientRequest.setUrlParam(request, "after_id", after);
248 const result = yield* sendJson(
249 label,
250 anthropicRequest(request, connection.apiKey),
251 AnthropicModelPage,
252 );
253 for (const entry of result.data) {
254 const model = readModel({ id: entry.id, name: entry.display_name });
255 if (model) models.set(model.id, model);
256 }
257 if (!result.has_more || !result.last_id || result.last_id === after) break;
258 after = result.last_id;
259 }
260 return sortModels(models.values());
261 },
262 (effect, connection) => effect.pipe(withTimeout(connection.label, LIST_MODELS_TIMEOUT)),
263 ),
264};
265​
266export const TEXT_GENERATOR_DRIVERS: Readonly<Record<TextGeneratorKind, TextGeneratorDriver>> = {
267 openaiCompatible: openAICompatible,
268 anthropic,
269};