Skip to content

agent/server: code-driven provider config via SetProvider - #96

Merged
FMXExpress merged 1 commit into
mainfrom
claude/code-driven-provider-config
May 30, 2026
Merged

FMXExpress merged 1 commit into
mainfrom
claude/code-driven-provider-config

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Closes the gap that made the samples awkward: you couldn't fully configure an embedded TPasClawAgent or TPasClawServer without running pasclaw onboard + pasclaw auth login <provider> on the same machine first, because LoadConfig was the only path to a populated TConfig.Providers.

Now you can:

Agent := TPasClawAgent.Create('claude-opus-4-7');
Agent.SetProvider('anthropic', GetEnvironmentVariable('ANTHROPIC_API_KEY'));
Agent.RegisterTool(TWebSearchTool.Create);
WriteLn(Agent.Run('hi'));

No ~/.pasclaw/config.json required. Same shape on TPasClawServer.

What's new

Three overloads on each component:

procedure SetProvider(const Kind, APIKey: string);
procedure SetProvider(const Kind, APIKey, Model: string);
procedure SetProvider(const Kind, APIKey, Model, APIBase: string);

Kind is a catalog identifier (anthropic, openai, gemini, groq, ollama, ...) — anything LookupProvider in PasClaw.Providers.Catalog recognises. The catalog supplies the default base URL and default model; Model and APIBase overloads override either.

Implementation pattern (mirrors pasclaw auth login)

  1. SetProvider builds a TProviderConfig in-memory via BuildProviderOverride. Raises EPasClawRun if Kind isn't a catalog entry — caught early so embedders see a clear error instead of "provider unavailable" at first Chat.

  2. Stashed in FProviderOverride / FHasProviderOverride. Folded into FConfig.Providers at the right point in the lifecycle:

    • TPasClawAgent.EnsureConfig: after LoadConfig, before EnsureProvider runs.
    • TPasClawServer.Start: after LoadConfig, before the NewProviderFromConfig block.

    Works whether or not ~/.pasclaw/config.json exists.

  3. ApplyProviderOverride finds an existing same-Kind entry and replaces it, or appends. Promotes Kind to DefaultProvider and the override's Model to DefaultModel. Same shape pasclaw auth login writes when it updates credentials in place.

  4. TPasClawAgent calls ApplyProviderOverride immediately when SetProvider is invoked after Chat has already run (FConfig already loaded), and drops FProvider so the next Chat picks up new credentials.

Sample updates

Both SampleSimple.dpr and SampleServer.dpr now:

  • Read ANTHROPIC_API_KEY from the env (Halt(2) with a clear "not set — export and re-run" message when missing)
  • Call SetProvider('anthropic', ApiKey)
  • Proceed normally — no ~/.pasclaw/config.json required

README "Embedding in your own app" section rewritten to show SetProvider in both snippets, with a one-sentence explanation that the catalog supplies defaults and embedders override only what they need.

Verification

Check Result
make clean && make smoke 11/11 OK
cd samples/component-console && make All three sample binaries (Console, Simple, Server) build clean
./build/SampleSimple (no env) Prints "ANTHROPIC_API_KEY not set — export it and re-run.", halts cleanly
ANTHROPIC_API_KEY=sk-ant-fake ./build/SampleSimple Runs all the way through SetProvider → ApplyProviderOverride → NewProviderFromConfig and reaches the actual HTTPS call — only stops at TLS (libcrypto not in build dir, unrelated to this PR)

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

Closes the gap that made the samples awkward: you couldn't fully
configure an embedded TPasClawAgent or TPasClawServer without
running `pasclaw onboard` + `pasclaw auth login <provider>` on
the same machine first, because LoadConfig was the only path to
a populated TConfig.Providers.

New on both components — three overloads each:

  procedure SetProvider(const Kind, APIKey: string);
  procedure SetProvider(const Kind, APIKey, Model: string);
  procedure SetProvider(const Kind, APIKey, Model, APIBase: string);

`Kind` is a catalog identifier ("anthropic", "openai", "gemini",
"groq", "ollama", ...) — anything LookupProvider in
PasClaw.Providers.Catalog recognises. The catalog supplies the
default base URL and default model; Model and APIBase overloads
override either default.

Implementation pattern (mirrors `pasclaw auth login`):

  1. SetProvider builds a TProviderConfig in-memory via
     BuildProviderOverride. Raises EPasClawRun if Kind isn't a
     catalog entry — caught early so embedders see a clear error
     instead of "provider unavailable" at first Chat.

  2. The override is stashed in FProviderOverride /
     FHasProviderOverride. Folded into FConfig.Providers at the
     right point in the lifecycle:
       TPasClawAgent.EnsureConfig: after LoadConfig, before
                                   EnsureProvider runs.
       TPasClawServer.Start:       after LoadConfig, before the
                                   NewProviderFromConfig block.
     This means SetProvider works whether the caller has a
     ~/.pasclaw/config.json or not.

  3. ApplyProviderOverride finds an existing same-Kind entry
     and replaces it, or appends. Then promotes Kind to
     DefaultProvider and the override's Model to DefaultModel.
     Same shape `pasclaw auth login` writes when it updates
     credentials in place.

  4. TPasClawAgent calls ApplyProviderOverride immediately when
     SetProvider is called after Chat has already run (FConfig
     already loaded), and drops FProvider so the next Chat picks
     up new credentials.

