forked from eraycc/ossapi-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgptoss.ts
More file actions
83 lines (72 loc) · 2.27 KB
/
gptoss.ts
File metadata and controls
83 lines (72 loc) · 2.27 KB
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
// gptoss.ts - GPT-OSS API client
export class GPTOSS {
private apiEndpoint = "https://api.gpt-oss.com/chatkit";
async *chatCompletion(params: {
model: string;
messages: Array<{ role: string; content: string }>;
stream: boolean;
}): AsyncGenerator<string, void, unknown> {
const { model, messages } = params;
const userMessage = messages.filter(m => m.role === "user").pop()?.content || "";
const data = {
"op": "threads.create",
"params": {
"input": {
"text": userMessage,
"content": [{ "type": "input_text", "text": userMessage }],
"quoted_text": "",
"attachments": []
}
}
};
const headers = {
"accept": "text/event-stream",
"x-reasoning-effort": "high",
"x-selected-model": model,
"x-show-reasoning": "true"
};
try {
const response = await fetch(this.apiEndpoint, {
method: "POST",
headers,
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}
if (!response.body) {
throw new Error("No response body");
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) {
if (line.startsWith("data:")) {
const jsonStr = line.substring(5).trim();
if (jsonStr === "[DONE]") continue;
try {
const data = JSON.parse(jsonStr);
if (data.type === "thread.item_updated") {
const entry = data.update?.entry || data.update;
if (entry?.type === "assistant_message.content_part.text_delta") {
yield entry.delta;
}
}
} catch (e) {
console.error("Error parsing SSE data:", e);
}
}
}
}
} catch (error) {
console.error("Error in GPT-OSS communication:", error);
throw error;
}
}
}