🎨 use common streamSse for LLMs
This commit is contained in:
parent
4de45f7956
commit
b9b6cd83b1
6 changed files with 76 additions and 139 deletions
|
|
@ -1,6 +1,6 @@
|
|||
import { BaseLLM } from "..";
|
||||
import { CompletionOptions, LLMOptions, ModelProvider } from "../..";
|
||||
import { streamResponse } from "../stream";
|
||||
import { streamSse } from "../stream";
|
||||
import { anthropicTemplateMessages } from "../templates/chat";
|
||||
|
||||
class Anthropic extends BaseLLM {
|
||||
|
|
@ -73,18 +73,9 @@ class Anthropic extends BaseLLM {
|
|||
}),
|
||||
});
|
||||
|
||||
let chunk = "";
|
||||
for await (const value of streamResponse(response)) {
|
||||
chunk += value;
|
||||
const lines = chunk.split("\n");
|
||||
chunk = lines.pop() as string;
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("data: ")) {
|
||||
const result = JSON.parse(line.slice(6));
|
||||
if (result.completion) {
|
||||
yield result.completion;
|
||||
}
|
||||
}
|
||||
for await (const value of streamSse(response)) {
|
||||
if (value.completion) {
|
||||
yield value.completion;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { BaseLLM } from "..";
|
||||
import { CompletionOptions, LLMOptions, ModelProvider } from "../..";
|
||||
import { streamResponse } from "../stream";
|
||||
import { streamSse } from "../stream";
|
||||
|
||||
class HuggingFaceTGI extends BaseLLM {
|
||||
static providerName: ModelProvider = "huggingface-tgi";
|
||||
|
|
@ -37,44 +37,8 @@ class HuggingFaceTGI extends BaseLLM {
|
|||
body: JSON.stringify({ inputs: prompt, parameters: args }),
|
||||
});
|
||||
|
||||
let chunk = "";
|
||||
|
||||
for await (const value of streamResponse(response)) {
|
||||
chunk += value;
|
||||
|
||||
const lines = chunk.split("\n");
|
||||
|
||||
for (let i = 0; i < lines.length - 1; i++) {
|
||||
let processedChunk = lines[i];
|
||||
if (processedChunk.startsWith("data: ")) {
|
||||
processedChunk = processedChunk.slice("data: ".length);
|
||||
} else if (processedChunk.startsWith("data:")) {
|
||||
processedChunk = processedChunk.slice("data:".length);
|
||||
}
|
||||
|
||||
if (processedChunk.trim() === "") {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const jsonChunk = JSON.parse(processedChunk);
|
||||
yield jsonChunk.token.text;
|
||||
} catch (e) {
|
||||
console.log(`Error parsing JSON: ${e}`);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
chunk = lines[lines.length - 1];
|
||||
}
|
||||
|
||||
if (chunk.trim() !== "") {
|
||||
try {
|
||||
const jsonChunk = JSON.parse(chunk);
|
||||
yield jsonChunk.token.text;
|
||||
} catch (e) {
|
||||
console.log(`Error parsing JSON: ${e}`);
|
||||
}
|
||||
for await (const value of streamSse(response)) {
|
||||
yield value.token.text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { BaseLLM } from "..";
|
||||
import { CompletionOptions, LLMOptions, ModelProvider } from "../..";
|
||||
import { streamResponse } from "../stream";
|
||||
import { streamSse } from "../stream";
|
||||
|
||||
class LlamaCpp extends BaseLLM {
|
||||
static providerName: ModelProvider = "llama.cpp";
|
||||
|
|
@ -37,27 +37,11 @@ class LlamaCpp extends BaseLLM {
|
|||
}),
|
||||
});
|
||||
|
||||
let buffer = "";
|
||||
for await (const chunk of streamResponse(resp)) {
|
||||
buffer += chunk;
|
||||
|
||||
const lines = buffer.split("\n");
|
||||
buffer = lines.pop() ?? "";
|
||||
for (const line of lines) {
|
||||
if (line.trim() === "") continue;
|
||||
const data = JSON.parse(line.substring(6));
|
||||
if ("error" in data) {
|
||||
throw new Error(data.error);
|
||||
}
|
||||
yield data.content;
|
||||
for await (const value of streamSse(resp)) {
|
||||
if (value.content) {
|
||||
yield value.content;
|
||||
}
|
||||
}
|
||||
|
||||
const lines = buffer.split("\n");
|
||||
for (const line of lines) {
|
||||
if (line.trim() === "") continue;
|
||||
yield JSON.parse(line.substring(6))["content"];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../..";
|
||||
import { streamResponse } from "../stream";
|
||||
import { streamSse } from "../stream";
|
||||
|
||||
class OpenAI extends BaseLLM {
|
||||
static providerName: ModelProvider = "openai";
|
||||
|
|
@ -84,34 +84,9 @@ class OpenAI extends BaseLLM {
|
|||
}),
|
||||
});
|
||||
|
||||
let buffer = "";
|
||||
for await (const value of streamResponse(response)) {
|
||||
buffer += value;
|
||||
let position;
|
||||
while ((position = buffer.indexOf("\n")) >= 0) {
|
||||
const line = buffer.slice(0, position);
|
||||
buffer = buffer.slice(position + 1);
|
||||
if (line.startsWith("data: ") && !line.startsWith("data: [DONE]")) {
|
||||
const result = JSON.parse(line.slice(6));
|
||||
if (result.choices?.[0]?.delta?.content) {
|
||||
yield result.choices[0].delta;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (buffer.length > 0) {
|
||||
if (buffer.startsWith("data: ") && !buffer.startsWith("data: [DONE]")) {
|
||||
const result = JSON.parse(buffer.slice(6));
|
||||
if (result.choices?.[0]?.delta?.content) {
|
||||
yield result.choices[0].delta;
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
const result = JSON.parse(buffer);
|
||||
if (result.error) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
} catch (e) {}
|
||||
for await (const value of streamSse(response)) {
|
||||
if (value.choices?.[0]?.delta?.content) {
|
||||
yield value.choices[0].delta;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { BaseLLM } from "..";
|
||||
import { CompletionOptions, LLMOptions, ModelProvider } from "../..";
|
||||
import { streamSse } from "../stream";
|
||||
|
||||
class Together extends BaseLLM {
|
||||
static providerName: ModelProvider = "together";
|
||||
|
|
@ -53,43 +54,9 @@ class Together extends BaseLLM {
|
|||
}),
|
||||
});
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) {
|
||||
return "";
|
||||
}
|
||||
let result: any = { done: false };
|
||||
let jsonChunk = "";
|
||||
while (!result.done) {
|
||||
result = await reader.read();
|
||||
jsonChunk = new TextDecoder().decode(result.value);
|
||||
if (result.value) {
|
||||
if (
|
||||
jsonChunk.startsWith(": ping - ") ||
|
||||
jsonChunk.startsWith("data: [DONE]")
|
||||
) {
|
||||
result = await reader.read();
|
||||
jsonChunk = new TextDecoder().decode(result.value);
|
||||
continue;
|
||||
}
|
||||
|
||||
const chunks = jsonChunk.split("\n");
|
||||
for (const chunk of chunks) {
|
||||
if (chunk.trim() !== "") {
|
||||
let strippedChunk = chunk.startsWith("data: ")
|
||||
? chunk.slice(6)
|
||||
: chunk;
|
||||
if (strippedChunk === "[DONE]") {
|
||||
continue;
|
||||
}
|
||||
let parsedChunk = JSON.parse(strippedChunk);
|
||||
|
||||
if ("error" in parsedChunk) {
|
||||
throw new Error(parsedChunk.error);
|
||||
} else if ("choices" in parsedChunk) {
|
||||
yield parsedChunk.choices[0].text;
|
||||
}
|
||||
}
|
||||
}
|
||||
for await (const value of streamSse(response)) {
|
||||
if (value.choices) {
|
||||
yield value.choices[0].text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
export async function* streamResponse(response: Response): AsyncGenerator<any> {
|
||||
export async function* streamResponse(
|
||||
response: Response
|
||||
): AsyncGenerator<string> {
|
||||
if (response.status !== 200) {
|
||||
throw new Error(await response.text());
|
||||
}
|
||||
|
|
@ -20,3 +22,57 @@ export async function* streamResponse(response: Response): AsyncGenerator<any> {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseDataLine(line: string): any {
|
||||
const json = line.startsWith("data: ")
|
||||
? line.slice("data: ".length)
|
||||
: line.slice("data:".length);
|
||||
|
||||
try {
|
||||
const data = JSON.parse(json);
|
||||
if (data.error) {
|
||||
throw new Error(`Error streaming response: ${data.error}`);
|
||||
}
|
||||
|
||||
return data;
|
||||
} catch (e) {
|
||||
throw new Error(`Malformed JSON sent from server: ${json}`);
|
||||
}
|
||||
}
|
||||
|
||||
function parseSseLine(line: string): { done: boolean; data: any } {
|
||||
if (line.startsWith("data: [DONE]")) {
|
||||
return { done: true, data: undefined };
|
||||
} else if (line.startsWith("data:")) {
|
||||
return { done: false, data: parseDataLine(line) };
|
||||
} else if (line.startsWith(": ping")) {
|
||||
return { done: true, data: undefined };
|
||||
}
|
||||
throw new Error(`Invalid data sent from server: ${line}`);
|
||||
}
|
||||
|
||||
export async function* streamSse(response: Response): AsyncGenerator<any> {
|
||||
let buffer = "";
|
||||
for await (const value of streamResponse(response)) {
|
||||
buffer += value;
|
||||
|
||||
let position;
|
||||
while ((position = buffer.indexOf("\n")) >= 0) {
|
||||
const line = buffer.slice(0, position);
|
||||
buffer = buffer.slice(position + 1);
|
||||
|
||||
const { done, data } = parseSseLine(line);
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
yield data;
|
||||
}
|
||||
}
|
||||
|
||||
if (buffer.length > 0) {
|
||||
const { done, data } = parseSseLine(buffer);
|
||||
if (!done) {
|
||||
yield data;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue