geminiapi

package
v0.2.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package geminiapi implements the Gemini API ingress dialect (generateContent and streamGenerateContent): it translates client requests into the canonical chat request and renders canonical responses back in the Gemini shape. It depends only on internal/core; talking to the Gemini upstream is the gemini provider's job (see ADR-0017).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IncludeThoughts

func IncludeThoughts(req *GenerateContentRequest) bool

IncludeThoughts reports whether the request asked for the model's thoughts (generationConfig.thinkingConfig.includeThoughts).

func NewStreamConverter

func NewStreamConverter(body io.ReadCloser, model string, opts ResponseOptions) io.ReadCloser

NewStreamConverter wraps an OpenAI-style chat completion SSE stream and emits the equivalent streamGenerateContent SSE stream (alt=sse): one "data:" event per GenerateContentResponse. The returned reader owns body and closes it on Close.

func ToChatRequest

func ToChatRequest(req *GenerateContentRequest, model string, stream bool) (*core.ChatRequest, error)

ToChatRequest translates a generateContent request into the canonical chat request. model comes from the request path and stream from the method (streamGenerateContent). The translation is provider-agnostic. A member the canonical request cannot represent is rejected with a 400 that names it when dropping it would change what the model is asked (cached content, built-in tools, file references); tuning members without a portable equivalent (topK, safetySettings, …) are ignored.

Types

type Blob

type Blob struct {
	MimeType    string `json:"mimeType,omitempty"`
	MimeTypeAlt string `json:"mime_type,omitempty" swaggerignore:"true"`
	Data        string `json:"data,omitempty"`
}

Blob is inline media: base64 data with its MIME type.

type Candidate

type Candidate struct {
	Content      ResponseContent `json:"content"`
	FinishReason string          `json:"finishReason,omitempty"`
	Index        int             `json:"index"`
}

Candidate is one generated answer.

type Content

type Content struct {
	Role  string `json:"role,omitempty"`
	Parts []Part `json:"parts"`
}

Content is one turn of the conversation: a role ("user" or "model") and its parts.

type ErrorObject

type ErrorObject struct {
	// Code is the HTTP status code.
	Code    int    `json:"code"`
	Message string `json:"message"`
	// Status is the canonical gRPC status name, e.g. INVALID_ARGUMENT.
	Status string `json:"status"`
}

ErrorObject is the inner error of a Gemini error envelope.

type ErrorResponse

type ErrorResponse struct {
	Error ErrorObject `json:"error"`
}

ErrorResponse is the Gemini (google.rpc.Status) error envelope.

func ErrorFromGateway

func ErrorFromGateway(err *core.GatewayError) (int, ErrorResponse)

ErrorFromGateway converts a gateway error into an HTTP status code and the Gemini error envelope. A nil error is reported as a generic INTERNAL error.

func NewErrorResponse

func NewErrorResponse(status int, message string) ErrorResponse

NewErrorResponse builds the Gemini error envelope for an HTTP status.

type FunctionCall

type FunctionCall struct {
	ID   string          `json:"id,omitempty"`
	Name string          `json:"name"`
	Args json.RawMessage `json:"args,omitempty" swaggertype:"object"`
}

FunctionCall is a function the model wants called.

type FunctionCallingConfig

type FunctionCallingConfig struct {
	Mode                    string   `json:"mode,omitempty"`
	AllowedFunctionNames    []string `json:"allowedFunctionNames,omitempty"`
	AllowedFunctionNamesAlt []string `json:"allowed_function_names,omitempty" swaggerignore:"true"`
}

FunctionCallingConfig selects the function calling mode: AUTO, ANY, NONE or VALIDATED, optionally limited to AllowedFunctionNames.

type FunctionDeclaration

type FunctionDeclaration struct {
	Name                    string          `json:"name"`
	Description             string          `json:"description,omitempty"`
	Parameters              json.RawMessage `json:"parameters,omitempty" swaggertype:"object"`
	ParametersJSONSchema    json.RawMessage `json:"parametersJsonSchema,omitempty" swaggertype:"object"`
	ParametersJSONSchemaAlt json.RawMessage `json:"parameters_json_schema,omitempty" swaggerignore:"true"`
}

