Tonic commited on
Commit
9323d9d
·
1 Parent(s): 864a03d

Create app.ts

Browse files
Files changed (1) hide show
  1. app.ts +81 -0
app.ts ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { kv } from '@vercel/kv';
2
+ import { HfInference } from '@huggingface/inference';
3
+ import { HuggingFaceStream, StreamingTextResponse } from 'ai';
4
+
5
+ import { auth } from '@/auth';
6
+ import { nanoid } from '@/lib/utils';
7
+
8
+ export const runtime = 'edge';
9
+
10
+ const Hf = new HfInference(process.env.HUGGINGFACE_API_KEY);
11
+
12
+ export async function POST(req: Request) {
13
+ const json = await req.json();
14
+ const { messages } = json;
15
+ const userId = (await auth())?.user.id;
16
+
17
+ if (!userId) {
18
+ return new Response('Unauthorized', {
19
+ status: 401
20
+ });
21
+ }
22
+
23
+ const systemMessage = {
24
+ role: "system",
25
+ content: "You are a helpful and knowledgeable teacher, Socrates, begin by asking what subject the user would like to learn then use the Socratic method to help distill the knowledge. Ask questions about the topic and see if they can answer correctly and correct any mistakes"
26
+ };
27
+
28
+ messages.unshift(systemMessage);
29
+ console.log(messages);
30
+
31
+ const prompt = messages.map((msg: { role: string; content: string }) => {
32
+ if (msg.role === "user") {
33
+ return `<s>[INST]${msg.content}[/INST]`;
34
+ } else if (msg.role === "assistant") {
35
+ return `${msg.content}[/INST]</s>`;
36
+ } else {
37
+ return `[INST]${msg.content}[/INST]`; // Default case, can be adjusted if needed
38
+ }
39
+ }).join('\n');
40
+
41
+ const response = await Hf.textGenerationStream({
42
+ model: "mistralai/Mistral-7B-Instruct-v0.1",
43
+ inputs: prompt,
44
+ parameters: {
45
+ max_new_tokens: 200,
46
+ repetition_penalty: 1,
47
+ truncate: 1000,
48
+ return_full_text: false,
49
+ },
50
+ });
51
+
52
+ const stream = HuggingFaceStream(response, {
53
+ async onCompletion(completion: string) {
54
+ const title = json.messages[0].content.substring(0, 100);
55
+ const id = json.id ?? nanoid();
56
+ const createdAt = Date.now();
57
+ const path = `/chat/${id}`;
58
+ const payload = {
59
+ id,
60
+ title,
61
+ userId,
62
+ createdAt,
63
+ path,
64
+ messages: [
65
+ ...messages,
66
+ {
67
+ content: completion,
68
+ role: 'assistant'
69
+ }
70
+ ]
71
+ };
72
+ await kv.hmset(`chat:${id}`, payload);
73
+ await kv.zadd(`user:chat:${userId}`, {
74
+ score: createdAt,
75
+ member: `chat:${id}`
76
+ });
77
+ }
78
+ });
79
+
80
+ return new StreamingTextResponse(stream);
81
+ }