(
prompt: string | ChatGPTMessage[],
params: ChatGPTParams = {},
model: string,
)
| 29 | }; |
| 30 | |
| 31 | export async function getLLMResponse( |
| 32 | prompt: string | ChatGPTMessage[], |
| 33 | params: ChatGPTParams = {}, |
| 34 | model: string, |
| 35 | ): Promise<string> { |
| 36 | if (typeof prompt === "string" && model !== "gpt-3.5-turbo-instruct") |
| 37 | throw new Error( |
| 38 | `String prompts only supported with model gpt-3.5-turbo-instruct. You have selected model: ${model}`, |
| 39 | ); |
| 40 | |
| 41 | const { url, options } = |
| 42 | typeof prompt === "string" |
| 43 | ? getOAIRequestCompletion(prompt, params, model) |
| 44 | : getLLMRequestChat(prompt, params, model); |
| 45 | |
| 46 | const response = await Promise.race([ |
| 47 | fetch(url, options), |
| 48 | (async () => { |
| 49 | // Time out after 90s |
| 50 | await new Promise((resolve) => setTimeout(resolve, 90000)); |
| 51 | return new Response( |
| 52 | JSON.stringify({ error: { message: "Timed out!" } }), |
| 53 | { |
| 54 | status: 500, |
| 55 | }, |
| 56 | ); |
| 57 | })(), |
| 58 | ]); |
| 59 | const responseJson: ChatGPTResponse | { error: OpenAIError } = |
| 60 | await response.json(); |
| 61 | if (response.status >= 300) { |
| 62 | console.log( |
| 63 | "Response from LLM: ", |
| 64 | JSON.stringify(responseJson, undefined, 2), |
| 65 | ); |
| 66 | } |
| 67 | |
| 68 | if (response.status === 429) { |
| 69 | // Throwing an error triggers exponential backoff retry |
| 70 | throw Error( |
| 71 | // TODO: Check whether retry_after exists |
| 72 | `OpenAI API rate limit exceeded. Full error: ${JSON.stringify( |
| 73 | responseJson, |
| 74 | )}`, |
| 75 | ); |
| 76 | } |
| 77 | if ("error" in responseJson) { |
| 78 | throw Error( |
| 79 | `Error from LLM provider: ${JSON.stringify(responseJson.error)}`, |
| 80 | ); |
| 81 | } |
| 82 | |
| 83 | return removeEmptyCharacters(textFromResponse(responseJson)).trim(); |
| 84 | } |
| 85 | |
| 86 | export function textFromResponse( |
| 87 | response: |
no test coverage detected