Repository navigation
Expand file tree
/
Copy pathprovider_gemini.go
More file actions
1761 lines (1664 loc) · 58.5 KB
/
Copy pathprovider_gemini.go
File metadata and controls
1761 lines (1664 loc) · 58.5 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
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package lm15
import (
"encoding/base64"
"encoding/binary"
"reflect"
"sort"
"strconv"
"strings"
"github.com/lm15-dev/lm15-go/v2/internal/sse"
)
// GeminiLM is the Google Gemini GenerateContent dialect.
type GeminiLM struct {
lmCore
uploadBaseURL string
}
const (
geminiDefaultBaseURL = "https://generativelanguage.googleapis.com/v1beta"
geminiDefaultUploadURL = "https://generativelanguage.googleapis.com/upload/v1beta"
)
var geminiBuiltinMap = map[string]string{"web_search": "googleSearch", "code_execution": "codeExecution"}
var geminiProviderExecutedKeys = []string{"executableCode", "codeExecutionResult"}
// NewGeminiLM constructs the Gemini dialect (default policy GeminiAPI).
func NewGeminiLM(opts ...Option) (*GeminiLM, error) {
o, err := applyOptions(opts)
if err != nil {
return nil, err
}
lm := &GeminiLM{uploadBaseURL: geminiDefaultUploadURL}
if o.uploadBaseURL != "" {
lm.uploadBaseURL = o.uploadBaseURL
}
lm.apiKeyHeader = "x-goog-api-key"
if err := lm.bindAccess(lm, GeminiAPI, o, geminiDefaultBaseURL); err != nil {
return nil, err
}
return lm, nil
}
// GeminiLevelClass reports the Gemini 3.x class (thinkingLevel, no full off).
func GeminiLevelClass(model string) bool {
lowered := strings.ToLower(model)
return strings.HasPrefix(lowered, "models/gemini-3") || strings.HasPrefix(lowered, "gemini-3")
}
var geminiErrorStatusMap = map[string]ErrorKind{
"INVALID_ARGUMENT": KindInvalidRequest, "FAILED_PRECONDITION": KindBilling, "PERMISSION_DENIED": KindAuth, "UNAUTHENTICATED": KindAuth,
"NOT_FOUND": KindInvalidRequest, "RESOURCE_EXHAUSTED": KindRateLimit, "INTERNAL": KindServer, "UNAVAILABLE": KindServer, "DEADLINE_EXCEEDED": KindTimeout,
}
var geminiCandidateFinishErrors = map[string]bool{
"SAFETY": true, "RECITATION": true, "LANGUAGE": true, "BLOCKLIST": true, "PROHIBITED_CONTENT": true, "SPII": true,
"MALFORMED_FUNCTION_CALL": true, "IMAGE_SAFETY": true, "IMAGE_PROHIBITED_CONTENT": true, "IMAGE_OTHER": true, "NO_IMAGE": true,
"IMAGE_RECITATION": true, "UNEXPECTED_TOOL_CALL": true, "TOO_MANY_TOOL_CALLS": true, "MISSING_THOUGHT_SIGNATURE": true, "MALFORMED_RESPONSE": true,
}
func geminiContextLengthMessage(msg string) bool {
l := strings.ToLower(msg)
return (strings.Contains(l, "token") && (strings.Contains(l, "limit") || strings.Contains(l, "exceed"))) ||
strings.Contains(l, "too long") || strings.Contains(l, "context is too long") || strings.Contains(l, "context length")
}
func (l *GeminiLM) errorDetail(providerCode, message string) ErrorDetail {
kind, ok := geminiErrorStatusMap[providerCode]
if !ok {
kind = KindProvider
}
if geminiContextLengthMessage(message) {
kind = KindContextLength
} else if providerCode == "NOT_FOUND" && isModelErrorMessage(message) {
kind = KindUnsupportedModel
}
msg := message
if msg == "" {
msg = providerCode
}
if msg == "" {
msg = "provider error"
}
if providerCode == "" {
providerCode = "provider"
}
return ErrorDetail{Code: kind.CanonicalCode(), Message: msg, ProviderCode: providerCode}
}
func (l *GeminiLM) inbandError(data JSONObject) *Error {
if pf := wireObj(data.Get("promptFeedback")); pf != nil {
if reason := wireStr(pf.Get("blockReason")); reason != "" && reason != "BLOCK_REASON_UNSPECIFIED" {
return l.providerError(KindInvalidRequest, "Prompt blocked: "+reason, 0, "promptFeedback", "")
}
}
candidates := wireList(data.Get("candidates"))
if len(candidates) > 0 {
if c := wireObj(candidates[0]); c != nil {
if fr := wireStr(c.Get("finishReason")); geminiCandidateFinishErrors[fr] {
msg := wireStr(c.Get("finishMessage"))
if msg == "" {
msg = "Candidate blocked: " + fr
}
return l.providerError(KindInvalidRequest, msg, 0, fr, "")
}
}
}
return nil
}
func (l *GeminiLM) normalizeError(status int, body string) *Error {
data, err := DecodeJSON([]byte(body))
if err != nil {
return l.lmCore.normalizeError(status, body)
}
obj := wireObj(data)
var msg, errStatus string
var reasons []string
if obj != nil {
switch e := jsonView(obj.Get("error")).(type) {
case JSONObject:
msg = wireStr(e.Get("message"))
errStatus = wireStr(e.Get("status"))
reasons = googleErrorReasons(e)
case nil:
default:
msg = wireStr(e)
}
}
if IsPinnedAuthFailure(errStatus, msg, reasons) { // MAP-18
return l.providerError(KindAuth, msg, status, errStatus, "")
}
if geminiContextLengthMessage(msg) {
return l.providerError(KindContextLength, msg, status, errStatus, "")
}
if errStatus == "NOT_FOUND" && isModelErrorMessage(msg) {
return l.providerError(KindUnsupportedModel, msg, status, errStatus, "")
}
if kind, ok := geminiErrorStatusMap[errStatus]; ok {
return l.providerError(kind, msg, status, errStatus, "")
}
if errStatus != "" && !strings.Contains(msg, errStatus) {
msg = msg + " (" + errStatus + ")"
}
if msg == "" {
msg = strings.TrimSpace(body)
if len(msg) > 500 {
msg = msg[:500]
}
if msg == "" {
msg = "HTTP " + strconv.Itoa(status)
}
}
return MapHTTPError(status, msg, l.provider, l.access.EnvKeys, errStatus, "", nil)
}
func (l *GeminiLM) modelPath(model string) string {
model = quoteSafe(model, "/:@")
if strings.HasPrefix(model, "models/") {
return model
}
return "models/" + model
}
func (l *GeminiLM) authHeaders(extra [][2]string) [][2]string {
return append([][2]string(nil), extra...)
}
func geminiNumber(v float64) any {
if v == float64(int64(v)) {
return int64(v)
}
return jsonFloat(v)
}
// geminiSchemaFields are the keys of Gemini's Schema object
// (generate-content#v1beta.Schema): what its OpenAPI fields parse.
var geminiSchemaFields = map[string]bool{
"type": true, "format": true, "title": true, "description": true, "nullable": true, "enum": true,
"maxItems": true, "minItems": true, "properties": true, "required": true, "minProperties": true,
"maxProperties": true, "minLength": true, "maxLength": true, "pattern": true, "example": true,
"anyOf": true, "propertyOrdering": true, "default": true, "items": true, "minimum": true, "maximum": true,
}
// jsonListOf reads any Go slice or array (a decoded []any, or a []string or
// []int a caller wrote) as a list; bytes are not a JSON list.
func jsonListOf(v any) ([]any, bool) {
if l, ok := v.([]any); ok {
return l, true
}
rv := reflect.ValueOf(v)
if !rv.IsValid() || (rv.Kind() != reflect.Slice && rv.Kind() != reflect.Array) || rv.Type().Elem().Kind() == reflect.Uint8 {
return nil, false
}
out := make([]any, rv.Len())
for i := range out {
out[i] = rv.Index(i).Interface()
}
return out, true
}
// geminiOpenAPISchema is MAP-16: can Gemini's OpenAPI field
// (responseSchema, functionDeclarations[].parameters) carry schema? No,
// when a schema node — the root, a value of properties, items, an element
// of anyOf (or anyOf itself when it is one object) — is a boolean, has a
// key that is not a field of Gemini's Schema object, has a list type, or
// has an enum list with an element that is not a string: the OpenAPI field
// answers 400 there and the JSON Schema field accepts it (live 2026-09-26,
// lm15-contract mapping/gemini-schema-field.json). Anything else stays on
// the OpenAPI field; example and default are values, never walked.
func geminiOpenAPISchema(schema any) bool {
stack := []any{schema}
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if _, ok := node.(bool); ok {
return false
}
obj, ok := jsonView(node).(JSONObject)
if !ok {
continue
}
for _, m := range obj {
if !geminiSchemaFields[m.Key] {
return false
}
switch m.Key {
case "type":
if _, isList := jsonListOf(m.Value); isList {
return false
}
case "enum":
if items, isList := jsonListOf(m.Value); isList {
for _, item := range items {
if _, isString := item.(string); !isString {
return false
}
}
}
case "properties":
if props, isObject := jsonView(m.Value).(JSONObject); isObject {
for _, p := range props {
stack = append(stack, p.Value)
}
}
case "items":
stack = append(stack, m.Value)
case "anyOf":
if items, isList := jsonListOf(m.Value); isList {
stack = append(stack, items...)
} else {
stack = append(stack, m.Value)
}
}
}
}
return true
}
// geminiFunctionDeclaration is MAP-16 for a tool: parameters or
// parametersJsonSchema, the schema verbatim either way (INV-002).
func geminiFunctionDeclaration(ft FunctionTool) JSONObject {
params := ft.EffectiveParameters()
field := "parameters"
if !geminiOpenAPISchema(params) {
field = "parametersJsonSchema"
}
return toolDeclaration(JSONObject{{"name", ft.Name}}, ft.Description, KV(field, params))
}
func geminiResponseFormat(f JSONObject) JSONObject {
if f.Get("type") == "json_object" {
return JSONObject{{"responseMimeType", "application/json"}}
}
schema := f.Get("schema")
field := "responseSchema"
if !geminiOpenAPISchema(schema) {
field = "responseJsonSchema"
}
return JSONObject{{"responseMimeType", "application/json"}, {field, schema}}
}
func modalityTokens(details any, modality string) *int {
list, ok := details.([]any)
if !ok {
return nil
}
sum := 0
found := false
for _, e := range list {
if obj := wireObj(e); obj != nil && wireStr(obj.Get("modality")) == modality {
sum += wireInt(obj.Get("tokenCount"), 0)
found = true
}
}
if !found {
return nil
}
return &sum
}
// geminiUsage is MAP-19 rule 6. Gemini counts the prompt, its own tool-use
// tokens, the answer and the thoughts side by side (the total is their sum):
// input is prompt + tool use, output is answer + thoughts, and the cached
// count is part of the prompt. Inside a present usageMetadata an absent
// counter is a reported 0 (proto3 JSON omits zeros); Gemini reports no
// cache-write count.
func geminiUsage(usage JSONObject, outputKeys ...string) Usage {
if len(usage) == 0 {
return Usage{}
}
count := func(key string) int { return intOr0(wireIntPtr(usage.Get(key))) }
answer := 0
for _, k := range outputKeys {
if v, ok := usage.Lookup(k); ok {
answer = intOr0(wireIntPtr(v))
break
}
}
thoughts := count("thoughtsTokenCount")
input := count("promptTokenCount") + count("toolUsePromptTokenCount")
output := answer + thoughts
cached := count("cachedContentTokenCount")
var inputAudio *int
for _, key := range []string{"promptTokensDetails", "toolUsePromptTokensDetails"} {
if a := modalityTokens(usage.Get(key), "AUDIO"); a != nil {
sum := intOr0(inputAudio) + *a
inputAudio = &sum
}
}
outputDetails := usage.Get("candidatesTokensDetails")
if outputDetails == nil {
outputDetails = usage.Get("responseTokensDetails")
}
return Usage{
InputTokens: &input,
OutputTokens: &output,
TotalTokens: wireIntPtr(usage.Get("totalTokenCount")),
CacheReadTokens: &cached,
ReasoningTokens: &thoughts,
InputAudioTokens: inputAudio,
OutputAudioTokens: modalityTokens(outputDetails, "AUDIO"),
}.Settle()
}
func thoughtSignatureState(part JSONObject) []ContinuationState {
sig, ok := part.Lookup("thoughtSignature")
if !ok || sig == nil {
return nil
}
return []ContinuationState{{Provider: "gemini", Kind: "thought_signature", Data: JSONObject{{"value", wireStr(sig)}}}}
}
func geminiFinish(reason string, hasToolCall bool) string {
if hasToolCall {
return FinishToolCall
}
switch strings.ToUpper(reason) {
case "MAX_TOKENS":
return FinishLength
case "SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII":
return FinishContentFilter
}
return FinishStop
}
func geminiBatchStatus(data JSONObject) string {
state := strings.ToUpper(wireStr(wireObj(data.Get("metadata")).Get("state")))
mapping := map[string]string{
"BATCH_STATE_PENDING": BatchQueued, "BATCH_STATE_RUNNING": BatchRunning, "BATCH_STATE_CANCELLING": BatchCancelling,
"BATCH_STATE_SUCCEEDED": BatchCompleted, "BATCH_STATE_FAILED": BatchFailed, "BATCH_STATE_CANCELLED": BatchCancelled, "BATCH_STATE_EXPIRED": BatchExpired,
}
if s, ok := mapping[state]; ok {
return s
}
if truthy(data.Get("done")) {
return BatchCompleted
}
return BatchQueued
}
func geminiTokenLogprobs(result any) []TokenLogprob {
lr := wireObj(result)
if lr == nil {
return nil
}
chosen := wireList(lr.Get("chosenCandidates"))
topSteps := wireList(lr.Get("topCandidates"))
var out []TokenLogprob
for i, c := range chosen {
cand := wireObj(c)
if cand == nil {
continue
}
var top []TopLogprob
if i < len(topSteps) {
for _, a := range wireList(wireObj(topSteps[i]).Get("candidates")) {
if alt := wireObj(a); alt != nil {
top = append(top, TopLogprob{Token: wireStr(alt.Get("token")), Logprob: wireFloat(alt.Get("logProbability"), 0), TokenID: wireIntPtr(alt.Get("tokenId"))})
}
}
}
out = append(out, TokenLogprob{Token: wireStr(cand.Get("token")), Logprob: wireFloat(cand.Get("logProbability"), 0), TokenID: wireIntPtr(cand.Get("tokenId")), Top: top})
}
return out
}
func geminiSegmentText(segment JSONObject, full string) string {
if t := stringOnly(segment.Get("text")); t != "" {
return t
}
start, end := wireIntPtr(segment.Get("startIndex")), wireIntPtr(segment.Get("endIndex"))
if start != nil && end != nil && 0 <= *start && *start < *end && *end <= len(full) {
return full[*start:*end]
}
return ""
}
func geminiCitations(candidate JSONObject, full string) []Part {
grounding := wireObj(candidate.Get("groundingMetadata"))
if grounding == nil {
return nil
}
chunks := wireList(grounding.Get("groundingChunks"))
supports, ok := grounding.Get("groundingSupports").([]any)
if !ok {
return nil
}
seen := map[[3]string]bool{}
var out []Part
for _, s := range supports {
support := wireObj(s)
if support == nil {
continue
}
cited := geminiSegmentText(wireObj(support.Get("segment")), full)
indices, ok := support.Get("groundingChunkIndices").([]any)
if !ok {
continue
}
for _, raw := range indices {
idx := wireIntPtr(raw)
var chunk JSONObject
if idx != nil && *idx >= 0 && *idx < len(chunks) {
chunk = wireObj(chunks[*idx])
}
source := wireObj(chunk.Get("web"))
if source == nil {
source = wireObj(chunk.Get("retrievedContext"))
}
if source == nil {
source = wireObj(chunk.Get("googleSearch"))
}
url := firstStr(source.Get("uri"), source.Get("url"))
title := firstStr(source.Get("title"), source.Get("name"))
key := [3]string{url, title, cited}
if seen[key] || (url == "" && title == "" && cited == "") {
continue
}
seen[key] = true
out = append(out, CitationPart{URL: url, Title: title, Text: cited})
}
}
return out
}
// ─── Request serialization ───────────────────────────────────────────
func (l *GeminiLM) functionResponse(part ToolResultPart, names map[string]string) (JSONObject, error) {
var textParts, mediaParts []Part
for _, p := range part.Content {
if IsMediaPart(p) {
if p.Type() != "image" && p.Type() != "document" {
return nil, UnsupportedFeature(l.provider, "messages[*].tool_result["+part.ID+"].content["+p.Type()+"]", "%s: a %s part in tool_result %q cannot reach a functionResponse — multimodal function responses take images (png/jpeg/webp) and documents (pdf, text/plain) only (MAP-10)", l.provider, p.Type(), part.ID)
}
mediaParts = append(mediaParts, p)
} else {
textParts = append(textParts, p)
}
}
if len(mediaParts) > 0 {
// MAP-24: beside media, an empty text part writes nothing (the
// media is the result); alone, it is the empty output and is
// written.
kept := textParts[:0:0]
for _, p := range textParts {
if t, ok := p.(TextPart); ok && t.Text == "" {
continue
}
kept = append(kept, p)
}
textParts = kept
}
name := part.Name
if name == "" {
name = names[part.ID]
}
if name == "" {
return nil, UnsupportedFeature(l.provider, "messages[*].tool_result["+part.ID+"].name", "%s: tool_result %q needs a function name on the Gemini wire and no preceding assistant tool_call with that id is in the transcript; set ToolResultPart.name (MAP-10 rule 6)", l.provider, part.ID)
}
text, err := partsToText(textParts, l.provider, "functionResponse.response")
if err != nil {
return nil, err
}
var response JSONObject
switch {
case part.IsError:
response = JSONObject{{"error", text}}
case len(mediaParts) > 0 && len(textParts) == 0:
response = JSONObject{}
default:
response = JSONObject{{"result", text}}
}
fr := JSONObject{{"name", name}, {"response", response}}
if part.ID != "" {
fr.Set("id", part.ID)
}
if len(mediaParts) > 0 {
var blocks []any
for _, p := range mediaParts {
b, err := l.part(p, nil)
if err != nil {
return nil, err
}
blocks = append(blocks, b)
}
fr.Set("parts", blocks)
}
return JSONObject{{"functionResponse", fr}}, nil
}
func (l *GeminiLM) part(p Part, names map[string]string) (JSONObject, error) {
switch x := p.(type) {
case TextPart:
out := JSONObject{{"text", x.Text}}
if thought := ContinuationData(x.Continuation, "gemini", "thought_signature"); thought != nil && truthy(thought.Get("value")) {
out.Set("thoughtSignature", thought.Get("value"))
}
return out, nil
case DataPart:
// 2026-09-19 D3: a data part on a text wire is its compact JSON.
return JSONObject{{"text", DataPartText(x)}}, nil
case ToolCallPart:
fc := JSONObject{{"name", x.Name}, {"args", x.Input}}
if x.ID != "" {
fc.Set("id", x.ID)
}
out := JSONObject{{"functionCall", fc}}
if thought := ContinuationData(x.Continuation, "gemini", "thought_signature"); thought != nil && truthy(thought.Get("value")) {
out.Set("thoughtSignature", thought.Get("value"))
}
return out, nil
case ToolResultPart:
return l.functionResponse(x, names)
case ThinkingPart:
out := JSONObject{{"text", x.Text}}
if thought := ContinuationData(x.Continuation, "gemini", "thought_signature"); thought != nil && truthy(thought.Get("value")) {
out.Set("thought", true)
out.Set("thoughtSignature", thought.Get("value"))
}
return out, nil
}
if m, ok := MediaOf(p); ok {
mime := m.MediaType
if mime == "" {
mime = "application/octet-stream"
}
switch {
case m.URL != "":
return JSONObject{{"fileData", JSONObject{{"mimeType", mime}, {"fileUri", m.URL}}}}, nil
case m.FileID != "":
return JSONObject{{"fileData", JSONObject{{"mimeType", mime}, {"fileUri", m.FileID}}}}, nil
default:
b64, err := m.Base64()
if err != nil {
return nil, err
}
return JSONObject{{"inlineData", JSONObject{{"mimeType", mime}, {"data", b64}}}}, nil
}
}
return JSONObject{{"text", partText(p)}}, nil
}
// geminiWritesNothing is MAP-24 on this wire: a part that is only
// {"text": ""}. One that also carries a thoughtSignature is state this
// dialect consumes and goes back as the model sent it.
func geminiWritesNothing(wirePart JSONObject) bool {
if text, ok := wirePart.Get("text").(string); !ok || text != "" {
return false
}
for k := range wirePart.All() {
if k != "text" && k != "thought" {
return false
}
}
return true
}
// message is one content, or nil when it has nothing to write (MAP-24): a
// content with no parts is refused ("must include at least one parts
// field", live 2026-11-11), so a message whose parts all write nothing is
// not written.
func (l *GeminiLM) message(msg Message, names map[string]string) (JSONObject, error) {
if msg.Role == RoleDeveloper {
text, err := partsToText(msg.Parts, l.provider, "a developer turn")
if err != nil {
return nil, err
}
if text == "" {
return nil, nil
}
return JSONObject{{"role", "user"}, {"parts", []any{JSONObject{{"text", "[developer]\n" + text}}}}}, nil
}
role := "user"
if msg.Role == RoleAssistant {
role = "model"
}
var parts []any
for _, p := range msg.Parts {
b, err := l.part(p, names)
if err != nil {
return nil, err
}
if geminiWritesNothing(b) {
continue
}
parts = append(parts, b)
}
if len(parts) == 0 {
return nil, nil
}
return JSONObject{{"role", role}, {"parts", parts}}, nil
}
func callNames(messages []Message) map[string]string {
names := map[string]string{}
for _, m := range messages {
for _, p := range m.Parts {
if tc, ok := p.(ToolCallPart); ok && tc.ID != "" {
names[tc.ID] = tc.Name
}
}
}
return names
}
func (l *GeminiLM) toolConfigPayload(req *Request, scope *adaptScope) (JSONObject, error) {
tc := req.Config.ToolChoice
if tc == nil {
return nil, nil
}
if tc.Parallel != nil && !*tc.Parallel {
// MAP-13: no wire knob (live 2026-09-02: two calls came back on 2.5
// and 3.7 with the preference set). A preference; agent loops
// iterate tool-call parts as a list anyway. Dropped and recorded.
if err := scope.dropped("config.tool_choice.parallel", "GenerateContent has no parallel-tool-calls knob and may return several calls (OpenAI and Anthropic carry it)", false); err != nil {
return nil, err
}
}
mode := map[string]string{"none": "NONE", "required": "ANY", "auto": "AUTO"}[tc.EffectiveMode()]
cfg := JSONObject{{"mode", mode}}
if len(tc.Allowed) > 0 {
var builtins []string
for _, name := range tc.Allowed {
if _, ok := req.ToolByName(name).(BuiltinTool); ok {
builtins = append(builtins, name)
}
}
if len(builtins) > 0 {
// MAP-13 rule 4(b): the program depends on the forced tool running.
return nil, UnsupportedFeature(l.provider, "config.tool_choice.allowed", "gemini: cannot force builtin tools %v — functionCallingConfig addresses function declarations only; googleSearch/codeExecution have no tool_choice form (OpenAI Responses and Anthropic carry builtin forcing)", builtins)
}
cfg.Set("allowedFunctionNames", toAnyList(tc.Allowed, func(s string) any { return s }))
if tc.EffectiveMode() == "auto" {
cfg.Set("mode", "VALIDATED")
}
}
return JSONObject{{"functionCallingConfig", cfg}}, nil
}
func (l *GeminiLM) cacheResource(cacheID string) string {
if strings.HasPrefix(cacheID, "cachedContents/") {
return cacheID
}
return "cachedContents/" + cacheID
}
func (l *GeminiLM) payload(req *Request, scope *adaptScope) (JSONObject, error) {
cfg := req.Config
ext := copyObject(cfg.Extensions)
resource := ""
suffixFrom := 0
if c := cfg.Cache; c != nil && c.EffectiveMode() != "off" {
if c.Key != "" {
if err := scope.dropped("config.cache.key", "GenerateContent has no cache affinity key; implicit caching applies, and a stored cache (lm.cache(prefix), cache.resource) is the explicit tier", c.Key); err != nil {
return nil, err
}
}
if c.Retention != "" && c.Retention != "short" {
if err := scope.dropped("config.cache.retention", "GenerateContent takes no lifetime in-request; it belongs to the stored cache (cache_create(..., ttl_seconds=...) / cache_update)", c.Retention); err != nil {
return nil, err
}
}
if c.Resource != "" {
resource = c.Resource
if c.PrefixUntilIndex != nil {
idx := *c.PrefixUntilIndex
if idx > len(req.Messages)-1 {
idx = len(req.Messages) - 1
}
suffixFrom = idx + 1
}
}
}
wireMessages := req.Messages[suffixFrom:]
if resource != "" && len(wireMessages) == 0 {
return nil, valueErrorf("gemini: a request against a stored cache needs at least one message after the prefix")
}
names := callNames(req.Messages)
var contents []any
for _, m := range wireMessages {
wm, err := l.message(m, names)
if err != nil {
return nil, err
}
if wm == nil {
continue // MAP-24: nothing to write
}
contents = append(contents, wm)
}
if contents == nil {
contents = []any{}
}
payload := JSONObject{{"contents", contents}}
if resource != "" {
payload.Set("cachedContent", l.cacheResource(resource))
}
if req.System != nil && resource == "" {
text, err := systemText(req.System, l.provider)
if err != nil {
return nil, err
}
if text != "" { // MAP-24: a system prompt with no characters writes nothing
payload.Set("systemInstruction", JSONObject{{"parts", []any{JSONObject{{"text", text}}}}})
}
}
gen := JSONObject{}
if cfg.Temperature != nil {
gen.Set("temperature", geminiNumber(*cfg.Temperature))
}
if cfg.MaxTokens != nil {
gen.Set("maxOutputTokens", *cfg.MaxTokens)
}
if cfg.TopP != nil {
gen.Set("topP", geminiNumber(*cfg.TopP))
}
if cfg.TopK != nil {
gen.Set("topK", *cfg.TopK)
}
if len(cfg.Stop) > 0 {
gen.Set("stopSequences", toAnyList(cfg.Stop, func(s string) any { return s }))
}
if cfg.Seed != nil {
gen.Set("seed", *cfg.Seed)
}
if cfg.FrequencyPenalty != nil {
gen.Set("frequencyPenalty", geminiNumber(*cfg.FrequencyPenalty))
}
if cfg.PresencePenalty != nil {
gen.Set("presencePenalty", geminiNumber(*cfg.PresencePenalty))
}
if cfg.Logprobs != nil {
gen.Set("responseLogprobs", true)
if *cfg.Logprobs > 0 {
gen.Set("logprobs", *cfg.Logprobs)
}
}
if len(cfg.ResponseFormat) > 0 {
// MAP-14 §2: judgment properties go as enum with descriptions folded
// into the property description — responseJsonSchema ignores
// anyOf/const (receipted 2026-09-17); probabilities cannot be
// measured here.
if err := noteUnmeasurableProbabilities(scope, req, l.provider); err != nil {
return nil, err
}
format := cfg.ResponseFormat
if found := RequestJudgments(req); len(found) > 0 {
if schema, ok := asObject(format.Get("schema")); ok {
format = copyObject(format)
format.Set("schema", geminiSchema(schema, found))
}
}
for k, v := range geminiResponseFormat(format).All() {
gen.Set(k, v)
}
}
if r := cfg.Reasoning; r != nil {
rr := *r
r = &rr
levelClass := GeminiLevelClass(req.Model)
if r.IsOff() && levelClass {
// MAP-13 (decision 2026-09-14 §4.2): the Gemini 3 class has no
// honoured off switch (thinkingBudget 0 accepted, 58 tokens still
// spent on 3.7 Flash, live 2026-09-02); the closest to "none" is
// the lowest level, and the spend shows in usage.reasoning_tokens.
if err := scope.substituted("config.reasoning.effort", req.Model+" cannot disable thinking (the Gemini 3 class honours no off switch); the lowest level was sent and the thinking spend is visible in usage", "off", "minimal"); err != nil {
return nil, err
}
r.Effort = "minimal"
}
if r.IsOff() {
gen.Set("thinkingConfig", JSONObject{{"thinkingBudget", 0}})
} else {
if r.Summary == "concise" || r.Summary == "detailed" {
if err := scope.substituted("config.reasoning.summary", "GenerateContent has includeThoughts only, no detail levels; 'auto' shows the thoughts", r.Summary, "auto"); err != nil {
return nil, err
}
r.Summary = "auto"
}
thinking := JSONObject{}
if r.Summary != "" {
thinking.Set("includeThoughts", true)
}
switch {
case r.ThinkingBudget != nil:
thinking.Set("thinkingBudget", *r.ThinkingBudget)
case levelClass:
effort := r.Effort
if effort == "xhigh" || effort == "max" {
if err := scope.clamped("config.reasoning.effort", "the Gemini 3 class has thinkingLevel minimal|low|medium|high; 'high' is the ceiling", effort, "high"); err != nil {
return nil, err
}
effort = "high"
}
thinking.Set("thinkingLevel", effort)
default:
thinking.Set("thinkingBudget", EffortThinkingBudgets[r.Effort])
}
gen.Set("thinkingConfig", thinking)
}
}
if len(gen) > 0 {
payload.Set("generationConfig", gen)
}
if len(req.Tools) > 0 && resource == "" {
var declarations []any
var tools []any
for _, t := range req.Tools {
if ft, ok := t.(FunctionTool); ok {
declarations = append(declarations, geminiFunctionDeclaration(ft))
}
}
if len(declarations) > 0 {
tools = append(tools, JSONObject{{"functionDeclarations", declarations}})
}
for _, t := range req.Tools {
if bt, ok := t.(BuiltinTool); ok {
tools = append(tools, geminiBuiltin(bt))
}
}
payload.Set("tools", tools)
}
if resource == "" {
tc, err := l.toolConfigPayload(req, scope)
if err != nil {
return nil, err
}
if tc != nil {
payload.Set("toolConfig", tc)
}
}
switch wireStr(ext.Get("output")) {
case "image":
setIn(&payload, []any{"IMAGE"}, "generationConfig", "responseModalities")
case "audio":
setIn(&payload, []any{"AUDIO"}, "generationConfig", "responseModalities")
}
if cfg.Store != nil {
payload.Set("store", *cfg.Store)
}
if cfg.ServiceTier != "" {
payload.Set("serviceTier", cfg.ServiceTier)
}
if cfg.UserID != "" {
// MAP-13 (decision 2026-09-14 §4.5): attribution has no field here
// and nothing in the program depends on it at run time; a
// compliance policy sets adaptations="refuse".
if err := scope.dropped("config.user_id", "GenerateContent has no end-user attribution field (OpenAI and Anthropic carry it)", cfg.UserID); err != nil {
return nil, err
}
}
for k, v := range ext.All() {
if k != "prompt_caching" && k != "output" {
payload.Set(k, v)
}
}
return payload, nil
}
func geminiBuiltin(t BuiltinTool) JSONObject {
key := t.Name
if mapped, ok := geminiBuiltinMap[t.Name]; ok {
key = mapped
}
cfg := t.Config
if cfg == nil {
cfg = JSONObject{}
}
return JSONObject{{key, cfg}}
}
func (l *GeminiLM) buildRequest(req *Request, stream bool, scope *adaptScope) (*TransportRequest, error) {
payload, err := l.payload(req, scope)
if err != nil {
return nil, err
}
endpoint := "generateContent"
var params map[string]string
if stream {
endpoint = "streamGenerateContent"
params = map[string]string{"alt": "sse"}
}
return l.emit(emitSpec{
method: "POST", url: strings.TrimRight(l.baseURL, "/") + "/" + l.modelPath(req.Model) + ":" + endpoint,
endpoint: "generateContent", stream: stream, model: req.Model,
headers: [][2]string{{"Content-Type", "application/json"}}, params: params, payload: payload, scope: scope,
})
}
// ─── Response parsing ────────────────────────────────────────────────
func (l *GeminiLM) parseCandidateParts(partsPayload []any, unmapped *[]JSONObject, pathPrefix string) ([]Part, error) {
var parts []Part
for i, raw := range partsPayload {
part := wireObj(raw)
path := pathPrefix + "[" + strconv.Itoa(i) + "]"
if part == nil {
if unmapped != nil {
recordUnmapped(unmapped, path, jsonTypeName(raw))
}
continue
}
_, hasText := part.Lookup("text")
switch {
case truthy(part.Get("thought")) && hasText:
parts = append(parts, ThinkingPart{Text: wireStr(part.Get("text")), Continuation: thoughtSignatureState(part)})
case hasText:
parts = append(parts, TextPart{Text: wireStr(part.Get("text")), Continuation: thoughtSignatureState(part)})
case wireObj(part.Get("functionCall")) != nil:
fc := wireObj(part.Get("functionCall"))
var continuation []ContinuationState
sig := part.Get("thoughtSignature")
if sig == nil {
sig = fc.Get("thoughtSignature")
}
if sig != nil {
continuation = []ContinuationState{{Provider: "gemini", Kind: "thought_signature", Data: JSONObject{{"value", wireStr(sig)}}}}
}
if !truthy(fc.Get("name")) {
return nil, unnamedToolCallError(l.provider, path)
}
id := wireStr(fc.Get("id"))
if id == "" || fc.Get("id") == nil {
id = "tool_call_" + strconv.Itoa(len(parts))
}
args := wireObj(fc.Get("args"))
if args == nil {
args = JSONObject{}
}
parts = append(parts, ToolCallPart{ID: id, Name: wireStr(fc.Get("name")), Input: args, Continuation: continuation})
case wireObj(part.Get("inlineData")) != nil:
inline := wireObj(part.Get("inlineData"))
mime := wireStr(inline.Get("mimeType"))
if mime == "" {
mime = "application/octet-stream"
}
data := wireStr(inline.Get("data"))
if data == "" {
continue
}
parts = append(parts, mediaPartFor(mime, Media{MediaType: mime, Data: data}))
case wireObj(part.Get("fileData")) != nil:
fd := wireObj(part.Get("fileData"))
uri := wireStr(fd.Get("fileUri"))
mime := wireStr(fd.Get("mimeType"))
if mime == "" {
mime = "application/octet-stream"
}
if uri == "" {
continue
}
parts = append(parts, mediaPartFor(mime, Media{MediaType: mime, URL: uri}))
case hasAnyKey(part, geminiProviderExecutedKeys):
default:
if unmapped != nil {
keys := sortedKeys(part)
t := strings.Join(keys, "+")
if t == "" {
t = "<empty>"