File size: 10,081 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
import { describe, it, expect, beforeEach } from "bun:test";
import { OpenAIService } from "../src/openai-service";
import type { ChatCompletionRequest, ToolDefinition } from "../src/types";

describe("Rate Limiting and Error Handling", () => {
  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"],
        },
      },
    },
  ];

  describe("Duck.ai API Error Handling", () => {
    it("should handle rate limiting gracefully with fallback", async () => {
      const request: ChatCompletionRequest = {
        model: "gpt-4o-mini",
        messages: [{ role: "user", content: "What time is it?" }],
        tools: sampleTools,
        tool_choice: "required",
      };

      // Mock Duck.ai to throw rate limit error
      const originalChat = openAIService["duckAI"].chat;
      openAIService["duckAI"].chat = async () => {
        throw new Error("429 Too Many Requests");
      };

      try {
        const response = await openAIService.createChatCompletion(request);

        // Should still work with fallback mechanism
        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"
        );
      } catch (error) {
        // If it throws, it should be handled gracefully
        expect(error).toBeInstanceOf(Error);
      } finally {
        // Restore original method
        openAIService["duckAI"].chat = originalChat;
      }
    });

    it("should handle empty responses with tool_choice required", async () => {
      const request: ChatCompletionRequest = {
        model: "gpt-4o-mini",
        messages: [{ role: "user", content: "Calculate 5 + 3" }],
        tools: sampleTools,
        tool_choice: "required",
      };

      // Mock Duck.ai to return empty response
      const originalChat = openAIService["duckAI"].chat;
      openAIService["duckAI"].chat = async () => "";

      const response = await openAIService.createChatCompletion(request);

      // Should generate appropriate function call based on user input
      expect(response.choices[0].finish_reason).toBe("tool_calls");
      expect(response.choices[0].message.tool_calls).toHaveLength(1);

      // Should choose calculate function based on the math expression in the message
      expect(response.choices[0].message.tool_calls![0].function.name).toBe(
        "calculate"
      );

      // Restore original method
      openAIService["duckAI"].chat = originalChat;
    });

    it("should handle network errors gracefully", async () => {
      const request: ChatCompletionRequest = {
        model: "gpt-4o-mini",
        messages: [{ role: "user", content: "Hello" }],
        tools: sampleTools,
      };

      // Mock Duck.ai to throw network error
      const originalChat = openAIService["duckAI"].chat;
      openAIService["duckAI"].chat = async () => {
        throw new Error("Network error");
      };

      try {
        await openAIService.createChatCompletion(request);
        // If it doesn't throw, that's fine - it means fallback worked
      } catch (error) {
        // If it throws, the error should be properly handled
        expect(error).toBeInstanceOf(Error);
        expect((error as Error).message).toContain("Network error");
      } finally {
        // Restore original method
        openAIService["duckAI"].chat = originalChat;
      }
    });

    it("should handle malformed responses from Duck.ai", async () => {
      const request: ChatCompletionRequest = {
        model: "gpt-4o-mini",
        messages: [{ role: "user", content: "Test" }],
        tools: sampleTools,
      };

      // Mock Duck.ai to return malformed response
      const originalChat = openAIService["duckAI"].chat;
      openAIService["duckAI"].chat = async () =>
        "This is not JSON and not a function call";

      const response = await openAIService.createChatCompletion(request);

      // Should handle as regular response
      expect(response.choices[0].message.role).toBe("assistant");
      expect(response.choices[0].message.content).toBe(
        "This is not JSON and not a function call"
      );
      expect(response.choices[0].finish_reason).toBe("stop");

      // Restore original method
      openAIService["duckAI"].chat = originalChat;
    });

    it("should handle partial JSON responses", async () => {
      const request: ChatCompletionRequest = {
        model: "gpt-4o-mini",
        messages: [{ role: "user", content: "Test" }],
        tools: sampleTools,
      };

      // Mock Duck.ai to return partial JSON
      const originalChat = openAIService["duckAI"].chat;
      openAIService["duckAI"].chat = async () =>
        '{"tool_calls": [{"id": "call_1", "type": "function"';

      const response = await openAIService.createChatCompletion(request);

      // Should handle as regular response since JSON is malformed
      expect(response.choices[0].message.role).toBe("assistant");
      expect(response.choices[0].finish_reason).toBe("stop");

      // Restore original method
      openAIService["duckAI"].chat = originalChat;
    });
  });

  describe("Resilience Testing", () => {
    it("should handle rapid consecutive requests", async () => {
      const requests = Array.from({ length: 5 }, (_, i) => ({
        model: "gpt-4o-mini",
        messages: [{ role: "user", content: `Test message ${i}` }],
        tools: sampleTools,
      }));

      // Mock Duck.ai with varying responses
      const originalChat = openAIService["duckAI"].chat;
      let callCount = 0;
      openAIService["duckAI"].chat = async () => {
        callCount++;
        if (callCount % 2 === 0) {
          throw new Error("Rate limited");
        }
        return `Response ${callCount}`;
      };

      const results = await Promise.allSettled(
        requests.map((req) => openAIService.createChatCompletion(req))
      );

      // All requests should either succeed or fail gracefully
      results.forEach((result, index) => {
        if (result.status === "fulfilled") {
          expect(result.value.choices[0].message.role).toBe("assistant");
        } else {
          expect(result.reason).toBeInstanceOf(Error);
        }
      });

      // Restore original method
      openAIService["duckAI"].chat = originalChat;
    });

    it("should maintain function execution capability during API issues", async () => {
      // Test that built-in functions still work even if Duck.ai is down
      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}/);
    });

    it("should handle streaming errors gracefully", async () => {
      const request: ChatCompletionRequest = {
        model: "gpt-4o-mini",
        messages: [{ role: "user", content: "Test streaming" }],
        stream: true,
      };

      // Mock Duck.ai to throw error during streaming
      const originalChat = openAIService["duckAI"].chat;
      openAIService["duckAI"].chat = async () => {
        throw new Error("Streaming error");
      };

      try {
        const stream = await openAIService.createChatCompletionStream(request);
        const reader = stream.getReader();

        // Should handle error in stream
        const { done, value } = await reader.read();

        if (value) {
          const text = new TextDecoder().decode(value);
          expect(text).toContain("data:");
        }
      } catch (error) {
        // Error should be handled gracefully
        expect(error).toBeInstanceOf(Error);
      } finally {
        // Restore original method
        openAIService["duckAI"].chat = originalChat;
      }
    });
  });

  describe("Fallback Mechanisms", () => {
    it("should use intelligent function selection when Duck.ai fails", async () => {
      const testCases = [
        {
          message: "What time is it now?",
          expectedFunction: "get_current_time",
        },
        {
          message: "Calculate 15 * 8 + 42",
          expectedFunction: "calculate",
        },
        {
          message: "Please compute 2 + 2",
          expectedFunction: "calculate",
        },
      ];

      // Mock Duck.ai to always fail
      const originalChat = openAIService["duckAI"].chat;
      openAIService["duckAI"].chat = async () => {
        throw new Error("API unavailable");
      };

      for (const testCase of testCases) {
        const request: ChatCompletionRequest = {
          model: "gpt-4o-mini",
          messages: [{ role: "user", content: testCase.message }],
          tools: sampleTools,
          tool_choice: "required",
        };

        try {
          const response = await openAIService.createChatCompletion(request);

          if (response.choices[0].finish_reason === "tool_calls") {
            expect(
              response.choices[0].message.tool_calls![0].function.name
            ).toBe(testCase.expectedFunction);
          }
        } catch (error) {
          // Fallback might not always work, but should not crash
          expect(error).toBeInstanceOf(Error);
        }
      }

      // Restore original method
      openAIService["duckAI"].chat = originalChat;
    });
  });
});