FunctionDeclaration describes one callable function. Parameters is Gemini's OpenAPI-style Schema; ParametersJSONSchema is standard JSON Schema.

type FunctionResponse

type FunctionResponse struct {
	ID       string          `json:"id,omitempty"`
	Name     string          `json:"name"`
	Response json.RawMessage `json:"response,omitempty" swaggertype:"object"`
	// Parts holds media a function returned (Gemini 3). A tool message
	// carries text only, so a response with parts is refused.
	Parts json.RawMessage `json:"parts,omitempty" swaggerignore:"true"`
}

FunctionResponse is the client's result for a FunctionCall.

type GenerateContentRequest

type GenerateContentRequest struct {
	Contents             []Content         `json:"contents" binding:"required"`
	SystemInstruction    *Content          `json:"systemInstruction,omitempty"`
	SystemInstructionAlt *Content          `json:"system_instruction,omitempty" swaggerignore:"true"`
	Tools                []Tool            `json:"tools,omitempty"`
	ToolConfig           *ToolConfig       `json:"toolConfig,omitempty"`
	ToolConfigAlt        *ToolConfig       `json:"tool_config,omitempty" swaggerignore:"true"`
	GenerationConfig     *GenerationConfig `json:"generationConfig,omitempty"`
	GenerationConfigAlt  *GenerationConfig `json:"generation_config,omitempty" swaggerignore:"true"`
	// SafetySettings are accepted and ignored: they have no portable
	// equivalent, and a provider's own defaults apply.
	SafetySettings    json.RawMessage `json:"safetySettings,omitempty" swaggertype:"array,object"`
	SafetySettingsAlt json.RawMessage `json:"safety_settings,omitempty" swaggerignore:"true"`
	// CachedContent is not supported: a request that sets it is refused
	// with a 400.
	CachedContent    string `json:"cachedContent,omitempty"`
	CachedContentAlt string `json:"cached_content,omitempty" swaggerignore:"true"`
	// Store is whether the provider may retain the request. It is carried
	// as the Chat Completions store flag, which means the same.
	Store *bool `json:"store,omitempty"`
}

GenerateContentRequest is the body of generateContent and streamGenerateContent.

func DecodeGenerateContentRequest

func DecodeGenerateContentRequest(body []byte) (*GenerateContentRequest, error)

DecodeGenerateContentRequest parses a generateContent request body.

type GenerateContentResponse

type GenerateContentResponse struct {
	Candidates    []Candidate    `json:"candidates"`
	UsageMetadata *UsageMetadata `json:"usageMetadata,omitempty"`
	ModelVersion  string         `json:"modelVersion,omitempty"`
	ResponseID    string         `json:"responseId,omitempty"`
}

GenerateContentResponse is the generateContent response body and each streamGenerateContent event.

func FromChatResponse

func FromChatResponse(resp *core.ChatResponse, opts ResponseOptions) *GenerateContentResponse

FromChatResponse renders a canonical chat response in the generateContent response shape.

type GenerationConfig

