-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib_test.go
More file actions
543 lines (477 loc) · 16.9 KB
/
lib_test.go
File metadata and controls
543 lines (477 loc) · 16.9 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
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
package llm_test
import (
"encoding/json"
"os"
"strings"
"testing"
"time"
"github.com/Back-to-code/go-llm"
"github.com/Back-to-code/go-llm/googleaistudio"
"github.com/Back-to-code/go-llm/inception"
"github.com/Back-to-code/go-llm/openai"
"github.com/Back-to-code/go-llm/togetherai"
"github.com/joho/godotenv"
)
func init() {
// Load .env file if present; ignore errors (env vars may already be set).
_ = godotenv.Load()
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
func skipIfEnvMissing(t *testing.T, key string) {
t.Helper()
if strings.TrimSpace(os.Getenv(key)) == "" {
t.Skipf("skipping: %s environment variable not set", key)
}
}
// weatherTool returns a simple tool that the model can call.
// It accepts a JSON object with a "city" field and returns a static forecast.
func weatherTool() llm.Tool {
return llm.Tool{
Type: "function",
Function: llm.FunctionDef{
Name: "get_weather",
Description: "Get the current weather for a city",
Parameters: json.RawMessage(`{
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "The city name"
}
},
"required": ["city"]
}`),
},
Resolver: func(args json.RawMessage) (any, error) {
return map[string]any{
"city": "Amsterdam",
"temperature": "18°C",
"condition": "Partly cloudy",
}, nil
},
}
}
// assertResponse validates all the common invariants of a Response.
func assertResponse(t *testing.T, resp llm.Response, err error) {
t.Helper()
if err != nil {
t.Fatalf("expected no error, got: %v", err)
}
if resp.Value == "" {
t.Fatal("expected non-empty Value")
}
if resp.String() != resp.Value {
t.Fatalf("String() = %q, want %q", resp.String(), resp.Value)
}
if len(resp.Conversation) == 0 {
t.Fatal("expected non-empty Conversation")
}
// The last message in the conversation should be the assistant response.
last := resp.Conversation[len(resp.Conversation)-1]
if last.Role != "assistant" {
t.Fatalf("expected last conversation message role to be 'assistant', got %q", last.Role)
}
if last.Content != resp.Value {
t.Fatalf("expected last conversation message content to equal Value:\n content = %q\n value = %q", last.Content, resp.Value)
}
}
func assertUsageNonZero(t *testing.T, usage llm.TokenUsage) {
t.Helper()
if usage.InputTokens <= 0 {
t.Errorf("expected InputTokens > 0, got %d", usage.InputTokens)
}
if usage.OutputTokens <= 0 {
t.Errorf("expected OutputTokens > 0, got %d", usage.OutputTokens)
}
}
// ---------------------------------------------------------------------------
// OpenAI
// ---------------------------------------------------------------------------
func TestOpenAI(t *testing.T) {
skipIfEnvMissing(t, "OPENAI_TOKEN")
provider := &openai.Provider{}
model := &llm.Model{Name: "gpt-5.4-nano", Provider: provider}
t.Run("PromptSingle", func(t *testing.T) {
resp, err := model.PromptSingle("Reply with only the word 'hello'.", llm.Options{NoRetry: true})
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
if !strings.Contains(strings.ToLower(resp.Value), "hello") {
t.Errorf("expected response to contain 'hello', got: %q", resp.Value)
}
// Conversation should have at least user + assistant.
if len(resp.Conversation) < 2 {
t.Fatalf("expected at least 2 messages in conversation, got %d", len(resp.Conversation))
}
if resp.Conversation[0].Role != "user" {
t.Errorf("expected first message role 'user', got %q", resp.Conversation[0].Role)
}
})
t.Run("Prompt", func(t *testing.T) {
messages := []llm.Message{
llm.System("You are a helpful assistant. Always reply in one short sentence."),
llm.User("What is 2+2?"),
}
resp, err := model.Prompt(messages, llm.Options{NoRetry: true})
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
// Conversation should have system + user + assistant = at least 3.
if len(resp.Conversation) < 3 {
t.Fatalf("expected at least 3 messages in conversation, got %d", len(resp.Conversation))
}
})
t.Run("PromptWithTools", func(t *testing.T) {
resp, err := model.Prompt(
[]llm.Message{
llm.System("You have access to a weather tool. Use it to answer the question. After getting the result, reply with a short sentence."),
llm.User("What is the weather in Amsterdam?"),
},
llm.Options{
NoRetry: true,
Tools: []llm.Tool{weatherTool()},
},
)
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
// With tool calls the conversation should contain intermediate messages:
// system, user, assistant (tool_calls), tool (response), assistant (final).
// That's at least 5 messages.
if len(resp.Conversation) < 5 {
t.Fatalf("expected at least 5 messages in conversation with tool calls, got %d", len(resp.Conversation))
}
// Verify tool call messages exist in the conversation.
hasToolCall := false
hasToolResponse := false
for _, msg := range resp.Conversation {
if msg.Role == "assistant" && len(msg.ToolCalls) > 0 {
hasToolCall = true
}
if msg.Role == "tool" {
hasToolResponse = true
}
}
if !hasToolCall {
t.Error("expected at least one assistant message with ToolCalls in conversation")
}
if !hasToolResponse {
t.Error("expected at least one tool response message in conversation")
}
// Usage should be accumulated across the tool-call round-trips,
// so input tokens should be higher than a simple prompt because
// the conversation grew between rounds.
if resp.Usage.InputTokens < 10 {
t.Errorf("expected accumulated InputTokens to be significant, got %d", resp.Usage.InputTokens)
}
})
t.Run("PromptJSON", func(t *testing.T) {
resp, err := model.PromptSingle(
`Return a JSON object with a single key "color" and value "blue". No other text.`,
llm.Options{
NoRetry: true,
ResponseFormat: llm.ResponseFormatJsonObject,
},
)
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
var parsed map[string]string
if err := json.Unmarshal([]byte(resp.Value), &parsed); err != nil {
t.Fatalf("expected valid JSON response, got parse error: %v\nraw: %q", err, resp.Value)
}
if parsed["color"] != "blue" {
t.Errorf("expected color=blue, got %q", parsed["color"])
}
})
t.Run("YesNo", func(t *testing.T) {
result, err := llm.YesNo(model.PromptSingle("Is the sky blue? Reply with only yes or no.", llm.Options{NoRetry: true}))
if err != nil {
t.Fatalf("expected no error, got: %v", err)
}
if !result {
t.Error("expected YesNo to return true for 'is the sky blue'")
}
})
}
// ---------------------------------------------------------------------------
// Google AI Studio
// ---------------------------------------------------------------------------
func TestGoogleAIStudio(t *testing.T) {
skipIfEnvMissing(t, "GOOGLE_AI_STUDIO_KEY")
provider := &googleaistudio.Provider{}
model := &llm.Model{Name: "gemini-3.1-flash-lite-preview", Provider: provider}
t.Run("PromptSingle", func(t *testing.T) {
resp, err := model.PromptSingle("Reply with only the word 'hello'.", llm.Options{NoRetry: true})
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
if !strings.Contains(strings.ToLower(resp.Value), "hello") {
t.Errorf("expected response to contain 'hello', got: %q", resp.Value)
}
if len(resp.Conversation) < 2 {
t.Fatalf("expected at least 2 messages in conversation, got %d", len(resp.Conversation))
}
if resp.Conversation[0].Role != "user" {
t.Errorf("expected first message role 'user', got %q", resp.Conversation[0].Role)
}
})
t.Run("Prompt", func(t *testing.T) {
messages := []llm.Message{
llm.System("You are a helpful assistant. Always reply in one short sentence."),
llm.User("What is 2+2?"),
}
resp, err := model.Prompt(messages, llm.Options{NoRetry: true})
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
// System message is extracted as system_instruction in Google AI Studio,
// so the conversation passed to the provider only has user + assistant.
// But from Model.Prompt's perspective the original messages are preserved.
if len(resp.Conversation) < 3 {
t.Fatalf("expected at least 3 messages in conversation, got %d", len(resp.Conversation))
}
})
t.Run("PromptWithTools", func(t *testing.T) {
resp, err := model.Prompt(
[]llm.Message{
llm.System("You have access to a weather tool. Use it to answer the question. After getting the result, reply with a short sentence."),
llm.User("What is the weather in Amsterdam?"),
},
llm.Options{
NoRetry: true,
Tools: []llm.Tool{weatherTool()},
},
)
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
if len(resp.Conversation) < 5 {
t.Fatalf("expected at least 5 messages in conversation with tool calls, got %d", len(resp.Conversation))
}
hasToolCall := false
hasToolResponse := false
for _, msg := range resp.Conversation {
if msg.Role == "assistant" && len(msg.ToolCalls) > 0 {
hasToolCall = true
}
if msg.Role == "tool" {
hasToolResponse = true
}
}
if !hasToolCall {
t.Error("expected at least one assistant message with ToolCalls in conversation")
}
if !hasToolResponse {
t.Error("expected at least one tool response message in conversation")
}
})
t.Run("PromptJSON", func(t *testing.T) {
resp, err := model.PromptSingle(
`Return a JSON object with a single key "color" and value "blue". No other text.`,
llm.Options{
NoRetry: true,
ResponseFormat: llm.ResponseFormatJsonObject,
},
)
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
var parsed map[string]string
if err := json.Unmarshal([]byte(resp.Value), &parsed); err != nil {
t.Fatalf("expected valid JSON response, got parse error: %v\nraw: %q", err, resp.Value)
}
if parsed["color"] != "blue" {
t.Errorf("expected color=blue, got %q", parsed["color"])
}
})
t.Run("YesNo", func(t *testing.T) {
result, err := llm.YesNo(model.PromptSingle("Is the sky blue? Reply with only yes or no.", llm.Options{NoRetry: true}))
if err != nil {
t.Fatalf("expected no error, got: %v", err)
}
if !result {
t.Error("expected YesNo to return true for 'is the sky blue'")
}
})
}
// ---------------------------------------------------------------------------
// Together AI
// ---------------------------------------------------------------------------
func TestTogetherAI(t *testing.T) {
skipIfEnvMissing(t, "TOGETHER_AI_TOKEN")
provider := &togetherai.Provider{}
model := &llm.Model{Name: "Qwen/Qwen3.5-9B", Provider: provider}
// Together AI can be slow/flaky, use a longer timeout and allow retries.
opts := llm.Options{Timeout: 60 * time.Second}
t.Run("PromptSingle", func(t *testing.T) {
resp, err := model.PromptSingle("Reply with only the word 'hello'.", opts)
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
if !strings.Contains(strings.ToLower(resp.Value), "hello") {
t.Errorf("expected response to contain 'hello', got: %q", resp.Value)
}
if len(resp.Conversation) < 2 {
t.Fatalf("expected at least 2 messages in conversation, got %d", len(resp.Conversation))
}
if resp.Conversation[0].Role != "user" {
t.Errorf("expected first message role 'user', got %q", resp.Conversation[0].Role)
}
})
t.Run("Prompt", func(t *testing.T) {
messages := []llm.Message{
llm.System("You are a helpful assistant. Always reply in one short sentence."),
llm.User("What is 2+2?"),
}
resp, err := model.Prompt(messages, opts)
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
if len(resp.Conversation) < 3 {
t.Fatalf("expected at least 3 messages in conversation, got %d", len(resp.Conversation))
}
})
t.Run("PromptJSON", func(t *testing.T) {
resp, err := model.PromptSingle(
`Return a JSON object with a single key "color" and value "blue". No other text.`,
llm.Options{
Timeout: 60 * time.Second,
ResponseFormat: llm.ResponseFormatJsonObject,
},
)
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
var parsed map[string]string
if err := json.Unmarshal([]byte(resp.Value), &parsed); err != nil {
t.Fatalf("expected valid JSON response, got parse error: %v\nraw: %q", err, resp.Value)
}
if parsed["color"] != "blue" {
t.Errorf("expected color=blue, got %q", parsed["color"])
}
})
t.Run("YesNo", func(t *testing.T) {
result, err := llm.YesNo(model.PromptSingle("Is the sky blue? Reply with only yes or no.", opts))
if err != nil {
t.Fatalf("expected no error, got: %v", err)
}
if !result {
t.Error("expected YesNo to return true for 'is the sky blue'")
}
})
// Together AI does not support tools, verify it errors correctly.
t.Run("ToolsUnsupported", func(t *testing.T) {
_, err := model.Prompt(
[]llm.Message{llm.User("What is the weather?")},
llm.Options{
NoRetry: true,
Tools: []llm.Tool{weatherTool()},
},
)
if err == nil {
t.Fatal("expected error when using tools with Together AI provider")
}
if !strings.Contains(err.Error(), "does not support tools") {
t.Errorf("expected 'does not support tools' error, got: %v", err)
}
})
// Together AI does not support streaming, verify it errors correctly.
t.Run("StreamUnsupported", func(t *testing.T) {
_, err := model.Stream(
[]llm.Message{llm.User("Hello")},
llm.Options{NoRetry: true},
)
if err == nil {
t.Fatal("expected error when using streaming with Together AI provider")
}
if !strings.Contains(err.Error(), "does not support streaming") {
t.Errorf("expected 'does not support streaming' error, got: %v", err)
}
})
}
// ---------------------------------------------------------------------------
// Inception
// ---------------------------------------------------------------------------
func TestInception(t *testing.T) {
skipIfEnvMissing(t, "INCEPTION_API_KEY")
provider := &inception.Provider{}
model := &llm.Model{Name: "mercury-2", Provider: provider}
t.Run("PromptSingle", func(t *testing.T) {
resp, err := model.PromptSingle("Reply with only the word 'hello'.", llm.Options{NoRetry: true})
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
if !strings.Contains(strings.ToLower(resp.Value), "hello") {
t.Errorf("expected response to contain 'hello', got: %q", resp.Value)
}
if len(resp.Conversation) < 2 {
t.Fatalf("expected at least 2 messages in conversation, got %d", len(resp.Conversation))
}
if resp.Conversation[0].Role != "user" {
t.Errorf("expected first message role 'user', got %q", resp.Conversation[0].Role)
}
})
t.Run("Prompt", func(t *testing.T) {
messages := []llm.Message{
llm.System("You are a helpful assistant. Always reply in one short sentence."),
llm.User("What is 2+2?"),
}
resp, err := model.Prompt(messages, llm.Options{NoRetry: true})
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
if len(resp.Conversation) < 3 {
t.Fatalf("expected at least 3 messages in conversation, got %d", len(resp.Conversation))
}
})
t.Run("PromptWithTools", func(t *testing.T) {
resp, err := model.Prompt(
[]llm.Message{
llm.System("You have access to a weather tool. Use it to answer the question. After getting the result, reply with a short sentence."),
llm.User("What is the weather in Amsterdam?"),
},
llm.Options{
NoRetry: true,
Tools: []llm.Tool{weatherTool()},
},
)
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
if len(resp.Conversation) < 5 {
t.Fatalf("expected at least 5 messages in conversation with tool calls, got %d", len(resp.Conversation))
}
hasToolCall := false
hasToolResponse := false
for _, msg := range resp.Conversation {
if msg.Role == "assistant" && len(msg.ToolCalls) > 0 {
hasToolCall = true
}
if msg.Role == "tool" {
hasToolResponse = true
}
}
if !hasToolCall {
t.Error("expected at least one assistant message with ToolCalls in conversation")
}
if !hasToolResponse {
t.Error("expected at least one tool response message in conversation")
}
})
t.Run("PromptJSON", func(t *testing.T) {
resp, err := model.PromptSingle(
`Return a JSON object with a single key "color" and value "blue". No other text.`,
llm.Options{
NoRetry: true,
ResponseFormat: llm.ResponseFormatJsonObject,
},
)
assertResponse(t, resp, err)
assertUsageNonZero(t, resp.Usage)
var parsed map[string]string
if err := json.Unmarshal([]byte(resp.Value), &parsed); err != nil {
t.Fatalf("expected valid JSON response, got parse error: %v\nraw: %q", err, resp.Value)
}
if parsed["color"] != "blue" {
t.Errorf("expected color=blue, got %q", parsed["color"])
}
})
t.Run("YesNo", func(t *testing.T) {
result, err := llm.YesNo(model.PromptSingle("Is the sky blue? Reply with only yes or no.", llm.Options{NoRetry: true}))
if err != nil {
t.Fatalf("expected no error, got: %v", err)
}
if !result {
t.Error("expected YesNo to return true for 'is the sky blue'")
}
})
}