File size: 24,429 Bytes
63eaa16 |
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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 |
import { describe, it, expect, beforeEach } from "bun:test";
import { OpenAIService } from "../src/openai-service";
import type {
ChatCompletionRequest,
ToolDefinition,
ToolCall,
} from "../src/types";
describe("OpenAIService with Tools", () => {
let openAIService: OpenAIService;
beforeEach(() => {
openAIService = new OpenAIService();
});
const sampleTools: ToolDefinition[] = [
{
type: "function",
function: {
name: "get_current_time",
description: "Get the current time",
},
},
{
type: "function",
function: {
name: "calculate",
description: "Perform mathematical calculations",
parameters: {
type: "object",
properties: {
expression: {
type: "string",
description: "Mathematical expression to evaluate",
},
},
required: ["expression"],
},
},
},
{
type: "function",
function: {
name: "get_weather",
description: "Get weather information for a location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city and state, e.g. San Francisco, CA",
},
},
required: ["location"],
},
},
},
];
describe("validateRequest with tools", () => {
it("should validate requests with valid tools", () => {
const request = {
model: "gpt-4o-mini",
messages: [{ role: "user", content: "What's the weather like?" }],
tools: sampleTools,
};
const validated = openAIService.validateRequest(request);
expect(validated.tools).toEqual(sampleTools);
});
it("should reject requests with invalid tools", () => {
const request = {
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Hello" }],
tools: [
{
type: "invalid",
function: { name: "test" },
},
],
};
expect(() => openAIService.validateRequest(request)).toThrow(
"Invalid tools"
);
});
it("should validate tool messages", () => {
const request = {
model: "gpt-4o-mini",
messages: [
{ role: "user", content: "What time is it?" },
{
role: "assistant",
content: null,
tool_calls: [
{
id: "call_1",
type: "function",
function: {
name: "get_current_time",
arguments: "{}",
},
},
],
},
{
role: "tool",
content: "2024-01-15T10:30:00Z",
tool_call_id: "call_1",
},
],
};
const validated = openAIService.validateRequest(request);
expect(validated.messages).toHaveLength(3);
});
it("should reject tool messages without tool_call_id", () => {
const request = {
model: "gpt-4o-mini",
messages: [
{
role: "tool",
content: "Some result",
},
],
};
expect(() => openAIService.validateRequest(request)).toThrow(
"Tool messages must have a tool_call_id"
);
});
});
describe("registerFunction", () => {
it("should allow registering custom functions", () => {
const customFunction = (args: { name: string }) => `Hello, ${args.name}!`;
openAIService.registerFunction("greet", customFunction);
// The function should now be available for execution
expect(openAIService["availableFunctions"]["greet"]).toBe(customFunction);
});
});
describe("executeToolCall", () => {
it("should execute built-in functions", async () => {
const toolCall = {
id: "call_1",
type: "function" as const,
function: {
name: "get_current_time",
arguments: "{}",
},
};
const result = await openAIService.executeToolCall(toolCall);
expect(result).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/); // ISO date format
});
it("should execute calculate function", async () => {
const toolCall = {
id: "call_1",
type: "function" as const,
function: {
name: "calculate",
arguments: '{"expression": "2 + 2"}',
},
};
const result = await openAIService.executeToolCall(toolCall);
const parsed = JSON.parse(result);
expect(parsed.result).toBe(4);
});
it("should execute weather function", async () => {
const toolCall = {
id: "call_1",
type: "function" as const,
function: {
name: "get_weather",
arguments: '{"location": "New York"}',
},
};
const result = await openAIService.executeToolCall(toolCall);
const parsed = JSON.parse(result);
expect(parsed.location).toBe("New York");
expect(parsed.temperature).toBeTypeOf("number");
expect(parsed.condition).toBeTypeOf("string");
});
it("should handle function execution errors", async () => {
const toolCall = {
id: "call_1",
type: "function" as const,
function: {
name: "calculate",
arguments: '{"expression": "invalid expression"}',
},
};
const result = await openAIService.executeToolCall(toolCall);
const parsed = JSON.parse(result);
expect(parsed.error).toBeDefined();
});
});
describe("createChatCompletion with tools", () => {
it("should handle requests without tools normally", async () => {
const request: ChatCompletionRequest = {
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Hello, how are you?" }],
};
// Mock the DuckAI response
const originalChat = openAIService["duckAI"].chat;
openAIService["duckAI"].chat = async () => "I'm doing well, thank you!";
const response = await openAIService.createChatCompletion(request);
expect(response.choices[0].message.role).toBe("assistant");
expect(response.choices[0].message.content).toBe(
"I'm doing well, thank you!"
);
expect(response.choices[0].finish_reason).toBe("stop");
// Restore original method
openAIService["duckAI"].chat = originalChat;
});
it("should detect and extract function calls from AI response", async () => {
const request: ChatCompletionRequest = {
model: "gpt-4o-mini",
messages: [{ role: "user", content: "What time is it?" }],
tools: [sampleTools[0]], // get_current_time
};
// Mock the DuckAI response to return a function call
const originalChat = openAIService["duckAI"].chat;
openAIService["duckAI"].chat = async () =>
JSON.stringify({
tool_calls: [
{
id: "call_1",
type: "function",
function: {
name: "get_current_time",
arguments: "{}",
},
},
],
});
const response = await openAIService.createChatCompletion(request);
expect(response.choices[0].message.role).toBe("assistant");
expect(response.choices[0].message.content).toBe(null);
expect(response.choices[0].message.tool_calls).toHaveLength(1);
expect(response.choices[0].message.tool_calls![0].function.name).toBe(
"get_current_time"
);
expect(response.choices[0].finish_reason).toBe("tool_calls");
// Restore original method
openAIService["duckAI"].chat = originalChat;
});
it("should handle tool_choice 'required'", async () => {
const request: ChatCompletionRequest = {
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Calculate 5 + 3" }],
tools: [sampleTools[1]], // calculate
tool_choice: "required",
};
// Mock the DuckAI response
const originalChat = openAIService["duckAI"].chat;
openAIService["duckAI"].chat = async (req) => {
// Verify that the system prompt contains the required instruction
const systemMessage = req.messages.find((m) => m.role === "system");
expect(systemMessage?.content).toContain(
"You MUST call at least one function"
);
return JSON.stringify({
tool_calls: [
{
id: "call_1",
type: "function",
function: {
name: "calculate",
arguments: '{"expression": "5 + 3"}',
},
},
],
});
};
const response = await openAIService.createChatCompletion(request);
expect(response.choices[0].finish_reason).toBe("tool_calls");
// Restore original method
openAIService["duckAI"].chat = originalChat;
});
it("should handle tool_choice 'none'", async () => {
const request: ChatCompletionRequest = {
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Hello" }],
tools: sampleTools,
tool_choice: "none",
};
// Mock the DuckAI response
const originalChat = openAIService["duckAI"].chat;
openAIService["duckAI"].chat = async () =>
"Hello! How can I help you today?";
const response = await openAIService.createChatCompletion(request);
expect(response.choices[0].message.content).toBe(
"Hello! How can I help you today?"
);
expect(response.choices[0].finish_reason).toBe("stop");
// Restore original method
openAIService["duckAI"].chat = originalChat;
});
});
describe("createChatCompletionStream with tools", () => {
it("should handle streaming with function calls", async () => {
const request: ChatCompletionRequest = {
model: "gpt-4o-mini",
messages: [{ role: "user", content: "What time is it?" }],
tools: sampleTools,
stream: true,
};
// Mock the DuckAI response to include function calls
const originalChat = openAIService["duckAI"].chat;
openAIService["duckAI"].chat = async () =>
JSON.stringify({
tool_calls: [
{
id: "call_1",
type: "function",
function: {
name: "get_current_time",
arguments: "{}",
},
},
],
});
const stream = await openAIService.createChatCompletionStream(request);
const chunks: string[] = [];
const reader = stream.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) {
const text = new TextDecoder().decode(value);
chunks.push(text);
}
}
const fullResponse = chunks.join("");
expect(fullResponse).toContain("data:");
expect(fullResponse).toContain("[DONE]");
// Restore original method
openAIService["duckAI"].chat = originalChat;
});
it("should handle streaming without tools", async () => {
const request: ChatCompletionRequest = {
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Hello!" }],
stream: true,
};
// Mock the DuckAI response
const originalChat = openAIService["duckAI"].chat;
openAIService["duckAI"].chat = async () => "Hello! How can I help you?";
const stream = await openAIService.createChatCompletionStream(request);
const chunks: string[] = [];
const reader = stream.getReader();
let chunkCount = 0;
while (true && chunkCount < 10) {
// Limit chunks to prevent infinite loop
const { done, value } = await reader.read();
if (done) break;
if (value) {
const text = new TextDecoder().decode(value);
chunks.push(text);
}
chunkCount++;
}
const fullResponse = chunks.join("");
expect(fullResponse).toContain("data:");
// Restore original method
openAIService["duckAI"].chat = originalChat;
});
});
describe("Advanced Tool Scenarios", () => {
it("should handle tool_choice with specific function", async () => {
const request: ChatCompletionRequest = {
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Calculate something" }],
tools: sampleTools,
tool_choice: {
type: "function",
function: { name: "calculate" },
},
};
// Mock the DuckAI response
const originalChat = openAIService["duckAI"].chat;
openAIService["duckAI"].chat = async () => "I'll calculate that for you.";
const response = await openAIService.createChatCompletion(request);
// Should force the specific function call
expect(response.choices[0].finish_reason).toBe("tool_calls");
expect(response.choices[0].message.tool_calls).toHaveLength(1);
expect(response.choices[0].message.tool_calls![0].function.name).toBe(
"calculate"
);
// Restore original method
openAIService["duckAI"].chat = originalChat;
});
it("should handle empty response from Duck.ai gracefully", async () => {
const request: ChatCompletionRequest = {
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Test" }],
tools: sampleTools,
tool_choice: "required",
};
// Mock empty response
const originalChat = openAIService["duckAI"].chat;
openAIService["duckAI"].chat = async () => "";
const response = await openAIService.createChatCompletion(request);
// Should still generate a function call due to tool_choice: required
expect(response.choices[0].finish_reason).toBe("tool_calls");
expect(response.choices[0].message.tool_calls).toHaveLength(1);
// Restore original method
openAIService["duckAI"].chat = originalChat;
});
it("should handle conversation with multiple tool calls", async () => {
const request: ChatCompletionRequest = {
model: "gpt-4o-mini",
messages: [
{ role: "user", content: "What time is it and what's 2+2?" },
{
role: "assistant",
content: null,
tool_calls: [
{
id: "call_1",
type: "function",
function: { name: "get_current_time", arguments: "{}" },
},
],
},
{
role: "tool",
content: "2024-01-15T10:30:00Z",
tool_call_id: "call_1",
},
],
tools: sampleTools,
};
// Mock the DuckAI response
const originalChat = openAIService["duckAI"].chat;
openAIService["duckAI"].chat = async () =>
"The time is 2024-01-15T10:30:00Z. Now let me calculate 2+2.";
const response = await openAIService.createChatCompletion(request);
expect(response.choices[0].message.role).toBe("assistant");
expect(response.choices[0].message.content).toContain(
"2024-01-15T10:30:00Z"
);
// Restore original method
openAIService["duckAI"].chat = originalChat;
});
it("should handle custom registered functions", async () => {
// Register a custom function
const customFunction = (args: { name: string }) => `Hello, ${args.name}!`;
openAIService.registerFunction("greet", customFunction);
const toolCall: ToolCall = {
id: "call_1",
type: "function",
function: {
name: "greet",
arguments: '{"name": "Alice"}',
},
};
const result = await openAIService.executeToolCall(toolCall);
expect(result).toBe("Hello, Alice!");
});
it("should handle tool validation edge cases", () => {
// Test with empty tools array
expect(() => {
openAIService.validateRequest({
model: "gpt-4o-mini",
messages: [{ role: "user", content: "test" }],
tools: [],
});
}).not.toThrow();
// Test with null tools
expect(() => {
openAIService.validateRequest({
model: "gpt-4o-mini",
messages: [{ role: "user", content: "test" }],
tools: null,
});
}).not.toThrow();
});
it("should handle malformed tool_calls in assistant messages", () => {
const request = {
model: "gpt-4o-mini",
messages: [
{
role: "assistant",
content: null,
tool_calls: [
{
// Missing required fields
type: "function",
},
],
},
],
};
// Should not throw during validation - malformed tool_calls are handled during execution
expect(() => openAIService.validateRequest(request)).not.toThrow();
});
it("should handle concurrent tool executions", async () => {
const slowFunction = async (args: any) => {
await new Promise((resolve) => setTimeout(resolve, 50));
return `Slow result: ${args.input}`;
};
openAIService.registerFunction("slow_func", slowFunction);
const toolCalls = [
{
id: "call_1",
type: "function" as const,
function: { name: "slow_func", arguments: '{"input": "test1"}' },
},
{
id: "call_2",
type: "function" as const,
function: { name: "slow_func", arguments: '{"input": "test2"}' },
},
];
const results = await Promise.all(
toolCalls.map((call) => openAIService.executeToolCall(call))
);
expect(results).toHaveLength(2);
expect(results[0]).toBe("Slow result: test1");
expect(results[1]).toBe("Slow result: test2");
});
// Additional advanced scenarios
it("should handle tool_choice with non-existent function gracefully", async () => {
const request: ChatCompletionRequest = {
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Test" }],
tools: sampleTools,
tool_choice: {
type: "function",
function: { name: "non_existent_function" },
},
};
// Mock the DuckAI response
const originalChat = openAIService["duckAI"].chat;
openAIService["duckAI"].chat = async () => "I'll help you with that.";
const response = await openAIService.createChatCompletion(request);
// Should still force the non-existent function call (validation happens at execution time)
expect(response.choices[0].finish_reason).toBe("tool_calls");
expect(response.choices[0].message.tool_calls).toHaveLength(1);
expect(response.choices[0].message.tool_calls![0].function.name).toBe(
"non_existent_function"
);
// Restore original method
openAIService["duckAI"].chat = originalChat;
});
it("should handle complex tool arguments extraction", async () => {
const request: ChatCompletionRequest = {
model: "gpt-4o-mini",
messages: [
{ role: "user", content: "Calculate the result of 15 * 8 + 42" },
],
tools: [sampleTools[1]], // calculate function
tool_choice: "required",
};
// Mock empty response to trigger fallback
const originalChat = openAIService["duckAI"].chat;
openAIService["duckAI"].chat = async () => "";
const response = await openAIService.createChatCompletion(request);
expect(response.choices[0].finish_reason).toBe("tool_calls");
expect(response.choices[0].message.tool_calls).toHaveLength(1);
expect(response.choices[0].message.tool_calls![0].function.name).toBe(
"calculate"
);
// Should extract the math expression
const args = JSON.parse(
response.choices[0].message.tool_calls![0].function.arguments
);
expect(args.expression).toBe("15 * 8");
// Restore original method
openAIService["duckAI"].chat = originalChat;
});
it("should handle weather function with location extraction", async () => {
const request: ChatCompletionRequest = {
model: "gpt-4o-mini",
messages: [
{
role: "user",
content: "What's the weather like in San Francisco?",
},
],
tools: [sampleTools[2]], // weather function
tool_choice: "required",
};
// Mock empty response to trigger fallback
const originalChat = openAIService["duckAI"].chat;
openAIService["duckAI"].chat = async () => "";
const response = await openAIService.createChatCompletion(request);
expect(response.choices[0].finish_reason).toBe("tool_calls");
expect(response.choices[0].message.tool_calls).toHaveLength(1);
expect(response.choices[0].message.tool_calls![0].function.name).toBe(
"get_weather"
);
// Should extract the location
const args = JSON.parse(
response.choices[0].message.tool_calls![0].function.arguments
);
expect(args.location).toBe("San Francisco");
// Restore original method
openAIService["duckAI"].chat = originalChat;
});
it("should handle mixed content with function calls", async () => {
const request: ChatCompletionRequest = {
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Hello! What time is it?" }],
tools: sampleTools,
};
// Mock response with mixed content and function call
const originalChat = openAIService["duckAI"].chat;
openAIService["duckAI"].chat = async () =>
JSON.stringify({
message: "Hello! Let me check the time for you.",
tool_calls: [
{
id: "call_1",
type: "function",
function: {
name: "get_current_time",
arguments: "{}",
},
},
],
});
const response = await openAIService.createChatCompletion(request);
expect(response.choices[0].finish_reason).toBe("tool_calls");
expect(response.choices[0].message.tool_calls).toHaveLength(1);
expect(response.choices[0].message.tool_calls![0].function.name).toBe(
"get_current_time"
);
// Restore original method
openAIService["duckAI"].chat = originalChat;
});
it("should handle function execution with complex return types", async () => {
// Register a function that returns various data types
const complexReturnFunction = (args: { type: string }) => {
switch (args.type) {
case "array":
return [1, 2, 3, "four", { five: 5 }];
case "object":
return { nested: { data: "value" }, array: [1, 2, 3] };
case "null":
return null;
case "boolean":
return true;
case "number":
return 42.5;
default:
return "string result";
}
};
openAIService.registerFunction("complex_return", complexReturnFunction);
const testCases = [
{ type: "array", expected: [1, 2, 3, "four", { five: 5 }] },
{
type: "object",
expected: { nested: { data: "value" }, array: [1, 2, 3] },
},
{ type: "null", expected: null },
{ type: "boolean", expected: true },
{ type: "number", expected: 42.5 },
{ type: "string", expected: "string result" },
];
for (const testCase of testCases) {
const toolCall: ToolCall = {
id: "call_1",
type: "function",
function: {
name: "complex_return",
arguments: JSON.stringify({ type: testCase.type }),
},
};
const result = await openAIService.executeToolCall(toolCall);
// Handle string results differently - they're returned as-is, not JSON-encoded
if (testCase.type === "string") {
expect(result).toBe(testCase.expected as string);
} else {
const parsed = JSON.parse(result);
expect(parsed).toEqual(testCase.expected);
}
}
});
});
});
|