type GenerationConfig struct {
	Temperature        *float64 `json:"temperature,omitempty"`
	TopP               *float64 `json:"topP,omitempty"`
	TopPAlt            *float64 `json:"top_p,omitempty" swaggerignore:"true"`
	MaxOutputTokens    *int     `json:"maxOutputTokens,omitempty"`
	MaxOutputTokensAlt *int     `json:"max_output_tokens,omitempty" swaggerignore:"true"`
	StopSequences      []string `json:"stopSequences,omitempty"`
	StopSequencesAlt   []string `json:"stop_sequences,omitempty" swaggerignore:"true"`
	// CandidateCount above 1 is refused with a 400.
	CandidateCount        *int            `json:"candidateCount,omitempty"`
	CandidateCountAlt     *int            `json:"candidate_count,omitempty" swaggerignore:"true"`
	Seed                  *int64          `json:"seed,omitempty"`
	PresencePenalty       *float64        `json:"presencePenalty,omitempty"`
	PresencePenaltyAlt    *float64        `json:"presence_penalty,omitempty" swaggerignore:"true"`
	FrequencyPenalty      *float64        `json:"frequencyPenalty,omitempty"`
	FrequencyPenaltyAlt   *float64        `json:"frequency_penalty,omitempty" swaggerignore:"true"`
	ResponseMimeType      string          `json:"responseMimeType,omitempty"`
	ResponseMimeTypeAlt   string          `json:"response_mime_type,omitempty" swaggerignore:"true"`
	ResponseSchema        json.RawMessage `json:"responseSchema,omitempty" swaggertype:"object"`
	ResponseSchemaAlt     json.RawMessage `json:"response_schema,omitempty" swaggerignore:"true"`
	ResponseJSONSchema    json.RawMessage `json:"responseJsonSchema,omitempty" swaggertype:"object"`
	ResponseJSONSchemaAlt json.RawMessage `json:"response_json_schema,omitempty" swaggerignore:"true"`
	// ResponseModalities other than TEXT are refused with a 400.
	ResponseModalities    []string        `json:"responseModalities,omitempty"`
	ResponseModalitiesAlt []string        `json:"response_modalities,omitempty" swaggerignore:"true"`
	ThinkingConfig        *ThinkingConfig `json:"thinkingConfig,omitempty"`
	ThinkingConfigAlt     *ThinkingConfig `json:"thinking_config,omitempty" swaggerignore:"true"`
}

GenerationConfig holds the sampling and output options.

type ModelInfo

type ModelInfo struct {
	// Name is the resource name: "models/" followed by the model ID.
	Name                       string   `json:"name"`
	DisplayName                string   `json:"displayName,omitempty"`
	Description                string   `json:"description,omitempty"`
	InputTokenLimit            int      `json:"inputTokenLimit,omitempty"`
	OutputTokenLimit           int      `json:"outputTokenLimit,omitempty"`
	SupportedGenerationMethods []string `json:"supportedGenerationMethods"`
}

ModelInfo is one model in the Gemini model shape.

func FromModel

func FromModel(model core.Model) ModelInfo

FromModel renders one model in the Gemini model shape. The gateway's model ID, provider prefix included, follows "models/", so the name a client reads from the list is the one it sends back in a request path.

type ModelsList

type ModelsList struct {
	Models        []ModelInfo `json:"models"`
	NextPageToken string      `json:"nextPageToken,omitempty"`
}

ModelsList is the GET /v1beta/models response body.

func FromModels

func FromModels(models []core.Model) *ModelsList

FromModels renders the catalog in the Gemini models-list shape. The whole catalog is one page: nextPageToken is never set, so SDK pagers stop after a single request.

type Part

type Part struct {
	Text                string            `json:"text,omitempty"`
	InlineData          *Blob             `json:"inlineData,omitempty"`
	InlineDataAlt       *Blob             `json:"inline_data,omitempty" swaggerignore:"true"`
	FunctionCall        *FunctionCall     `json:"functionCall,omitempty"`
	FunctionCallAlt     *FunctionCall     `json:"function_call,omitempty" swaggerignore:"true"`
	FunctionResponse    *FunctionResponse `json:"functionResponse,omitempty"`
	FunctionResponseAlt *FunctionResponse `json:"function_response,omitempty" swaggerignore:"true"`
	// Thought marks model reasoning, as opposed to the answer.
	Thought bool `json:"thought,omitempty"`
	// ThoughtSignature is opaque state Gemini 3 and later return on a part and
	// require back unchanged when the conversation continues.
	ThoughtSignature    string `json:"thoughtSignature,omitempty"`
	ThoughtSignatureAlt string `json:"thought_signature,omitempty" swaggerignore:"true"`

	// Members that carry content the translation cannot represent. They are
	// decoded only so a request carrying one is refused by name instead of
	// losing it silently. Members that only tune how a part is read
	// (videoMetadata, mediaResolution) are not declared and are ignored.
	FileData               json.RawMessage `json:"fileData,omitempty" swaggerignore:"true"`
	FileDataAlt            json.RawMessage `json:"file_data,omitempty" swaggerignore:"true"`
	ExecutableCode         json.RawMessage `json:"executableCode,omitempty" swaggerignore:"true"`
	ExecutableCodeAlt      json.RawMessage `json:"executable_code,omitempty" swaggerignore:"true"`
	CodeExecutionResult    json.RawMessage `json:"codeExecutionResult,omitempty" swaggerignore:"true"`
	CodeExecutionResultAlt json.RawMessage `json:"code_execution_result,omitempty" swaggerignore:"true"`
}

