Skip to content

Add TGeminiProvider so the gemini catalog row goes from placeholder to live - #48

Merged
FMXExpress merged 1 commit into
mainfrom
claude/pr44-gemini-provider
May 28, 2026
Merged

FMXExpress merged 1 commit into
mainfrom
claude/pr44-gemini-provider

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Implements TGeminiProvider for Google's generateContent REST API. The gemini row in the catalog flips from pfPlaceholder to a real protocol family (pfGemini) and an end-to-end pasclaw agent call against a Gemini config now actually round-trips.

Endpoint: POST <base>/v1beta/models/<model>:generateContent
Auth:     x-goog-api-key: <key>

Why a new provider class (not a TOpenAIProvider tweak)

Three wire-shape differences make it not fit OpenAI Chat Completions:

  1. Roles are user / model (not assistant). System prompts don't live in the messages array — they go in a top-level systemInstruction field. The request builder joins every mrSystem entry + Options.SystemPrompt with line breaks before placing it there.

  2. Tool calls live in parts[].functionCall; tool results come back via parts[].functionResponse (sent with role user, per Google's spec). functionResponse is keyed by tool name, not id, so the builder pre-scans assistant turns to build an id → name map before emitting contents[].

  3. Tools are wrapped: tools: [{functionDeclarations: [{name, description, parameters}]}] — one outer array, one object, an inner functionDeclarations array. A missing parameters schema emits parameters: {} so Gemini doesn't 400 on tools without input shape.

generationConfig handles maxOutputTokens + temperature from TChatOptions. The response parser normalizes Gemini's STOP / MAX_TOKENS finish reasons to the canonical stop / length / tool_calls strings so the tool loop doesn't need any special-casing, and lifts promptTokenCount / candidatesTokenCount into the usage record.

Scope kept tight (~340 LOC)

In Out (deferred)
text, tool calls, tool results streaming (ChatStream falls back to Chat, like our other non-streaming providers)
systemInstruction aggregation thinkingConfig
generationConfig (max_tokens, temperature) image / media attachments
usageMetadata parsing proxy / extraBody knobs
Finish reason normalization

Wiring changes

  • Catalog: adds pfGemini to TProtocolFamily, flips the gemini row from pfPlaceholder to pfGemini with asHeader / x-goog-api-key. Header comment refreshed to describe the three live families + what pfPlaceholder is still reserved for (Bedrock / Azure / Copilot / Antigravity).
  • Factory: case Spec.Family of gets a pfGemini → TGeminiProvider.Create(APIKey, Base, Model) branch + a uses-clause entry. No call site (onboard / status / tool loop) needs to know whether the kind is Gemini or OpenAI — they all go through NewProviderFromConfig.
  • PasClaw.dproj: new unit added in DCCReference order between OpenAI and Factory. FPC Makefile UNIT_DIRS already covers src/pkg/providers.
  • README: Gemini row drops the "implementation pending" qualifier and documents the auth scheme.

On Nanobot

Skipping — nanobot (nanobot-ai/nanobot and HKUDS/nanobot) isn't a proxy in front of LLMs. It's a peer agent framework that itself consumes the same Anthropic / OpenAI / Gemini APIs PasClaw does. The actual "one endpoint, many providers behind it" proxies in the catalog are LiteLLM (kind: litellm) and OpenRouter (kind: openrouter) — already there.

Test plan

  • pasclaw onboard → pick Gemini → key prompt appears (it's asHeader, not asNone) → config written with kind: gemini, api_base: https://generativelanguage.googleapis.com, default model gemini-1.5-flash
  • pasclaw agent "hi" against the Gemini config — returns text, no errors
  • pasclaw agent "list this directory" — model issues fs_list_dir tool call, tool result loops back, model produces final text. Specifically verify the tool result message is sent as role: "user" + parts[].functionResponse{name, response{result}} and Gemini accepts it
  • Multi-turn tool conversation: after a tool call, the next turn's id → name lookup correctly resolves to the tool name in functionResponse
  • FPC build (make) + Delphi .dproj build cleanly
  • Existing anthropic / openai / groq configs still work — no regression in factory dispatch

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

…o live

New unit src/pkg/providers/PasClaw.Providers.Gemini.pas implements
Google's generateContent REST API directly — different enough from
OpenAI Chat Completions that it doesn't fit TOpenAIProvider:

  Endpoint: POST <base>/v1beta/models/<model>:generateContent
  Auth:     x-goog-api-key: <key>

Three wire-shape differences from the OpenAI / Anthropic providers
that the implementation handles explicitly:

  1. Roles are "user" and "model" (not "assistant"). System prompts
     don't live in the messages array — they go in a top-level
     `systemInstruction` field. Multiple TMessage system entries +
     Options.SystemPrompt are joined with line breaks before being
     placed there.

  2. Tool calls live inside `parts[].functionCall`, and tool results
     come back via `parts[].functionResponse` (sent with role:"user").
     functionResponse is keyed by tool NAME, not by id, so the
     request builder pre-scans assistant turns to build an id->name
     map before emitting the contents[] array.

  3. Tools are declared at the top level as
     `tools: [{functionDeclarations: [{name, description, parameters}]}]`
     — one wrapper array containing a single object with an inner
     functionDeclarations array. The provider also defends against a
     missing parameters schema by emitting `parameters: {}`.

generationConfig handles `maxOutputTokens` + `temperature` from
TChatOptions. The response parser pulls text and functionCall parts
out of every candidate, normalizes Gemini's STOP / MAX_TOKENS finish
reasons to the canonical OpenAI-style stop / length / tool_calls so
the rest of PasClaw doesn't need special-casing, and lifts
promptTokenCount / candidatesTokenCount into the usage record.

Scope kept tight (~340 LOC):

  In   - text, tool calls, tool results, system instruction,
         generationConfig, usage parsing
  Out  - streaming (ChatStream delegates to Chat and emits a single
         text chunk like TOpenAIProvider does for its non-streaming
         providers), thinkingConfig, image / media attachments, proxy
         / extraBody knobs

Wiring changes:

  Catalog adds a `pfGemini` value to TProtocolFamily and flips the
  existing gemini row from pfPlaceholder to pfGemini with auth
  scheme asHeader/x-goog-api-key. Header comment updated to describe
  the three live families + what pfPlaceholder is still reserved for.

  Factory's case dispatch gets a `pfGemini -> TGeminiProvider.Create`
  branch and a uses-clause entry. No call site needs to know whether
  the kind is Gemini or OpenAI — onboard, status, and tool loop all
  go through NewProviderFromConfig.

  PasClaw.dproj picks up the new unit between OpenAI and Factory in
  DCCReference order. FPC Makefile UNIT_DIRS already covers
  src/pkg/providers.

  README's Gemini row drops the "implementation pending" note and
  documents the auth scheme.

Side note: Nanobot (nanobot-ai/nanobot and HKUDS/nanobot) is NOT
being added as a provider. It's a peer agent framework that itself
consumes the same Anthropic / OpenAI / Gemini APIs PasClaw does, not
a proxy in front of them. The actual proxies in the catalog —
LiteLLM (`kind: litellm`) and OpenRouter (`kind: openrouter`) — are
already there and cover the "fan out to many providers behind one
endpoint" use case.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit 149135b into main May 28, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 08958d18e2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

FuncCall := Part.ChildObject('functionCall');
if FuncCall <> nil then
try
TC.Id := FuncCall.GetStr('id', '');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Synthesize ids for Gemini tool calls

When Gemini returns a functionCall, the response has name/args but no OpenAI-style id, so this assigns '' to every Gemini tool call. In the next loop iteration the tool loop stores that empty id on the mrTool result (PasClaw.Tools.ToolLoop.pas lines 278-282), while this provider's request builder only records non-empty ids before resolving functionResponse.name; any Gemini tool call therefore gets sent back as a function response with an empty name and cannot be associated with the requested tool. Please synthesize a stable local id (for example from the function name and part index) when Gemini omits one.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants