-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcopilotkit-runtime-simple.js
More file actions
178 lines (150 loc) Β· 5.19 KB
/
copilotkit-runtime-simple.js
File metadata and controls
178 lines (150 loc) Β· 5.19 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/**
* Simple CopilotKit Runtime Server
*
* This uses your existing /query endpoint directly - no AG-UI protocol complexity!
*/
const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch');
const app = express();
const PORT = 3001;
// Your existing backend endpoint that already works
const BACKEND_URL = 'http://localhost:8000/query';
// Enable CORS for frontend (support both common Vite ports)
app.use(cors({
origin: ['http://localhost:3000', 'http://localhost:5173'],
credentials: true
}));
app.use(express.json());
// Request logging
app.use((req, res, next) => {
console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
next();
});
// Handle GraphQL queries from CopilotKit
app.post('/copilotkit', async (req, res) => {
const { operationName, variables } = req.body;
console.log('π¨ CopilotKit request:', operationName);
try {
// Handle availableAgents query
if (operationName === 'availableAgents') {
console.log('β
Returning available agents');
return res.json({
data: {
availableAgents: {
agents: [{
name: 'orchestrator_agent',
id: 'orchestrator_agent',
description: 'Driver\'s license and scheduling assistant',
__typename: 'Agent'
}],
__typename: 'AvailableAgents'
}
}
});
}
// Handle generateCopilotResponse mutation
if (operationName === 'generateCopilotResponse') {
const data = variables?.data || {};
const messages = data.messages || [];
const threadId = data.threadId || 'default';
console.log('π Messages count:', messages.length);
// Extract user messages
const userMessages = messages
.filter(m => m.textMessage?.role === 'user')
.map(m => m.textMessage.content);
if (userMessages.length === 0) {
console.log('β οΈ No user messages found');
return res.json({ data: { generateCopilotResponse: null } });
}
const question = userMessages[userMessages.length - 1];
console.log('β User question:', question);
// Call your existing working backend endpoint
console.log('π Calling backend /query...');
const backendResponse = await fetch(BACKEND_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
question: question,
session_id: threadId
})
});
if (!backendResponse.ok) {
throw new Error(`Backend error: ${backendResponse.status}`);
}
const result = await backendResponse.json();
console.log('β
Backend response received:', result.response.substring(0, 50) + '...');
// Format response as CopilotKit expects (multipart/mixed format)
res.setHeader('Content-Type', 'multipart/mixed; boundary=---');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const messageId = 'msg-' + Date.now();
const runId = 'run-' + Date.now();
// Send response in multipart format
res.write('---\r\n');
res.write('Content-Type: application/json\r\n\r\n');
res.write(JSON.stringify({
data: {
generateCopilotResponse: {
threadId: threadId,
runId: runId,
extensions: {},
__typename: 'CopilotResponse'
}
},
hasNext: true
}));
res.write('\r\n');
res.write('---\r\n');
res.write('Content-Type: application/json\r\n\r\n');
res.write(JSON.stringify({
incremental: [{
items: [{
__typename: 'TextMessageOutput',
id: messageId,
createdAt: new Date().toISOString(),
content: result.response,
role: 'assistant',
parentMessageId: null,
}],
path: ['generateCopilotResponse', 'messages', 0]
}],
hasNext: true
}));
res.write('\r\n');
res.write('---\r\n');
res.write('Content-Type: application/json\r\n\r\n');
res.write(JSON.stringify({
incremental: [{
data: {
status: {
code: 'SUCCESS',
__typename: 'BaseResponseStatus'
}
},
path: ['generateCopilotResponse']
}],
hasNext: false
}));
res.write('\r\n-----\r\n');
res.end();
console.log('β
Response sent to frontend');
return;
}
// Unknown operation
console.log('β οΈ Unknown operation:', operationName);
res.json({ data: null });
} catch (error) {
console.error('β Error:', error.message);
res.status(500).json({ error: error.message });
}
});
// Health check
app.get('/health', (req, res) => {
res.json({ status: 'ok', message: 'CopilotKit Simple Runtime' });
});
app.listen(PORT, () => {
console.log('π CopilotKit Simple Runtime running on http://localhost:' + PORT);
console.log('π‘ Using backend /query endpoint at ' + BACKEND_URL);
console.log('π― Frontend connects to http://localhost:3001/copilotkit');
});