Part is one piece of a Content. Exactly one of the data members is set.

type ResponseContent

type ResponseContent struct {
	Parts []ResponsePart `json:"parts"`
	Role  string         `json:"role"`
}

ResponseContent is the content of a Candidate. Its role is always "model".

type ResponseOptions

type ResponseOptions struct {
	// IncludeThoughts returns the model's reasoning as thought parts, as
	// thinkingConfig.includeThoughts does on the Gemini API. Without it
	// reasoning is left out, which is Gemini's default.
	IncludeThoughts bool
}

ResponseOptions carries what the request asked of the response.

type ResponsePart

type ResponsePart struct {
	Text             *string       `json:"text,omitempty"`
	Thought          bool          `json:"thought,omitempty"`
	FunctionCall     *FunctionCall `json:"functionCall,omitempty"`
	ThoughtSignature string        `json:"thoughtSignature,omitempty"`
}

ResponsePart is one part of a generated answer: text (reasoning when Thought is set) or a function call.

type ThinkingConfig

type ThinkingConfig struct {
	ThinkingBudget     *int   `json:"thinkingBudget,omitempty"`
	ThinkingBudgetAlt  *int   `json:"thinking_budget,omitempty" swaggerignore:"true"`
	ThinkingLevel      string `json:"thinkingLevel,omitempty"`
	ThinkingLevelAlt   string `json:"thinking_level,omitempty" swaggerignore:"true"`
	IncludeThoughts    bool   `json:"includeThoughts,omitempty"`
	IncludeThoughtsAlt bool   `json:"include_thoughts,omitempty" swaggerignore:"true"`
}

ThinkingConfig controls model reasoning: a token budget (Gemini 2.5) or a level (Gemini 3 and later), and whether thoughts are returned.

type Tool

type Tool struct {
	FunctionDeclarations    []FunctionDeclaration `json:"functionDeclarations,omitempty"`
	FunctionDeclarationsAlt []FunctionDeclaration `json:"function_declarations,omitempty" swaggerignore:"true"`
	// contains filtered or unexported fields
}

Tool is a set of tools the model may use. Only function declarations translate; a tool with any other member (googleSearch, codeExecution, …) is a Gemini built-in and is refused.

func (*Tool) UnmarshalJSON

func (t *Tool) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the function declarations and remembers the first other member, which names a built-in tool.

type ToolConfig

type ToolConfig struct {
	FunctionCallingConfig    *FunctionCallingConfig `json:"functionCallingConfig,omitempty"`
	FunctionCallingConfigAlt *FunctionCallingConfig `json:"function_calling_config,omitempty" swaggerignore:"true"`
}

ToolConfig controls function calling.

type UsageMetadata

type UsageMetadata struct {
	PromptTokenCount        int `json:"promptTokenCount"`
	CachedContentTokenCount int `json:"cachedContentTokenCount,omitempty"`
	CandidatesTokenCount    int `json:"candidatesTokenCount"`
	ThoughtsTokenCount      int `json:"thoughtsTokenCount,omitempty"`
	TotalTokenCount         int `json:"totalTokenCount"`
}

UsageMetadata reports token usage in the Gemini shape: promptTokenCount is the whole prompt including cached tokens, and thoughtsTokenCount is counted apart from candidatesTokenCount.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL