chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+430
View File
@@ -0,0 +1,430 @@
package googlegenai
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"academy/internal/logger"
"academy/internal/models/api"
"academy/internal/types"
)
const (
methodGenerate = "generateContent"
methodStreamGenerate = "streamGenerateContent"
)
// Client talks generateContent to one endpoint.
type Client struct {
cfg Config
}
// New creates a client. The endpoint must already carry auth and headers.
func New(cfg Config) *Client {
if cfg.ThinkingLevels == nil {
cfg.ThinkingLevels = api.ThinkingLevelMap{}
}
return &Client{cfg: cfg}
}
// GetModelName returns the wire model name.
func (c *Client) GetModelName() string { return c.cfg.Endpoint.Model }
// GetModelID returns Academy's model identifier.
func (c *Client) GetModelID() string { return c.cfg.Endpoint.ModelID }
// requestURL builds {base}/models/{model}:generateContent or
// {base}/models/{model}:streamGenerateContent?alt=sse. A bare host base URL
// gets Settings.APIVersionPrefix appended; an already versioned base is used
// as-is. An explicit Endpoint.URL overrides the path entirely.
func (c *Client) requestURL(stream bool) string {
ep := c.cfg.Endpoint
if ep.URL == "" {
base := strings.TrimRight(ep.BaseURL, "/")
if prefix := strings.Trim(c.cfg.Settings.APIVersionPrefix, "/"); prefix != "" && isBareHost(base) {
base += "/" + prefix
}
method := methodGenerate
if stream {
method = methodStreamGenerate
}
ep.URL = fmt.Sprintf("%s/models/%s:%s", base, ep.Model, method)
} else if stream && strings.HasSuffix(ep.URL, ":"+methodGenerate) {
// A vendor-supplied full URL names the non-streaming method; adding
// alt=sse to it would still return one buffered JSON document.
ep.URL = strings.TrimSuffix(ep.URL, ":"+methodGenerate) + ":" + methodStreamGenerate
}
if stream {
query := make(map[string]string, len(ep.Query)+1)
for k, v := range ep.Query {
query[k] = v
}
query["alt"] = "sse"
ep.Query = query
}
return ep.Resolve("")
}
func isBareHost(base string) bool {
u, err := url.Parse(base)
if err != nil {
return !strings.Contains(strings.TrimPrefix(strings.TrimPrefix(base, "https://"), "http://"), "/")
}
return u.Path == "" || u.Path == "/"
}
func (c *Client) send(
ctx context.Context, messages []api.Message, opts *api.Options, stream bool,
) (*http.Response, []byte, error) {
body, err := c.BuildRequestBody(messages, opts, stream)
if err != nil {
return nil, nil, err
}
target := c.requestURL(stream)
req, data, err := c.cfg.Endpoint.NewRequest(ctx, target, body, stream)
if err != nil {
return nil, nil, err
}
api.LogRequest(ctx, target, c.cfg.Endpoint.Model, data, stream)
resp, err := c.cfg.Endpoint.Do(req)
if err != nil {
return nil, data, err
}
return resp, data, nil
}
// Chat performs a non-streaming generation.
func (c *Client) Chat(ctx context.Context, messages []api.Message, opts *api.Options) (*types.ChatResponse, error) {
ctx, cancel := api.WithLLMTimeout(ctx, api.DefaultChatTimeout)
defer cancel()
resp, _, err := c.send(ctx, messages, opts, false)
if err != nil {
if api.IsMultimodalNotSupportedError(err) {
logger.Warnf(ctx, "[LLM Request] Model %s does not support multimodal, retrying without images",
c.cfg.Endpoint.Model)
resp, _, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, false)
}
if err != nil {
return nil, fmt.Errorf("create chat completion: %w", err)
}
}
defer func() { _ = resp.Body.Close() }()
raw, err := api.ReadResponseCapped(resp.Body, 0)
if err != nil {
return nil, fmt.Errorf("read response: %w", err)
}
result, err := c.parseResponse(raw)
if err != nil {
return nil, err
}
api.LogUsage(ctx, c.cfg.Endpoint.Model, &result.Usage)
return result, nil
}
// ChatStream performs a streaming generation over SSE.
func (c *Client) ChatStream(
ctx context.Context, messages []api.Message, opts *api.Options,
) (<-chan types.StreamResponse, error) {
ctx, cancel := api.WithLLMTimeout(ctx, api.DefaultStreamTimeout)
resp, data, err := c.send(ctx, messages, opts, true)
if err != nil {
if api.IsMultimodalNotSupportedError(err) {
logger.Warnf(ctx, "[LLM Stream] Model %s does not support multimodal, retrying without images",
c.cfg.Endpoint.Model)
resp, data, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, true)
}
if err != nil {
cancel()
return nil, fmt.Errorf("create chat completion stream: %w", err)
}
}
ch := make(chan types.StreamResponse)
dumper := api.NewStreamPacketDumper(c.cfg.Endpoint.Model, json.RawMessage(data))
if dumper != nil {
logger.Infof(ctx, "[LLM Stream Raw Dump] writing packets to %s", dumper.Path())
}
go func() {
defer cancel()
defer close(ch)
defer func() { _ = resp.Body.Close() }()
if dumper != nil {
defer dumper.Close()
}
c.processStream(ctx, resp.Body, ch, dumper)
}()
return ch, nil
}
// --- response decoding ---
type rawFunctionCall struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Args json.RawMessage `json:"args,omitempty"`
}
type rawPart struct {
Text string `json:"text,omitempty"`
Thought bool `json:"thought,omitempty"`
ThoughtSignature string `json:"thoughtSignature,omitempty"`
FunctionCall *rawFunctionCall `json:"functionCall,omitempty"`
}
type rawCandidate struct {
Content struct {
Role string `json:"role,omitempty"`
Parts []rawPart `json:"parts,omitempty"`
} `json:"content"`
FinishReason string `json:"finishReason,omitempty"`
}
type rawUsage struct {
PromptTokenCount int `json:"promptTokenCount"`
CandidatesTokenCount int `json:"candidatesTokenCount"`
ThoughtsTokenCount int `json:"thoughtsTokenCount"`
TotalTokenCount int `json:"totalTokenCount"`
CachedContentTokenCount *int `json:"cachedContentTokenCount"`
}
type rawResponse struct {
Candidates []rawCandidate `json:"candidates,omitempty"`
PromptFeedback *struct {
BlockReason string `json:"blockReason,omitempty"`
} `json:"promptFeedback,omitempty"`
UsageMetadata *rawUsage `json:"usageMetadata,omitempty"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
Status string `json:"status"`
} `json:"error,omitempty"`
}
func (c *Client) usage(u rawUsage) types.TokenUsage {
out := types.TokenUsage{
PromptTokens: u.PromptTokenCount,
CompletionTokens: u.CandidatesTokenCount + u.ThoughtsTokenCount,
TotalTokens: u.TotalTokenCount,
}
if out.TotalTokens == 0 {
out.TotalTokens = out.PromptTokens + out.CompletionTokens
}
switch {
case u.CachedContentTokenCount != nil:
cached := *u.CachedContentTokenCount
out.SetPromptCacheUsage(cached, 0, max(0, u.PromptTokenCount-cached), true)
case c.cfg.Settings.PromptCacheAcct:
out.SetPromptCacheUsage(0, 0, 0, false)
default:
out.MarkPromptCacheUnsupported()
}
return out
}
// toolCall lifts a functionCall part into the neutral tool call, minting an
// id when the vendor sent none and keeping the thought signature as
// provider metadata so it can be replayed verbatim.
func (c *Client) toolCall(p rawPart) types.LLMToolCall {
fc := p.FunctionCall
id := fc.ID
if id == "" {
id = newCallID()
}
args := "{}"
if len(fc.Args) > 0 && string(fc.Args) != "null" {
args = string(fc.Args)
}
call := types.LLMToolCall{
ID: id,
Type: "function",
Function: types.FunctionCall{Name: fc.Name, Arguments: args},
}
if p.ThoughtSignature != "" {
sig, _ := json.Marshal(p.ThoughtSignature)
call.ProviderMetadata = types.ToolCallMetadata{metadataThoughtSignature: sig}
}
return call
}
func newCallID() string {
var b [6]byte
if _, err := rand.Read(b[:]); err != nil {
return "call_000000000000"
}
return "call_" + hex.EncodeToString(b[:])
}
// mapFinishReason maps Gemini finish reasons onto the OpenAI vocabulary the
// rest of the system understands.
func mapFinishReason(reason string, hasToolCalls bool) string {
switch reason {
case "":
return ""
case "STOP":
if hasToolCalls {
return "tool_calls"
}
return "stop"
case "MAX_TOKENS":
return "length"
case "SAFETY", "RECITATION", "LANGUAGE", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII",
"IMAGE_SAFETY", "IMAGE_PROHIBITED_CONTENT", "IMAGE_RECITATION":
return "content_filter"
default:
return strings.ToLower(reason)
}
}
func (c *Client) parseResponse(raw []byte) (*types.ChatResponse, error) {
var env rawResponse
if err := json.Unmarshal(raw, &env); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
if env.Error != nil && env.Error.Message != "" {
return nil, fmt.Errorf("API error: %s", env.Error.Message)
}
if len(env.Candidates) == 0 {
if env.PromptFeedback != nil && env.PromptFeedback.BlockReason != "" {
return nil, fmt.Errorf("blocked: %s", env.PromptFeedback.BlockReason)
}
return nil, fmt.Errorf("no response from API")
}
cand := env.Candidates[0]
result := &types.ChatResponse{}
var content, reasoning strings.Builder
for _, p := range cand.Content.Parts {
if p.ThoughtSignature != "" {
result.ReasoningSignature = api.TagSignature(api.APIGoogleGenerativeAI, p.ThoughtSignature)
}
switch {
case p.FunctionCall != nil:
result.ToolCalls = append(result.ToolCalls, c.toolCall(p))
case p.Thought:
reasoning.WriteString(p.Text)
default:
content.WriteString(p.Text)
}
}
result.Content = content.String()
result.ReasoningContent = reasoning.String()
result.FinishReason = mapFinishReason(cand.FinishReason, len(result.ToolCalls) > 0)
// Classify the cache status even without usageMetadata: an empty
// CacheStatus is indistinguishable from a miss downstream.
usage := rawUsage{}
if env.UsageMetadata != nil {
usage = *env.UsageMetadata
}
result.Usage = c.usage(usage)
return result, nil
}
// processStream decodes the alt=sse stream: every data line carries a full
// GenerateContentResponse chunk. Function calls arrive complete in one part;
// they are fed to the assembler as a name delta followed by an arguments
// delta so the early ResponseTypeToolCall notification fires as it does for
// the fragment-based protocols.
func (c *Client) processStream(
ctx context.Context, body io.Reader, ch chan<- types.StreamResponse, dumper *api.StreamPacketDumper,
) {
assembler := api.NewStreamAssembler(ctx, c.cfg.Endpoint.Model)
reader := api.NewSSEReader(body)
toolIndex := 0
for {
// The consumer went away (client disconnect, aborted agent turn): stop
// decoding a stream nobody will read instead of spinning to EOF.
if assembler.Aborted() {
return
}
event, err := reader.ReadEvent()
if err != nil {
if err == io.EOF {
assembler.EndAtEOF(ch)
} else {
assembler.Fail(ch, err)
}
return
}
if event == nil {
continue
}
if event.Done {
assembler.End(ch)
return
}
if len(event.Data) == 0 {
continue
}
if dumper != nil {
raw := make([]byte, len(event.Data))
copy(raw, event.Data)
dumper.WritePacketRaw(raw)
}
var env rawResponse
if err := json.Unmarshal(event.Data, &env); err != nil {
assembler.Fail(ch, fmt.Errorf("decode stream chunk: %w", err))
return
}
if env.Error != nil && env.Error.Message != "" {
assembler.Fail(ch, fmt.Errorf("API stream error: %s", env.Error.Message))
return
}
if env.UsageMetadata != nil {
assembler.SetUsage(c.usage(*env.UsageMetadata))
}
if len(env.Candidates) == 0 {
if env.PromptFeedback != nil && env.PromptFeedback.BlockReason != "" {
assembler.Fail(ch, fmt.Errorf("blocked: %s", env.PromptFeedback.BlockReason))
return
}
continue
}
cand := env.Candidates[0]
var delta api.Delta
var calls []rawPart
for _, p := range cand.Content.Parts {
if p.ThoughtSignature != "" {
assembler.ReasoningSignature = api.TagSignature(api.APIGoogleGenerativeAI, p.ThoughtSignature)
}
switch {
case p.FunctionCall != nil:
calls = append(calls, p)
case p.Thought:
delta.Reasoning += p.Text
default:
delta.Content += p.Text
}
}
if delta.Reasoning != "" || delta.Content != "" {
assembler.Process(ch, delta)
}
for _, p := range calls {
call := c.toolCall(p)
idx := toolIndex
toolIndex++
assembler.Process(ch, api.Delta{ToolCalls: []api.ToolCallDelta{{
Index: idx, ID: call.ID, Type: call.Type, Name: call.Function.Name,
}}})
if len(call.ProviderMetadata) > 0 {
assembler.SetToolCallMetadata(idx, call.ProviderMetadata)
}
assembler.Process(ch, api.Delta{ToolCalls: []api.ToolCallDelta{{
Index: idx, Arguments: call.Function.Arguments,
}}})
}
if cand.FinishReason != "" {
assembler.Process(ch, api.Delta{FinishReason: mapFinishReason(cand.FinishReason, toolIndex > 0)})
}
}
}
@@ -0,0 +1,762 @@
package googlegenai
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"academy/internal/models/api"
"academy/internal/types"
)
func newTestClient(t *testing.T, baseURL string, mutate func(*Config)) *Client {
t.Helper()
cfg := Config{
Endpoint: api.Endpoint{
BaseURL: baseURL,
Model: "gemini-2.5-pro",
ModelID: "model-123",
Auth: api.HeaderAuth("x-goog-api-key", "test-key"),
},
Settings: api.DefaultGoogleGenerativeAI(),
Reasoning: true,
}
if mutate != nil {
mutate(&cfg)
}
return New(cfg)
}
// normalize round-trips a body through JSON so typed slices and ints compare
// equal to a parsed expectation.
func normalize(t *testing.T, v any) any {
t.Helper()
data, err := json.Marshal(v)
if err != nil {
t.Fatalf("marshal: %v", err)
}
var out any
if err := json.Unmarshal(data, &out); err != nil {
t.Fatalf("unmarshal: %v", err)
}
return out
}
func parseJSON(t *testing.T, s string) any {
t.Helper()
var out any
if err := json.Unmarshal([]byte(s), &out); err != nil {
t.Fatalf("parse expected json: %v", err)
}
return out
}
func goldenMessages() []api.Message {
return []api.Message{
{Role: "system", Content: "You are helpful."},
{Role: "user", MultiContent: []api.MessageContentPart{
{Type: "image_url", ImageURL: &api.ImageURL{URL: "data:image/png;base64,AAAA"}},
{Type: "text", Text: "What is this?"},
}},
{Role: "assistant", ReasoningContent: "never replayed", ToolCalls: []api.ToolCall{
{
ID: "call_1",
Type: "function",
Function: api.FunctionCall{
Name: "get_weather",
Arguments: `{"city":"Paris"}`,
},
ProviderMetadata: types.ToolCallMetadata{"thought_signature": json.RawMessage(`"sig-1"`)},
},
{ID: "call_2", Type: "function", Function: api.FunctionCall{Name: "get_time", Arguments: ""}},
}},
{Role: "tool", ToolCallID: "call_1", Content: `{"temp": 20}`},
{Role: "tool", ToolCallID: "call_2", Name: "get_time", Content: "noon"},
}
}
func goldenOptions() *api.Options {
return &api.Options{
Temperature: 0.7,
MaxTokens: 1024,
ReasoningEffort: api.ReasoningHigh,
ToolChoice: "auto",
Tools: []api.Tool{
{Type: "function", Function: api.FunctionDef{
Name: "get_weather",
Description: "Weather",
Parameters: json.RawMessage(`{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"title": "Weather",
"additionalProperties": false,
"properties": {
"city": {"type": "string", "default": "Paris", "examples": ["Paris"]},
"title": {"type": "string", "description": "a property named title"}
},
"required": ["city"]
}`),
}},
{Type: "function", Function: api.FunctionDef{Name: "get_time", Description: "Time"}},
},
}
}
const goldenBase = `{
"systemInstruction": {"parts": [{"text": "You are helpful."}]},
"contents": [
{"role": "user", "parts": [
{"inlineData": {"mimeType": "image/png", "data": "AAAA"}},
{"text": "What is this?"}
]},
{"role": "model", "parts": [
{"functionCall": {"id": "call_1", "name": "get_weather", "args": {"city": "Paris"}}, "thoughtSignature": "sig-1"},
{"functionCall": {"id": "call_2", "name": "get_time", "args": {}}}
]},
{"role": "user", "parts": [
{"functionResponse": {"id": "call_1", "name": "get_weather", "response": {"result": {"temp": 20}}}},
{"functionResponse": {"id": "call_2", "name": "get_time", "response": {"result": "noon"}}}
]}
],
"tools": [{"functionDeclarations": [
{"name": "get_weather", "description": "Weather", "parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"title": {"type": "string", "description": "a property named title"}
},
"required": ["city"]
}},
{"name": "get_time", "description": "Time"}
]}],
"toolConfig": {"functionCallingConfig": {"mode": "AUTO"}},
"generationConfig": {
"temperature": 0.7,
"maxOutputTokens": 1024,
"thinkingConfig": THINKING
}
}`
// TestThinkingConfigOmittedForNonReasoningModels guards models the catalog
// does not mark as reasoning (gemini-2.0-flash, Gemma): they may reject any
// thinkingConfig, including the thinkingBudget 0 an agent's default "off" maps to.
func TestThinkingConfigOmittedForNonReasoningModels(t *testing.T) {
client := newTestClient(t, "https://generativelanguage.googleapis.com",
func(c *Config) { c.Reasoning = false })
off := false
body, err := client.BuildRequestBody(
[]api.Message{{Role: "user", Content: "hi"}}, &api.Options{Thinking: &off}, false)
if err != nil {
t.Fatal(err)
}
if gc, ok := body["generationConfig"].(map[string]any); ok {
if _, has := gc["thinkingConfig"]; has {
t.Fatalf("thinkingConfig sent for a non-reasoning model: %v", gc)
}
}
}
// TestForeignSignatureNotReplayed guards cross-provider replay: a signature
// issued by another protocol must never reach Gemini as thoughtSignature.
func TestForeignSignatureNotReplayed(t *testing.T) {
client := newTestClient(t, "https://generativelanguage.googleapis.com", nil)
body, err := client.BuildRequestBody([]api.Message{
{Role: "user", Content: "hi"},
{
Role: "assistant", Content: "ok",
ReasoningSignature: api.TagSignature(api.APIAnthropicMessages, "claude-sig"),
},
{Role: "user", Content: "again"},
}, nil, false)
if err != nil {
t.Fatal(err)
}
data, _ := json.Marshal(body)
if strings.Contains(string(data), "claude-sig") {
t.Fatalf("foreign signature replayed: %s", data)
}
}
func TestBuildRequestBodyGolden(t *testing.T) {
cases := []struct {
name string
mutate func(*Config)
thinking string
}{
{
name: "budget mode",
thinking: `{"thinkingBudget": 24576, "includeThoughts": true}`,
},
{
name: "level mode",
mutate: func(c *Config) {
c.Settings.ThinkingMode = api.GoogleThinkingLevel
c.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningHigh: api.StringPtr("high")}
},
thinking: `{"thinkingLevel": "high", "includeThoughts": true}`,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
client := newTestClient(t, "https://generativelanguage.googleapis.com", tc.mutate)
body, err := client.BuildRequestBody(goldenMessages(), goldenOptions(), false)
if err != nil {
t.Fatalf("BuildRequestBody: %v", err)
}
expected := parseJSON(t, replaceThinking(goldenBase, tc.thinking))
got := normalize(t, body)
if !reflect.DeepEqual(got, expected) {
gotJSON, _ := json.MarshalIndent(got, "", " ")
wantJSON, _ := json.MarshalIndent(expected, "", " ")
t.Fatalf("body mismatch\n got: %s\nwant: %s", gotJSON, wantJSON)
}
})
}
}
func replaceThinking(tmpl, thinking string) string {
return strings.Replace(tmpl, "THINKING", thinking, 1)
}
func TestThinkingConfigVariants(t *testing.T) {
cases := []struct {
name string
mutate func(*Config)
opts *api.Options
want string // "" means no thinkingConfig
}{
{name: "not requested", opts: &api.Options{}, want: ""},
{
name: "budget off supported", opts: &api.Options{ReasoningEffort: api.ReasoningOff},
want: `{"thinkingBudget": 0}`,
},
{
name: "budget off unsupported",
mutate: func(c *Config) { c.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningOff: nil} },
opts: &api.Options{ReasoningEffort: api.ReasoningOff},
want: "",
},
{
name: "budget auto", opts: &api.Options{ReasoningEffort: api.ReasoningAuto},
want: `{"thinkingBudget": -1, "includeThoughts": true}`,
},
{
name: "budget explicit tokens",
opts: &api.Options{ReasoningEffort: api.ReasoningLow, ThinkingBudgetTokens: 512},
want: `{"thinkingBudget": 512, "includeThoughts": true}`,
},
{
name: "mode none",
mutate: func(c *Config) { c.Settings.ThinkingMode = api.GoogleThinkingNone },
opts: &api.Options{ReasoningEffort: api.ReasoningHigh},
want: "",
},
{
name: "level off unmapped",
mutate: func(c *Config) { c.Settings.ThinkingMode = api.GoogleThinkingLevel },
opts: &api.Options{ReasoningEffort: api.ReasoningOff},
want: "",
},
{
name: "level auto",
mutate: func(c *Config) { c.Settings.ThinkingMode = api.GoogleThinkingLevel },
opts: &api.Options{ReasoningEffort: api.ReasoningAuto},
want: `{"includeThoughts": true}`,
},
{
name: "level clamps unsupported rung",
mutate: func(c *Config) {
c.Settings.ThinkingMode = api.GoogleThinkingLevel
c.ThinkingLevels = api.ThinkingLevelMap{
api.ReasoningMedium: nil,
api.ReasoningHigh: api.StringPtr("high"),
}
},
opts: &api.Options{ReasoningEffort: api.ReasoningMedium},
want: `{"thinkingLevel": "high", "includeThoughts": true}`,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
client := newTestClient(t, "https://generativelanguage.googleapis.com", tc.mutate)
body, err := client.BuildRequestBody([]api.Message{{Role: "user", Content: "hi"}}, tc.opts, false)
if err != nil {
t.Fatal(err)
}
var got any
if gen, ok := body["generationConfig"].(map[string]any); ok {
if tcfg, ok := gen["thinkingConfig"]; ok {
got = normalize(t, tcfg)
}
}
var want any
if tc.want != "" {
want = parseJSON(t, tc.want)
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("thinkingConfig = %v, want %v", got, want)
}
})
}
}
func TestToolChoiceAndFormat(t *testing.T) {
client := newTestClient(t, "https://generativelanguage.googleapis.com", nil)
opts := &api.Options{
ToolChoice: "get_weather",
Tools: []api.Tool{{Function: api.FunctionDef{Name: "get_weather"}}},
Format: json.RawMessage(`{"type":"object"}`),
}
body, err := client.BuildRequestBody([]api.Message{{Role: "user", Content: "hi"}}, opts, false)
if err != nil {
t.Fatal(err)
}
got := normalize(t, body["toolConfig"])
want := parseJSON(t, `{"functionCallingConfig": {"mode": "ANY", "allowedFunctionNames": ["get_weather"]}}`)
if !reflect.DeepEqual(got, want) {
t.Fatalf("toolConfig = %v, want %v", got, want)
}
gen := body["generationConfig"].(map[string]any)
if gen["responseMimeType"] != "application/json" {
t.Fatalf("responseMimeType = %v", gen["responseMimeType"])
}
contents := body["contents"].([]map[string]any)
text := contents[0]["parts"].([]part)[0]["text"].(string)
if text != "hi\nUse this JSON schema: {\"type\":\"object\"}" {
t.Fatalf("schema hint not appended: %q", text)
}
}
func TestRequestURL(t *testing.T) {
cases := []struct {
name string
base string
stream bool
want string
}{
{
"bare host non-stream", "https://generativelanguage.googleapis.com", false,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent",
},
{
"bare host trailing slash stream", "https://generativelanguage.googleapis.com/", true,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse",
},
{
"versioned base non-stream", "https://proxy.example.com/gemini/v1beta", false,
"https://proxy.example.com/gemini/v1beta/models/gemini-2.5-pro:generateContent",
},
{
"versioned base stream", "https://proxy.example.com/v1beta/", true,
"https://proxy.example.com/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
client := newTestClient(t, tc.base, nil)
if got := client.requestURL(tc.stream); got != tc.want {
t.Fatalf("requestURL = %q, want %q", got, tc.want)
}
})
}
t.Run("explicit URL override", func(t *testing.T) {
client := newTestClient(t, "https://ignored.example.com", func(c *Config) {
c.Endpoint.URL = "https://custom.example.com/route:generateContent"
})
if got := client.requestURL(false); got != "https://custom.example.com/route:generateContent" {
t.Fatalf("requestURL = %q", got)
}
// A streaming call must name the streaming method: ":generateContent"
// answers with one buffered JSON document even with alt=sse, which the
// SSE reader would see as an empty stream.
want := "https://custom.example.com/route:streamGenerateContent?alt=sse"
if got := client.requestURL(true); got != want {
t.Fatalf("requestURL = %q, want %q", got, want)
}
})
t.Run("explicit URL override without a known method is left alone", func(t *testing.T) {
client := newTestClient(t, "https://ignored.example.com", func(c *Config) {
c.Endpoint.URL = "https://custom.example.com/route"
})
if got := client.requestURL(true); got != "https://custom.example.com/route?alt=sse" {
t.Fatalf("requestURL = %q", got)
}
})
}
func TestChatDecodesResponse(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var gotPath, gotQuery, gotKey string
var gotBody map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
gotQuery = r.URL.RawQuery
gotKey = r.Header.Get("x-goog-api-key")
raw, _ := io.ReadAll(r.Body)
_ = json.Unmarshal(raw, &gotBody)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{
"candidates": [{
"content": {"role": "model", "parts": [
{"text": "Thinking about Paris.", "thought": true, "thoughtSignature": "sig-thought"},
{"text": "Let me check."},
{"functionCall": {"id": "fc-1", "name": "get_weather", "args": {"city": "Paris"}},
"thoughtSignature": "sig-fc"}
]},
"finishReason": "STOP"
}],
"usageMetadata": {"promptTokenCount": 10, "candidatesTokenCount": 5, "thoughtsTokenCount": 3,
"totalTokenCount": 18, "cachedContentTokenCount": 4}
}`))
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
resp, err := client.Chat(context.Background(), []api.Message{{Role: "user", Content: "weather?"}}, &api.Options{})
if err != nil {
t.Fatalf("Chat: %v", err)
}
if gotPath != "/v1beta/models/gemini-2.5-pro:generateContent" || gotQuery != "" {
t.Fatalf("request path = %q query = %q", gotPath, gotQuery)
}
if gotKey != "test-key" {
t.Fatalf("x-goog-api-key = %q", gotKey)
}
if _, ok := gotBody["contents"]; !ok {
t.Fatalf("request body missing contents: %v", gotBody)
}
if resp.Content != "Let me check." {
t.Fatalf("Content = %q", resp.Content)
}
if resp.ReasoningContent != "Thinking about Paris." {
t.Fatalf("ReasoningContent = %q", resp.ReasoningContent)
}
if resp.ReasoningSignature != "google-generative-ai:sig-fc" {
t.Fatalf("ReasoningSignature = %q", resp.ReasoningSignature)
}
if resp.FinishReason != "tool_calls" {
t.Fatalf("FinishReason = %q", resp.FinishReason)
}
if len(resp.ToolCalls) != 1 {
t.Fatalf("ToolCalls = %+v", resp.ToolCalls)
}
tc := resp.ToolCalls[0]
if tc.ID != "fc-1" || tc.Type != "function" || tc.Function.Name != "get_weather" ||
tc.Function.Arguments != `{"city": "Paris"}` {
t.Fatalf("tool call = %+v", tc)
}
if string(tc.ProviderMetadata["thought_signature"]) != `"sig-fc"` {
t.Fatalf("thought_signature = %s", tc.ProviderMetadata["thought_signature"])
}
u := resp.Usage
if u.PromptTokens != 10 || u.CompletionTokens != 8 || u.TotalTokens != 18 {
t.Fatalf("usage = %+v", u)
}
if u.CacheReadTokens != 4 || u.CacheMissTokens != 6 || !u.CacheReported ||
u.CacheStatus != types.PromptCacheStatusHit {
t.Fatalf("cache usage = %+v", u)
}
}
func TestChatErrors(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
cases := []struct {
name string
body string
want string
}{
{
"error payload", `{"error": {"code": 400, "message": "bad request", "status": "INVALID_ARGUMENT"}}`,
"API error: bad request",
},
{"blocked prompt", `{"promptFeedback": {"blockReason": "SAFETY"}}`, "blocked: SAFETY"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(tc.body))
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
_, err := client.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err == nil || err.Error() != tc.want {
t.Fatalf("err = %v, want %q", err, tc.want)
}
})
}
}
func TestChatStreamDecodesSSE(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var gotPath, gotQuery string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
gotQuery = r.URL.RawQuery
w.Header().Set("Content-Type", "text/event-stream")
chunks := []string{
`{"candidates":[{"content":{"role":"model","parts":[{"text":"Let me think.","thought":true}]}}]}`,
`{"candidates":[{"content":{"role":"model","parts":[{"text":"Checking "}]}}]}`,
`{"candidates":[{"content":{"role":"model","parts":[{"text":"weather."}]}}]}`,
`{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"name":"get_weather",` +
`"args":{"city":"Paris"}},"thoughtSignature":"sig-stream"}]},"finishReason":"STOP"}],` +
`"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":5,"thoughtsTokenCount":3,` +
`"totalTokenCount":18}}`,
}
for _, c := range chunks {
_, _ = w.Write([]byte("data: " + c + "\n\n"))
}
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
ch, err := client.ChatStream(context.Background(),
[]api.Message{{Role: "user", Content: "weather?"}}, &api.Options{})
if err != nil {
t.Fatalf("ChatStream: %v", err)
}
var events []types.StreamResponse
for ev := range ch {
events = append(events, ev)
}
if gotPath != "/v1beta/models/gemini-2.5-pro:streamGenerateContent" || gotQuery != "alt=sse" {
t.Fatalf("request path = %q query = %q", gotPath, gotQuery)
}
if len(events) == 0 {
t.Fatal("no events")
}
firstThinking, firstAnswer, toolCallEvent := -1, -1, -1
var thinking, answer string
for i, ev := range events {
switch ev.ResponseType {
case types.ResponseTypeThinking:
if !ev.Done {
if firstThinking < 0 {
firstThinking = i
}
thinking += ev.Content
}
case types.ResponseTypeAnswer:
if ev.Content != "" {
if firstAnswer < 0 {
firstAnswer = i
}
answer += ev.Content
}
case types.ResponseTypeToolCall:
if toolCallEvent < 0 {
toolCallEvent = i
}
if ev.Data["tool_name"] != "get_weather" || ev.Data["tool_call_id"] == "" {
t.Fatalf("tool_call event data = %v", ev.Data)
}
case types.ResponseTypeError:
t.Fatalf("stream error: %s", ev.Content)
}
}
if firstThinking < 0 || firstAnswer < 0 || firstThinking > firstAnswer {
t.Fatalf("thinking (%d) must precede answer (%d)", firstThinking, firstAnswer)
}
if thinking != "Let me think." || answer != "Checking weather." {
t.Fatalf("thinking = %q answer = %q", thinking, answer)
}
if toolCallEvent < 0 {
t.Fatal("no ResponseTypeToolCall event")
}
final := events[len(events)-1]
if final.ResponseType != types.ResponseTypeAnswer || !final.Done {
t.Fatalf("final event = %+v", final)
}
if final.FinishReason != "tool_calls" {
t.Fatalf("final FinishReason = %q", final.FinishReason)
}
if final.Usage == nil || final.Usage.PromptTokens != 10 || final.Usage.CompletionTokens != 8 ||
final.Usage.TotalTokens != 18 {
t.Fatalf("final usage = %+v", final.Usage)
}
if final.Usage.CacheStatus != types.PromptCacheStatusUnreported || final.Usage.CacheReported {
t.Fatalf("cache status = %+v", final.Usage)
}
if len(final.ToolCalls) != 1 {
t.Fatalf("final tool calls = %+v", final.ToolCalls)
}
tc := final.ToolCalls[0]
if tc.Function.Name != "get_weather" || tc.Function.Arguments != `{"city":"Paris"}` || tc.Type != "function" {
t.Fatalf("tool call = %+v", tc)
}
if len(tc.ID) != len("call_")+12 || tc.ID[:5] != "call_" {
t.Fatalf("generated tool call id = %q", tc.ID)
}
if string(tc.ProviderMetadata["thought_signature"]) != `"sig-stream"` {
t.Fatalf("thought_signature = %s", tc.ProviderMetadata["thought_signature"])
}
if final.Data["reasoning_signature"] != "google-generative-ai:sig-stream" {
t.Fatalf("Data = %v", final.Data)
}
}
func TestChatStreamErrorPayload(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("data: {\"error\": {\"code\": 429, \"message\": \"quota exceeded\"}}\n\n"))
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
ch, err := client.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatal(err)
}
var last types.StreamResponse
for ev := range ch {
last = ev
}
if last.ResponseType != types.ResponseTypeError || last.Content != "API stream error: quota exceeded" {
t.Fatalf("last event = %+v", last)
}
}
// "contents" is required and must be an array. A request that produced no
// turns (only system prompts) used to marshal a nil slice as null, which
// generateContent rejects with 400.
func TestBuildRequestBodyContentsNeverNull(t *testing.T) {
client := newTestClient(t, "https://generativelanguage.googleapis.com", nil)
for _, msgs := range [][]api.Message{nil, {{Role: "system", Content: "be brief"}}} {
body, err := client.BuildRequestBody(msgs, nil, false)
if err != nil {
t.Fatalf("BuildRequestBody: %v", err)
}
data, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal: %v", err)
}
if strings.Contains(string(data), `"contents":null`) {
t.Fatalf("contents marshalled as null: %s", data)
}
if !strings.Contains(string(data), `"contents":[]`) {
t.Fatalf("contents not an empty array: %s", data)
}
}
}
// Without usageMetadata the cache status must still be classified, otherwise
// "the vendor reported nothing" is indistinguishable from a real miss on the
// usage dashboards.
func TestChatClassifiesCacheStatusWithoutUsageMetadata(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"candidates":[{"content":{"role":"model","parts":[{"text":"hi"}]},` +
`"finishReason":"STOP"}]}`))
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
resp, err := client.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatalf("Chat: %v", err)
}
if resp.Usage.CacheStatus == "" {
t.Fatal("CacheStatus is empty; the usage block must still be classified")
}
}
// A chunk that blocks the prompt mid-stream must surface as an error rather
// than being skipped as "no candidates".
func TestChatStreamSurfacesPromptFeedbackBlock(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: {\"promptFeedback\":{\"blockReason\":\"SAFETY\"}}\n\n"))
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
ch, err := client.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatalf("ChatStream: %v", err)
}
var sawError bool
for chunk := range ch {
if chunk.ResponseType == types.ResponseTypeError {
sawError = true
if !strings.Contains(chunk.Content, "SAFETY") {
t.Fatalf("error chunk = %q, want the block reason", chunk.Content)
}
}
}
if !sawError {
t.Fatal("blocked prompt did not produce an error chunk")
}
}
// Gemini streams end on EOF; the last candidate of a finished message carries
// a finishReason, so a body that stops without one was cut mid-answer.
func TestChatStreamEOFWithoutFinishReasonIsIncomplete(t *testing.T) {
for _, tc := range []struct {
name, body, want string
}{
{"cut off", `{"candidates":[{"content":{"parts":[{"text":"Hel"}]}}]}`, types.FinishReasonIncomplete},
{"finished", `{"candidates":[{"content":{"parts":[{"text":"Hello"}]},"finishReason":"STOP"}]}`, "stop"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("data: " + tc.body + "\n\n"))
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
ch, err := client.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatal(err)
}
var last types.StreamResponse
for ev := range ch {
last = ev
}
if last.ResponseType != types.ResponseTypeAnswer || !last.Done || last.FinishReason != tc.want {
t.Fatalf("last event = %+v, want finish reason %q", last, tc.want)
}
})
}
}
func TestMapFinishReason(t *testing.T) {
tests := []struct {
reason string
hasToolCalls bool
want string
}{
{"", false, ""},
{"STOP", false, "stop"},
{"STOP", true, "tool_calls"},
{"MAX_TOKENS", false, "length"},
{"SAFETY", false, "content_filter"},
{"RECITATION", false, "content_filter"},
{"LANGUAGE", false, "content_filter"},
{"BLOCKLIST", false, "content_filter"},
{"PROHIBITED_CONTENT", false, "content_filter"},
{"SPII", false, "content_filter"},
{"IMAGE_SAFETY", false, "content_filter"},
{"IMAGE_PROHIBITED_CONTENT", false, "content_filter"},
{"IMAGE_RECITATION", false, "content_filter"},
{"OTHER", false, "other"},
{"MALFORMED_FUNCTION_CALL", false, "malformed_function_call"},
}
for _, tt := range tests {
t.Run(tt.reason, func(t *testing.T) {
if got := mapFinishReason(tt.reason, tt.hasToolCalls); got != tt.want {
t.Fatalf("mapFinishReason(%q, %v) = %q, want %q", tt.reason, tt.hasToolCalls, got, tt.want)
}
})
}
}
+528
View File
@@ -0,0 +1,528 @@
// Package googlegenai implements the native Google Gemini generateContent
// wire protocol (https://ai.google.dev/api/generate-content). Every
// model-specific deviation is driven by api.GoogleGenerativeAISettings;
// this package contains no vendor names beyond the protocol itself.
package googlegenai
import (
"encoding/base64"
"encoding/json"
"fmt"
"mime"
"net/url"
"path"
"strings"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.GoogleGenerativeAISettings
// ThinkingLevels maps neutral levels to the vendor vocabulary
// (thinkingLevel values for Gemini 3, "off" support for budget models).
ThinkingLevels api.ThinkingLevelMap
// Reasoning marks a reasoning model. The Gemini protocol has no
// role selection to gate on it; the field is informational and mirrors
// the other protocol configs.
Reasoning bool
}
const (
roleUser = "user"
roleModel = "model"
// metadataThoughtSignature is the ToolCallMetadata key under which a
// function call's thoughtSignature round-trips. Gemini 3 rejects a
// replayed function call whose signature is missing or altered.
metadataThoughtSignature = "thought_signature"
defaultImageMIME = "image/jpeg"
)
type part = map[string]any
// convertMessages splits neutral messages into the system instruction text
// and the Gemini contents array. Consecutive tool results are merged into one
// user content carrying several functionResponse parts, as Gemini requires
// every functionCall of a model turn to be answered in the next content.
func (c *Client) convertMessages(messages []api.Message) (system []string, contents []map[string]any) {
toolNames := map[string]string{}
openToolBatch := -1 // index in contents of the functionResponse content being filled
for _, msg := range messages {
msg = api.NeutralizeMessageSpecialTokens(msg)
switch msg.Role {
case "system":
if text := systemText(msg); text != "" {
system = append(system, text)
}
case "assistant":
for _, tc := range msg.ToolCalls {
if tc.ID != "" {
toolNames[tc.ID] = tc.Function.Name
}
}
contents = append(contents, map[string]any{"role": roleModel, "parts": assistantParts(msg)})
case "tool":
p := toolResultPart(msg, toolNames)
if openToolBatch >= 0 && openToolBatch == len(contents)-1 {
batch := contents[openToolBatch]
batch["parts"] = append(batch["parts"].([]part), p)
continue
}
contents = append(contents, map[string]any{"role": roleUser, "parts": []part{p}})
openToolBatch = len(contents) - 1
default:
contents = append(contents, map[string]any{"role": roleUser, "parts": userParts(msg)})
}
}
return system, contents
}
func systemText(msg api.Message) string {
if len(msg.MultiContent) == 0 {
return msg.Content
}
var texts []string
for _, p := range msg.MultiContent {
if p.Type == "text" && p.Text != "" {
texts = append(texts, p.Text)
}
}
return strings.Join(texts, "\n")
}
// userParts renders a user turn. Legacy Message.Images are emitted before the
// text part, matching the Chat Completions package.
func userParts(msg api.Message) []part {
var parts []part
switch {
case len(msg.MultiContent) > 0:
for _, p := range msg.MultiContent {
switch p.Type {
case "text":
if p.Text != "" {
parts = append(parts, part{"text": p.Text})
}
case "image_url":
if p.ImageURL != nil {
if ip := imagePart(p.ImageURL.URL); ip != nil {
parts = append(parts, ip)
}
}
}
}
case len(msg.Images) > 0:
for _, img := range msg.Images {
if ip := imagePart(img); ip != nil {
parts = append(parts, ip)
}
}
parts = append(parts, part{"text": msg.Content})
}
if len(parts) == 0 {
parts = append(parts, part{"text": msg.Content})
}
return parts
}
// assistantParts renders a model turn: the answer text (carrying the thought
// signature when the turn had no function calls) followed by one functionCall
// part per tool call, each replaying its own thought signature. Reasoning
// text is never replayed as a thought part: Gemini only needs signatures.
func assistantParts(msg api.Message) []part {
var parts []part
if msg.Content != "" || len(msg.ToolCalls) == 0 {
p := part{"text": msg.Content}
sig := api.SignatureFor(api.APIGoogleGenerativeAI, msg.ReasoningSignature)
if sig != "" && len(msg.ToolCalls) == 0 {
p["thoughtSignature"] = sig
}
parts = append(parts, p)
}
for _, tc := range msg.ToolCalls {
fc := map[string]any{
"name": tc.Function.Name,
"args": parseArgs(tc.Function.Arguments),
}
if tc.ID != "" {
fc["id"] = tc.ID
}
p := part{"functionCall": fc}
if sig := thoughtSignatureFromMetadata(tc.ProviderMetadata); sig != "" {
p["thoughtSignature"] = sig
}
parts = append(parts, p)
}
return parts
}
// toolResultPart renders a tool result as a functionResponse part. The tool
// name comes from the message or, failing that, from the assistant turn that
// issued the call.
func toolResultPart(msg api.Message, toolNames map[string]string) part {
name := msg.Name
if name == "" {
name = toolNames[msg.ToolCallID]
}
fr := map[string]any{
"name": name,
"response": map[string]any{"result": decodeToolResult(msg.Content)},
}
if msg.ToolCallID != "" {
fr["id"] = msg.ToolCallID
}
return part{"functionResponse": fr}
}
// decodeToolResult returns the tool output as a JSON value when it is a JSON
// object or array, otherwise the raw string.
func decodeToolResult(content string) any {
trimmed := strings.TrimSpace(content)
if strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[") {
var v any
if err := json.Unmarshal([]byte(trimmed), &v); err == nil {
return v
}
}
return content
}
// parseArgs decodes a tool call's JSON arguments into the object Gemini
// expects; anything that is not a JSON object becomes an empty object.
func parseArgs(arguments string) map[string]any {
args := map[string]any{}
if strings.TrimSpace(arguments) == "" {
return args
}
if err := json.Unmarshal([]byte(arguments), &args); err != nil || args == nil {
return map[string]any{}
}
return args
}
func thoughtSignatureFromMetadata(md map[string]json.RawMessage) string {
raw, ok := md[metadataThoughtSignature]
if !ok || len(raw) == 0 {
return ""
}
var sig string
if err := json.Unmarshal(raw, &sig); err != nil {
return ""
}
return sig
}
// imagePart renders an image reference. Stored images are resolved to data
// URIs first; data URIs become inlineData, everything else is passed as
// fileData with a MIME type guessed from the extension.
func imagePart(ref string) part {
resolved := api.ResolveImageURLForLLM(ref)
if strings.HasPrefix(resolved, "data:") {
mimeType, data, ok := parseDataURI(resolved)
if !ok {
return nil
}
return part{"inlineData": map[string]any{"mimeType": mimeType, "data": data}}
}
return part{"fileData": map[string]any{"mimeType": guessImageMIME(resolved), "fileUri": resolved}}
}
// parseDataURI splits "data:<mime>[;base64],<payload>" into the MIME type and
// the base64 payload Gemini wants. Non-base64 payloads are re-encoded.
func parseDataURI(uri string) (mimeType, data string, ok bool) {
comma := strings.Index(uri, ",")
if comma < 0 {
return "", "", false
}
header := uri[len("data:"):comma]
payload := uri[comma+1:]
isBase64 := false
if strings.HasSuffix(header, ";base64") {
header = strings.TrimSuffix(header, ";base64")
isBase64 = true
}
mimeType = header
if idx := strings.Index(mimeType, ";"); idx >= 0 {
mimeType = mimeType[:idx]
}
if mimeType == "" {
mimeType = defaultImageMIME
}
if isBase64 {
return mimeType, payload, true
}
decoded, err := url.PathUnescape(payload)
if err != nil {
decoded = payload
}
return mimeType, base64.StdEncoding.EncodeToString([]byte(decoded)), true
}
func guessImageMIME(ref string) string {
ext := path.Ext(ref)
if u, err := url.Parse(ref); err == nil && u.Path != "" {
ext = path.Ext(u.Path)
}
if ext != "" {
if mt := mime.TypeByExtension(strings.ToLower(ext)); strings.HasPrefix(mt, "image/") {
return mt
}
}
return defaultImageMIME
}
// buildBody assembles the generateContent request body. The body is the
// same for streaming and non-streaming calls; streaming is selected by the
// URL. It returns nested maps so golden tests can inspect it.
func (c *Client) buildBody(messages []api.Message, opts *api.Options) (map[string]any, error) {
s := c.cfg.Settings
system, contents := c.convertMessages(messages)
if contents == nil {
// "contents" is required and must be an array: a nil slice marshals to
// null and generateContent answers 400. A request carrying only system
// messages legitimately produces no turns.
contents = []map[string]any{}
}
// Gemini has no in-sequence instruction role; the envelope identifies
// this trailing input as runtime context, rather than new user intent.
if opts != nil && opts.RuntimeNotice != "" {
contents = append(contents, map[string]any{"role": roleUser, "parts": []part{{"text": opts.RuntimeNotice}}})
}
body := map[string]any{"contents": contents}
if len(system) > 0 {
body["systemInstruction"] = map[string]any{
"parts": []part{{"text": strings.Join(system, "\n\n")}},
}
}
gen := map[string]any{}
if opts != nil {
c.applySampling(gen, opts)
if budget := opts.CompletionBudget(); budget > 0 {
gen["maxOutputTokens"] = budget
}
c.applyTools(body, opts)
if len(opts.Format) > 0 {
gen["responseMimeType"] = "application/json"
appendSchemaHint(contents, opts.Format)
}
if tc := c.thinkingConfig(opts); tc != nil {
gen["thinkingConfig"] = tc
}
}
for k, v := range s.ExtraGeneration {
if _, exists := gen[k]; !exists {
gen[k] = v
}
}
if len(gen) > 0 {
body["generationConfig"] = gen
}
return body, nil
}
func (c *Client) applySampling(gen map[string]any, opts *api.Options) {
s := c.cfg.Settings
if opts.Temperature > 0 {
gen["temperature"] = opts.Temperature
}
if opts.TopP > 0 {
gen["topP"] = opts.TopP
}
if opts.Seed > 0 && s.SupportsSeed {
gen["seed"] = opts.Seed
}
if s.SupportsPenalty {
if opts.FrequencyPenalty > 0 {
gen["frequencyPenalty"] = opts.FrequencyPenalty
}
if opts.PresencePenalty > 0 {
gen["presencePenalty"] = opts.PresencePenalty
}
}
}
func (c *Client) applyTools(body map[string]any, opts *api.Options) {
if len(opts.Tools) == 0 {
return
}
decls := make([]map[string]any, 0, len(opts.Tools))
for _, tool := range opts.Tools {
decl := map[string]any{
"name": tool.Function.Name,
"description": tool.Function.Description,
}
if schema := sanitizeParameters(tool.Function.Parameters); schema != nil {
decl["parameters"] = schema
}
decls = append(decls, decl)
}
body["tools"] = []map[string]any{{"functionDeclarations": decls}}
if opts.ToolChoice == "" {
return
}
cfg := map[string]any{}
switch opts.ToolChoice {
case "auto":
cfg["mode"] = "AUTO"
case "required":
cfg["mode"] = "ANY"
case "none":
cfg["mode"] = "NONE"
default:
cfg["mode"] = "ANY"
cfg["allowedFunctionNames"] = []string{opts.ToolChoice}
}
body["toolConfig"] = map[string]any{"functionCallingConfig": cfg}
}
// unsupportedSchemaKeys are JSON Schema members the Gemini Schema type
// rejects. They are stripped recursively; property names are never touched.
var unsupportedSchemaKeys = map[string]bool{
"$schema": true,
"$id": true,
"$ref": true,
"$defs": true,
"definitions": true,
"additionalProperties": true,
"default": true,
"examples": true,
"title": true,
}
// sanitizeParameters decodes a tool's JSON schema and strips the members
// Gemini does not accept. Empty or undecodable schemas yield nil.
func sanitizeParameters(raw json.RawMessage) any {
if len(raw) == 0 || string(raw) == "null" {
return nil
}
var schema any
if err := json.Unmarshal(raw, &schema); err != nil {
return nil
}
if _, ok := schema.(map[string]any); !ok {
return nil
}
return sanitizeSchema(schema)
}
func sanitizeSchema(v any) any {
switch t := v.(type) {
case map[string]any:
out := make(map[string]any, len(t))
for k, val := range t {
if unsupportedSchemaKeys[k] {
continue
}
if k == "properties" {
if props, ok := val.(map[string]any); ok {
cleaned := make(map[string]any, len(props))
for name, sub := range props {
cleaned[name] = sanitizeSchema(sub)
}
out[k] = cleaned
continue
}
}
out[k] = sanitizeSchema(val)
}
return out
case []any:
for i := range t {
t[i] = sanitizeSchema(t[i])
}
return t
}
return v
}
// appendSchemaHint appends the JSON schema instruction to the last user text
// part, mirroring the Chat Completions package.
func appendSchemaHint(contents []map[string]any, format json.RawMessage) {
hint := fmt.Sprintf("\nUse this JSON schema: %s", format)
for i := len(contents) - 1; i >= 0; i-- {
if contents[i]["role"] != roleUser {
continue
}
parts, _ := contents[i]["parts"].([]part)
for j := len(parts) - 1; j >= 0; j-- {
if text, ok := parts[j]["text"].(string); ok {
parts[j]["text"] = text + hint
return
}
}
contents[i]["parts"] = append(parts, part{"text": strings.TrimPrefix(hint, "\n")})
return
}
}
// thinkingConfig encodes the requested reasoning level in the shape the
// model generation supports: thinkingBudget (Gemini 2.5) or thinkingLevel
// (Gemini 3). nil means "send no thinkingConfig".
func (c *Client) thinkingConfig(opts *api.Options) map[string]any {
s := c.cfg.Settings
levels := c.cfg.ThinkingLevels
level, requested := opts.Reasoning()
// Models the catalog does not mark as reasoning (gemini-2.0-flash, Gemma,
// unknown ids) may reject thinkingConfig outright, so send none.
if !requested || !c.cfg.Reasoning {
return nil
}
mode := s.ThinkingMode
if mode == "" {
mode = api.GoogleThinkingBudget
}
switch mode {
case api.GoogleThinkingBudget:
switch level {
case api.ReasoningOff:
if levels.Supports(api.ReasoningOff) {
return map[string]any{"thinkingBudget": 0}
}
return nil
case api.ReasoningAuto:
return map[string]any{"thinkingBudget": -1, "includeThoughts": s.IncludeThoughts}
default:
level = levels.Clamp(level)
budget := opts.ThinkingBudgetTokens
if budget <= 0 {
if b, ok := s.ThinkingBudgets[level]; ok && level.Graded() {
budget = b
} else {
budget = -1
}
}
return map[string]any{"thinkingBudget": budget, "includeThoughts": s.IncludeThoughts}
}
case api.GoogleThinkingLevel:
switch level {
case api.ReasoningOff:
// Gemini 3 cannot switch thinking off; only send a level when the
// vendor explicitly mapped "off" to a wire value.
if v, ok := levels[api.ReasoningOff]; ok && v != nil && *v != "" {
return map[string]any{"thinkingLevel": *v}
}
return nil
case api.ReasoningAuto:
return map[string]any{"includeThoughts": s.IncludeThoughts}
default:
level = levels.Clamp(level)
if !level.Graded() {
return map[string]any{"includeThoughts": s.IncludeThoughts}
}
return map[string]any{"thinkingLevel": levels.Value(level), "includeThoughts": s.IncludeThoughts}
}
}
return nil
}
// BuildRequestBody is the golden-test entry point: it returns the exact
// JSON object that would be sent for the given inputs. The stream flag is
// accepted for interface parity; Gemini selects streaming through the URL.
func (c *Client) BuildRequestBody(messages []api.Message, opts *api.Options, stream bool) (map[string]any, error) {
_ = stream
return c.buildBody(messages, opts)
}