Samples updated to use the new API:

  samples/component-console/SampleSimple.dpr
  samples/component-console/SampleServer.dpr

Both read ANTHROPIC_API_KEY from the env (Halt(2) with a clear
message when missing), call SetProvider('anthropic', ApiKey),
then proceed normally. No ~/.pasclaw/config.json required.

README "Embedding in your own app" section rewritten to show
SetProvider in both the agent and server snippets, with a one-
sentence explanation that the catalog supplies defaults and
embedders override only what they need.

Verified:

  * make clean && make smoke — 11/11 OK.
  * cd samples/component-console && make — all three sample
    binaries (Console, Simple, Server) build.
  * ./build/SampleSimple without ANTHROPIC_API_KEY prints the
    clear "not set — export and re-run" message, halts cleanly.
  * ./build/SampleSimple ANTHROPIC_API_KEY=sk-ant-fake runs all
    the way through SetProvider, ApplyProviderOverride,
    NewProviderFromConfig, and the actual HTTPS call — only
    stops at TLS (libcrypto.so not in the build dir, which is
    Indy/OpenSSL packaging, not the provider config path).

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit f55b97e into main May 30, 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: e3a9baa7b9

ℹ️ 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".

Comment on lines +500 to +501
if (FModel = '') and (FProviderOverride.Model <> '') then
FModel := FProviderOverride.Model;

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 Refresh the cached model when changing providers

When SetProvider is called more than once, this guard leaves the first provider's model cached in FModel. For example, SetProvider('anthropic', key1) followed by SetProvider('openai', key2) keeps claude-opus-4-7, and ChatHistory selects FModel ahead of the newly applied FConfig.DefaultModel at line 566, so the OpenAI request is sent with the Anthropic model. The same stale-model behavior exists in TPasClawServer.SetProvider at lines 898-899 and affects the documented Stop / SetProvider / Start flow. Preserve an explicitly user-set Model if desired, but do not treat a model populated by an earlier SetProvider call as immutable.

Useful? React with 👍 / 👎.

Comment on lines +330 to +331
Cfg.DefaultProvider := Override.Kind;
if Override.Model <> '' then Cfg.DefaultModel := Override.Model;

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 Clear stale defaults for providers without a catalog model

For catalog entries with no default model, this conditional leaves TConfig.DefaultModel unchanged. In a fresh embedded process, TConfig.Create initializes it to claude-opus-4-7, while providers such as groq and ollama have an empty catalog default (PasClaw.Providers.Catalog.pas, lines 145-149 and 185-189). As a result, the advertised two-argument calls such as SetProvider('groq', key) or SetProvider('ollama', '') configure the requested provider but send the unrelated Anthropic model unless the caller supplies a model separately. Clear the old default or reject the two-argument form when the selected catalog entry has no model.

Useful? React with 👍 / 👎.

FMXExpress pushed a commit that referenced this pull request May 30, 2026
Two P2 findings from Codex on the merged PR #96, both legitimate:

1. **Cached FModel leaks across provider switches.** The original
   SetProvider had a "belt and suspenders" assignment:

       if (FModel = '') and (FProviderOverride.Model <> '') then
         FModel := FProviderOverride.Model;

   On the first call (e.g. anthropic), FModel was empty so it
   got set to "claude-opus-4-7". On the second call (e.g. openai),
   FModel was no longer empty so the update was skipped — and the
   Anthropic model name got sent to the OpenAI endpoint.

   Fix: drop the assignment entirely. ApplyProviderOverride already
   sets FConfig.DefaultModel, and ChatHistory falls back to it when
   FModel is empty. FModel is reserved for the embedder's EXPLICIT
   choice (constructor or Model property); SetProvider stays out.
   Same fix on TPasClawServer.SetProvider.

2. **Stale TConfig.DefaultModel for catalog entries without a
   default model.** groq and ollama ship Spec.DefaultModel := ''
   in PasClaw.Providers.Catalog (their model name depends on the
   user's deployment / local pull, not a one-size-fits-all). With
   no Model arg and no catalog default, BuildProviderOverride
   produced Result.Model := '', and ApplyProviderOverride's
   `if Override.Model <> ''` guard then SKIPPED updating
   FConfig.DefaultModel — leaving TConfig.Create's seed
   "claude-opus-4-7" in place. Calling
   `Agent.SetProvider('groq', key)` would then try to send
   claude-opus-4-7 to api.groq.com.

   Fix: BuildProviderOverride raises EPasClawRun with a clear
   pointer to the three-arg overload when neither the caller
   nor the catalog supplies a model. Two-arg SetProvider for
   anthropic / openai / etc. (which DO ship catalog defaults)
   keeps working; only the no-default providers now require
   the embedder to spell out the model — which they had to
   anyway for the call to succeed at the API.

Verified with a focused test (built + run, not committed):

    === Test 1: SetProvider must not stick FModel ===
      after anthropic: Agent.Model = ""
      after openai:    Agent.Model = ""
      PASS

    === Test 2: groq w/o explicit model must raise EPasClawRun ===
      PASS: EPasClawRun raised — provider "groq" has no catalog
      default model — pass one explicitly:
      SetProvider('groq', APIKey, '<model-name>')

    === Test 3: groq WITH explicit model must succeed ===
      PASS

`make clean && make smoke` also still 11/11 green.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
FMXExpress added a commit that referenced this pull request May 30, 2026
samples/agent: fix Codex reviews on merged PRs #95 + #96
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