-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathroute.ts
More file actions
107 lines (93 loc) · 2.68 KB
/
Copy pathroute.ts
File metadata and controls
107 lines (93 loc) · 2.68 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import OpenAI from "openai";
import { NextRequest } from "next/server";
import { makeC1Response } from "@thesysai/genui-sdk/server";
import { transformStream } from "@crayonai/stream";
import { saveVersion } from "../../../lib/versionStore";
export async function POST(req: NextRequest) {
const apiKey = process.env.THESYS_API_KEY;
if (!apiKey) {
return new Response("Missing THESYS_API_KEY", { status: 500 });
}
const { prompt, artifactType, artifactId, artifactContent } =
(await req.json()) as {
prompt?: string;
artifactType?: "slides" | "report";
artifactId?: string;
artifactContent?: string;
};
if (!prompt || typeof prompt !== "string") {
return new Response("Missing 'prompt'", { status: 400 });
}
if (!artifactId) {
return new Response("Missing 'artifactId'", { status: 400 });
}
const client = new OpenAI({
apiKey,
baseURL: "https://api.thesys.dev/v1/artifact",
});
const messages: Array<{
role: "system" | "user" | "assistant";
content: string;
}> = [];
// Include previous artifact content if editing
if (
typeof artifactContent === "string" &&
artifactContent.trim().length > 0
) {
messages.push({ role: "assistant", content: artifactContent });
}
messages.push({ role: "user", content: prompt });
const stream = client.chat.completions.runTools({
model: "c1/artifact/v-20251030",
stream: true,
messages,
abortSignal: req.signal,
tools: [],
metadata: {
thesys: JSON.stringify({
id: artifactId,
c1_artifact_type: artifactType,
}),
},
});
const c1Response = makeC1Response();
let isAborted = false;
req.signal.addEventListener("abort", () => {
isAborted = true;
});
// Accumulate content to save as a version
let accumulatedContent = "";
transformStream(
stream,
(chunk) => {
const content = chunk.choices?.[0]?.delta?.content;
if (content) {
accumulatedContent += content;
c1Response.writeContent(content);
}
},
{
onError: (error) => {
console.error("Error in ask route:", error);
},
onEnd: () => {
if (isAborted) {
return;
}
c1Response.end();
// Save the completed artifact as a new version
if (accumulatedContent) {
const version = saveVersion(artifactId, accumulatedContent, prompt);
console.log(`Saved version ${version.id} for artifact ${artifactId}`);
}
},
}
);
return new Response(c1Response.responseStream, {
headers: {
"Content-Type": "text/plain; charset=utf-8",
"Cache-Control": "no-cache",
"X-Artifact-Id": artifactId,
},
});
}