-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrok.ts
More file actions
98 lines (87 loc) · 3.36 KB
/
grok.ts
File metadata and controls
98 lines (87 loc) · 3.36 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
import { settings } from '$lib/config'
import { fetchRelevantHistory } from './history'
import { logger } from './logger'
import { openAiPrompt, systemContext } from './prompts'
import type { Message, ToneType } from './types'
import { formatMessagesAsText } from './utils'
const API_URL = 'https://grok.x.ai/api/chat/completions'
const DEFAULT_MODEL = 'grok-1'
const DEFAULT_TEMPERATURE = 0.5
const getConfig = () => ({
model: settings.GROK_MODEL || DEFAULT_MODEL,
temperature: Number(settings.GROK_TEMPERATURE || DEFAULT_TEMPERATURE),
apiKey: settings.GROK_API_KEY,
})
export const getGrokReply = async (
messages: Message[],
tone: ToneType,
context: string
): Promise<{ summary: string; replies: string[] }> => {
const config = getConfig()
if (!config.apiKey) {
return {
summary: 'Grok API key is not configured.',
replies: ['Please set up your Grok API key in the .env file.'],
}
}
const historyContext = await fetchRelevantHistory(messages)
const prompt = openAiPrompt(tone, historyContext) + '\n\n' + context
const body = {
model: config.model,
messages: [
{ role: 'system', content: systemContext() },
{ role: 'user', content: formatMessagesAsText(messages) },
{ role: 'user', content: prompt },
],
temperature: config.temperature,
tools: [
{
type: 'function',
function: {
name: 'draft_replies',
description: 'Generate a short summary and three suggested replies',
parameters: {
type: 'object',
properties: {
summary: { type: 'string' },
replies: { type: 'array', items: { type: 'string' } },
},
required: ['summary', 'replies'],
},
},
},
],
tool_choice: { type: 'function', function: { name: 'draft_replies' } },
}
logger.debug({ body }, 'Sending request to Grok')
logger.info('Sending request to Grok')
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${config.apiKey}`,
},
body: JSON.stringify(body),
})
if (!response.ok) {
logger.error({ status: response.status }, 'Grok API error')
throw new Error(`Grok API error code ${response.status}: ${response.statusText}`)
}
const { choices } = await response.json()
const functionCall = choices[0]?.message?.tool_calls?.[0]?.function
if (!functionCall) throw new Error('No function call in response')
const { summary, replies } = JSON.parse(functionCall.arguments)
if (!summary || !Array.isArray(replies)) {
logger.error({ summary, replies }, 'Invalid response format from Grok')
throw new Error('Invalid response format from Grok')
}
return { summary, replies }
} catch (error) {
logger.error({ error }, 'Failed to get Grok reply')
return {
summary: '',
replies: ['(AI API error. Check your key and usage.)'],
}
}
}