(
prompt: ChatGPTMessage[] | string,
params: ChatGPTParams = {},
model: string,
)
| 108 | } |
| 109 | |
| 110 | export async function streamLLMResponse( |
| 111 | prompt: ChatGPTMessage[] | string, |
| 112 | params: ChatGPTParams = {}, |
| 113 | model: string, |
| 114 | ): Promise<ReadableStream | { message: string; status: number } | null> { |
| 115 | /** Have only tested on edge runtime endpoints - not 100% sure it will work on Node runtime **/ |
| 116 | if (typeof prompt === "string" && model !== "gpt-3.5-turbo-instruct") |
| 117 | throw new Error( |
| 118 | `String prompts only supported with model gpt-3.5-turbo-instruct. You have selected model: ${model}`, |
| 119 | ); |
| 120 | |
| 121 | const { url, options } = |
| 122 | typeof prompt === "string" |
| 123 | ? getOAIRequestCompletion(prompt, { ...params, stream: true }, model) |
| 124 | : getLLMRequestChat(prompt, { ...params, stream: true }, model); |
| 125 | |
| 126 | const response = await fetch(url, options); |
| 127 | |
| 128 | if (response.status === 429) { |
| 129 | // Throwing an error triggers exponential backoff retry |
| 130 | throw new Error( |
| 131 | `LLM rate limit exceeded. Full error: ${JSON.stringify( |
| 132 | await response.json(), |
| 133 | )}`, |
| 134 | ); |
| 135 | } |
| 136 | if (!response.ok) { |
| 137 | const error = await response.json(); |
| 138 | console.error(`Error from ${model} LLM: ${JSON.stringify(error.error)}`); |
| 139 | return { message: error.error, status: response.status }; |
| 140 | } |
| 141 | |
| 142 | return response.body; |
| 143 | } |
| 144 | |
| 145 | // TODO: Rewrite this function to allow other LLMs, not just OpenAI so we can use Phind normally |
| 146 | function getOAIRequestCompletion( |
nothing calls this directly
no test coverage detected