Adding one bespoke provider package per vendor doesn't scale. LiteLLM proxy and OpenRouter both speak the OpenAI chat-completions wire format and each front dozens-to-hundreds of underlying models, so supporting them once gets that whole catalog instead of one more one-off integration — providers/qwen turns out to have been exactly that pattern hand-rolled a second time (its own copy of the OpenAI-compatible translation, just pointed at DashScope's base URL). providers/litellm and providers/openrouter are both thin constructors over the OpenAI provider's existing NewOpenAIProviderWithKind(apiKey, baseURL, "openai-compatible") — no new request/stream-translation code. OpenRouter defaults to its public endpoint when baseURL is empty; LiteLLM has none (self-hosted), so callers must supply one. Context-window detection (tokens.ContextWindow) already keys off the model ID's family rather than the provider prefix, specifically so a model exposed under a custom/proxy provider name still gets the right window — so litellm/openrouter models need zero changes there.
352 lines
10 KiB
Go
352 lines
10 KiB
Go
package gemini
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/binary"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"google.golang.org/genai"
|
|
"github.com/sausheong/harness/llm"
|
|
)
|
|
|
|
// GeminiProvider implements llm.LLMProvider using the Google Gemini API.
|
|
type GeminiProvider struct {
|
|
client *genai.Client
|
|
}
|
|
|
|
// NewGeminiProvider creates a new Gemini LLM provider.
|
|
func NewGeminiProvider(ctx context.Context, apiKey string) (*GeminiProvider, error) {
|
|
client, err := genai.NewClient(ctx, &genai.ClientConfig{
|
|
APIKey: apiKey,
|
|
Backend: genai.BackendGeminiAPI,
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create gemini client: %w", err)
|
|
}
|
|
return &GeminiProvider{client: client}, nil
|
|
}
|
|
|
|
func (p *GeminiProvider) Models() []llm.ModelInfo {
|
|
return []llm.ModelInfo{
|
|
{ID: "gemini-2.5-flash", Name: "Gemini 2.5 Flash", Provider: "gemini"},
|
|
{ID: "gemini-2.5-pro", Name: "Gemini 2.5 Pro", Provider: "gemini"},
|
|
{ID: "gemini-2.0-flash", Name: "Gemini 2.0 Flash", Provider: "gemini"},
|
|
}
|
|
}
|
|
|
|
func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
|
// Build a map from tool call ID to function name for resolving tool results.
|
|
toolIDToName := make(map[string]string)
|
|
for _, m := range req.Messages {
|
|
for _, tc := range m.ToolCalls {
|
|
toolIDToName[tc.ID] = tc.Name
|
|
}
|
|
}
|
|
|
|
// Build contents
|
|
var contents []*genai.Content
|
|
for _, m := range req.Messages {
|
|
switch m.Role {
|
|
case "user":
|
|
if m.ToolCallID != "" {
|
|
// Tool result — send as function response
|
|
funcName := m.ToolCallID
|
|
if name, ok := toolIDToName[m.ToolCallID]; ok {
|
|
funcName = name
|
|
}
|
|
var response map[string]any
|
|
if m.IsError {
|
|
response = map[string]any{"error": m.Content}
|
|
} else {
|
|
response = map[string]any{"output": m.Content}
|
|
}
|
|
contents = append(contents, &genai.Content{
|
|
Role: "user",
|
|
Parts: []*genai.Part{
|
|
{FunctionResponse: &genai.FunctionResponse{
|
|
Name: funcName,
|
|
ID: m.ToolCallID,
|
|
Response: response,
|
|
}},
|
|
},
|
|
})
|
|
} else {
|
|
var parts []*genai.Part
|
|
for _, img := range m.Images {
|
|
parts = append(parts, &genai.Part{
|
|
InlineData: &genai.Blob{
|
|
Data: img.Data,
|
|
MIMEType: img.MimeType,
|
|
},
|
|
})
|
|
}
|
|
if m.Content != "" {
|
|
parts = append(parts, genai.NewPartFromText(m.Content))
|
|
}
|
|
contents = append(contents, &genai.Content{
|
|
Role: "user",
|
|
Parts: parts,
|
|
})
|
|
}
|
|
case "assistant":
|
|
var parts []*genai.Part
|
|
if m.Content != "" {
|
|
parts = append(parts, genai.NewPartFromText(m.Content))
|
|
}
|
|
for _, tc := range m.ToolCalls {
|
|
var args map[string]any
|
|
if err := json.Unmarshal(tc.Input, &args); err != nil {
|
|
args = map[string]any{}
|
|
}
|
|
parts = append(parts, &genai.Part{
|
|
FunctionCall: &genai.FunctionCall{
|
|
ID: tc.ID,
|
|
Name: tc.Name,
|
|
Args: args,
|
|
},
|
|
})
|
|
}
|
|
if len(parts) > 0 {
|
|
contents = append(contents, &genai.Content{
|
|
Role: "model",
|
|
Parts: parts,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
// Build tool declarations
|
|
var tools []*genai.Tool
|
|
if len(req.Tools) > 0 {
|
|
var decls []*genai.FunctionDeclaration
|
|
for _, t := range req.Tools {
|
|
var schema any
|
|
if err := json.Unmarshal(t.Parameters, &schema); err != nil {
|
|
schema = map[string]any{"type": "object", "properties": map[string]any{}}
|
|
}
|
|
decls = append(decls, &genai.FunctionDeclaration{
|
|
Name: t.Name,
|
|
Description: t.Description,
|
|
ParametersJsonSchema: schema,
|
|
})
|
|
}
|
|
tools = append(tools, &genai.Tool{FunctionDeclarations: decls})
|
|
}
|
|
|
|
// Build config
|
|
model := req.Model
|
|
if model == "" {
|
|
model = "gemini-2.5-flash"
|
|
}
|
|
|
|
config := &genai.GenerateContentConfig{}
|
|
|
|
if sysPrompt := geminiResolveSystemPrompt(req); sysPrompt != "" {
|
|
config.SystemInstruction = genai.NewContentFromText(sysPrompt, "user")
|
|
}
|
|
|
|
if req.MaxTokens > 0 {
|
|
config.MaxOutputTokens = int32(req.MaxTokens)
|
|
}
|
|
|
|
if req.Temperature > 0 {
|
|
temp := float32(req.Temperature)
|
|
config.Temperature = &temp
|
|
}
|
|
|
|
if len(tools) > 0 {
|
|
config.Tools = tools
|
|
}
|
|
|
|
if budget, ok := p.BuildThinkingBudget(model, req.Reasoning); ok {
|
|
b := budget // need addressable int32 for *int32 field
|
|
config.ThinkingConfig = &genai.ThinkingConfig{
|
|
ThinkingBudget: &b,
|
|
}
|
|
slog.Info("gemini thinking enabled",
|
|
"model", model,
|
|
"budget_tokens", budget)
|
|
} else if req.Reasoning != llm.ReasoningOff {
|
|
slog.Info("reasoning ignored",
|
|
"provider", "gemini",
|
|
"model", model,
|
|
"requested", string(req.Reasoning),
|
|
"reason", "model does not support thinking")
|
|
}
|
|
|
|
// Stream responses
|
|
events := make(chan llm.ChatEvent, 100)
|
|
|
|
go func() {
|
|
defer close(events)
|
|
|
|
var lastUsage *llm.Usage
|
|
|
|
for resp, err := range p.client.Models.GenerateContentStream(ctx, model, contents, config) {
|
|
if err != nil {
|
|
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
|
|
return
|
|
}
|
|
|
|
if resp.UsageMetadata != nil {
|
|
lastUsage = updateUsage(lastUsage,
|
|
int(resp.UsageMetadata.PromptTokenCount),
|
|
int(resp.UsageMetadata.CandidatesTokenCount))
|
|
}
|
|
|
|
for _, cand := range resp.Candidates {
|
|
if cand.Content == nil {
|
|
continue
|
|
}
|
|
for _, part := range cand.Content.Parts {
|
|
if part.Text != "" {
|
|
events <- llm.ChatEvent{
|
|
Type: llm.EventTextDelta,
|
|
Text: part.Text,
|
|
}
|
|
}
|
|
if part.FunctionCall != nil {
|
|
fc := part.FunctionCall
|
|
argsJSON, err := json.Marshal(fc.Args)
|
|
if err != nil {
|
|
argsJSON = []byte("{}")
|
|
}
|
|
// Gemini's FunctionCall.ID is optional and is
|
|
// frequently empty (single, non-parallel calls
|
|
// commonly omit it). Falling back to fc.Name is
|
|
// wrong on two counts: it isn't a valid
|
|
// provider-neutral tool-call ID shape, and it
|
|
// isn't unique — two calls to the same tool in
|
|
// one turn, or the same tool called again later
|
|
// in the conversation (routine for a coding
|
|
// agent re-reading files), collide on the same
|
|
// ID. When that history is later replayed to
|
|
// Anthropic on a routing switch, duplicate
|
|
// tool_use ids across the conversation are
|
|
// rejected with a 400. Mint a synthetic
|
|
// toolu_-shaped ID instead, matching Anthropic's
|
|
// own ID shape so a later replay to Anthropic
|
|
// looks like any other tool_use id.
|
|
id := fc.ID
|
|
if id == "" {
|
|
id = syntheticToolCallID()
|
|
}
|
|
events <- llm.ChatEvent{
|
|
Type: llm.EventToolCallStart,
|
|
ToolCall: &llm.ToolCall{
|
|
ID: id,
|
|
Name: fc.Name,
|
|
},
|
|
}
|
|
events <- llm.ChatEvent{
|
|
Type: llm.EventToolCallDone,
|
|
ToolCall: &llm.ToolCall{
|
|
ID: id,
|
|
Name: fc.Name,
|
|
Input: json.RawMessage(argsJSON),
|
|
},
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Ensure a Done event is always sent
|
|
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage}
|
|
}()
|
|
|
|
return events, nil
|
|
}
|
|
|
|
// updateUsage returns a *llm.Usage carrying the latest cumulative counts.
|
|
// Gemini sends cumulative usage on multiple chunks; we keep only the last and
|
|
// emit a single EventDone at stream end (mirrors the OpenAI provider's lastUsage).
|
|
func updateUsage(_ *llm.Usage, prompt, candidates int) *llm.Usage {
|
|
return &llm.Usage{InputTokens: prompt, OutputTokens: candidates}
|
|
}
|
|
|
|
// syntheticToolCallID mints a unique, Anthropic-shaped tool-call ID
|
|
// ("toolu_" + 16 hex chars) for Gemini function calls that arrive with
|
|
// no ID of their own. Uniqueness (not just shape) is the point: a
|
|
// name-based fallback collides whenever the same tool is called more
|
|
// than once in a conversation, which produces duplicate tool_use ids if
|
|
// that history is later replayed to Anthropic. Falls back to a
|
|
// time+PID-derived suffix if crypto/rand is unavailable — still unique
|
|
// within one process lifetime, which is all a single conversation needs.
|
|
func syntheticToolCallID() string {
|
|
b := make([]byte, 8)
|
|
if _, err := rand.Read(b); err == nil {
|
|
return "toolu_" + hex.EncodeToString(b)
|
|
}
|
|
mix := uint64(time.Now().UnixNano()) ^ uint64(os.Getpid())
|
|
binary.BigEndian.PutUint64(b, mix)
|
|
return "toolu_" + hex.EncodeToString(b)
|
|
}
|
|
|
|
// geminiUnsupportedFields are JSON Schema fields Gemini's "OpenAPI 3.0
|
|
// subset" rejects. This is the broadest strip set across the four
|
|
// providers — most of the cross-provider portability gap shows up here.
|
|
var geminiUnsupportedFields = []string{"anyOf", "oneOf", "not", "$ref", "format"}
|
|
|
|
// NormalizeToolSchema strips fields incompatible with Gemini's OpenAPI
|
|
// 3.0 subset. Diagnostics list every stripped occurrence with a
|
|
// dotted JSON path.
|
|
func (p *GeminiProvider) NormalizeToolSchema(tools []llm.ToolDef) ([]llm.ToolDef, []llm.Diagnostic) {
|
|
return llm.ApplyStripList(tools, geminiUnsupportedFields)
|
|
}
|
|
|
|
// BuildThinkingBudget maps a llm.ReasoningMode to Gemini's thinking budget
|
|
// (in tokens). Returns (0, false) when reasoning is off or the model
|
|
// does not support thinking. Mapping: low=1024, medium=4096, high=16384.
|
|
func (p *GeminiProvider) BuildThinkingBudget(model string, mode llm.ReasoningMode) (int32, bool) {
|
|
if mode == llm.ReasoningOff {
|
|
return 0, false
|
|
}
|
|
if !geminiSupportsThinking(model) {
|
|
return 0, false
|
|
}
|
|
switch mode {
|
|
case llm.ReasoningLow:
|
|
return 1024, true
|
|
case llm.ReasoningMedium:
|
|
return 4096, true
|
|
case llm.ReasoningHigh:
|
|
return 16384, true
|
|
default:
|
|
return 0, false
|
|
}
|
|
}
|
|
|
|
// geminiSupportsThinking returns true for Gemini models that accept the
|
|
// ThinkingConfig field. Conservative — unknown IDs default to false
|
|
// (Gemini's thinking is tightly bound to 2.0-flash-thinking and 2.5
|
|
// families; other models reject the field).
|
|
func geminiSupportsThinking(model string) bool {
|
|
prefixes := []string{"gemini-2.0-flash-thinking", "gemini-2.5"}
|
|
for _, prefix := range prefixes {
|
|
if strings.HasPrefix(model, prefix) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// geminiResolveSystemPrompt returns the effective system prompt string,
|
|
// preferring SystemPromptParts when present. Mirrors the OpenAI
|
|
// resolution path but the per-provider helper avoids importing the
|
|
// genai SDK in test code.
|
|
func geminiResolveSystemPrompt(req llm.ChatRequest) string {
|
|
if len(req.SystemPromptParts) > 0 {
|
|
return llm.JoinSystemPromptParts(req.SystemPromptParts)
|
|
}
|
|
return req.SystemPrompt
|
|
}
|
|
|