Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
260 lines (218 loc) · 6.95 KB
/
Copy pathserver.js
File metadata and controls
260 lines (218 loc) · 6.95 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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import express from 'express';
import bodyParser from 'body-parser';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = 3333;
app.use(bodyParser.json());
let MOCK_RESPONSES = {};
let DEFAULT_RESPONSE = {};
function loadConfig() {
try {
const configPath = path.join(__dirname, 'config.json');
const configData = fs.readFileSync(configPath, 'utf8');
const config = JSON.parse(configData);
MOCK_RESPONSES = {};
for (const response of config.responses) {
const responseObj = {
type: response.action === 'function_call' ? 'function_call' : 'text'
};
if (response.action === 'function_call') {
if (response.tool_call) {
responseObj.tool_calls = [{
id: response.tool_call.id,
type: 'function',
function: {
name: response.tool_call.function_name,
arguments: JSON.stringify(response.tool_call.arguments)
}
}];
} else if (response.tool_calls) {
responseObj.tool_calls = response.tool_calls.map(tc => ({
id: tc.id,
type: 'function',
function: {
name: tc.function_name,
arguments: JSON.stringify(tc.arguments)
}
}));
}
} else {
responseObj.content = response.content;
}
for (const keyword of response.keywords) {
MOCK_RESPONSES[keyword.toLowerCase()] = responseObj;
}
}
DEFAULT_RESPONSE = {
type: config.default_response.action === 'function_call' ? 'function_call' : 'text',
content: config.default_response.content
};
MOCK_RESPONSES['default'] = DEFAULT_RESPONSE;
console.log('\n✓ Configuration loaded successfully');
console.log(` Configured ${Object.keys(MOCK_RESPONSES).length - 1} keyword responses`);
return true;
} catch (error) {
console.error('Error loading config:', error.message);
return false;
}
}
loadConfig();
function generateResponseFromToolResults(messages) {
// Find tool result messages
const toolResults = messages.filter(m => m.role === 'tool');
console.log('[DEBUG] Tool results found:', toolResults.length);
if (toolResults.length === 0) {
return null;
}
const assistantMessage = messages.find(m => m.role === 'assistant' && m.tool_calls);
console.log('[DEBUG] Assistant message found:', !!assistantMessage);
if (!assistantMessage) {
return null;
}
const responses = [];
for (const toolCall of assistantMessage.tool_calls) {
const toolResult = toolResults.find(tr => tr.tool_call_id === toolCall.id);
console.log('[DEBUG] Looking for tool_call_id:', toolCall.id, 'Found:', !!toolResult);
if (!toolResult) continue;
try {
let content = toolResult.content;
const jsonMatch = content.match(/\{.*\}/s);
if (jsonMatch) {
content = jsonMatch[0];
}
const resultData = JSON.parse(content);
const functionName = toolCall.function.name;
const args = JSON.parse(toolCall.function.arguments);
console.log('[DEBUG] Processing function:', functionName, 'with result:', resultData);
if (functionName === 'execute_command') {
// Return the command output directly
if (resultData.output !== undefined) {
responses.push(resultData.output);
} else {
responses.push(`Command executed: ${resultData.command || args.command}`);
}
}
} catch (e) {
// If parsing fails, skip this result
console.log('[DEBUG] Error parsing tool result:', e.message);
continue;
}
}
console.log('[DEBUG] Generated responses:', responses);
if (responses.length > 0) {
return {
type: 'text',
content: responses.join('\n\n')
};
}
return null;
}
function findResponse(messages) {
const lastMessage = messages[messages.length - 1];
// Check if we have tool results to process
if (lastMessage.role === 'tool' || lastMessage.role === 'assistant') {
const toolResponse = generateResponseFromToolResults(messages);
if (toolResponse) {
return toolResponse;
}
}
// For user messages, check for keyword matches
if (lastMessage.role === 'user') {
const content = lastMessage.content.toLowerCase();
// Check for keyword matches
for (const [keyword, response] of Object.entries(MOCK_RESPONSES)) {
if (keyword !== 'default' && content.includes(keyword)) {
return response;
}
}
}
return MOCK_RESPONSES['default'];
}
// Main chat completions endpoint
app.post('/v1/chat/completions', (req, res) => {
const { messages, model, tools, stream } = req.body;
if (!messages || !Array.isArray(messages)) {
return res.status(400).json({
error: {
message: 'messages must be an array',
type: 'invalid_request_error'
}
});
}
const response = findResponse(messages);
const responseId = `chatcmpl-${Math.random().toString(36).substring(7)}`;
// Build the response based on type
let choice;
if (response.type === 'function_call') {
choice = {
index: 0,
message: {
role: 'assistant',
content: null,
tool_calls: response.tool_calls
},
finish_reason: 'tool_calls'
};
} else {
choice = {
index: 0,
message: {
role: 'assistant',
content: response.content
},
finish_reason: 'stop'
};
}
const mockResponse = {
id: responseId,
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model: model || 'gpt-4-turbo-preview',
choices: [choice],
usage: {
prompt_tokens: 50,
completion_tokens: 20,
total_tokens: 70
}
};
console.log(`[${new Date().toISOString()}] Request:`, JSON.stringify(messages[messages.length - 1], null, 2));
console.log(`[${new Date().toISOString()}] Response:`, JSON.stringify(choice.message, null, 2));
res.json(mockResponse);
});
// Models endpoint
app.get('/v1/models', (req, res) => {
res.json({
object: 'list',
data: [
{
id: 'gpt-4-turbo-preview',
object: 'model',
created: 1677610602,
owned_by: 'openai'
},
{
id: 'gpt-3.5-turbo',
object: 'model',
created: 1677610602,
owned_by: 'openai'
}
]
});
});
// Health check
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
app.listen(PORT, () => {
console.log(`\nMock OpenAI API server running on http://localhost:${PORT}`);
console.log(`\nEndpoints:`);
console.log(`- POST /v1/chat/completions - OpenAI chat API`);
console.log(`- GET /v1/models - List models`);
console.log(`- GET /health - Health check`);
console.log('\n📝 Edit config.json to change responses (restart server to apply)');
console.log('\nConfigured keywords:', Object.keys(MOCK_RESPONSES).filter(k => k !== 'default').join(', '));
});