pikuri-core 0.0.7 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +17 -30
  3. data/lib/pikuri/agent/chat_transport.rb +168 -107
  4. data/lib/pikuri/agent/configurator.rb +194 -173
  5. data/lib/pikuri/agent/control/cancellable.rb +100 -70
  6. data/lib/pikuri/agent/control/handoff.rb +75 -0
  7. data/lib/pikuri/agent/control/interloper.rb +107 -118
  8. data/lib/pikuri/agent/control.rb +13 -35
  9. data/lib/pikuri/agent/event.rb +144 -197
  10. data/lib/pikuri/agent/extension.rb +83 -95
  11. data/lib/pikuri/agent/history.rb +247 -0
  12. data/lib/pikuri/agent/listener/in_memory_event_list.rb +1 -1
  13. data/lib/pikuri/agent/listener/terminal.rb +169 -136
  14. data/lib/pikuri/agent/listener/token_log.rb +84 -157
  15. data/lib/pikuri/agent/listener.rb +24 -44
  16. data/lib/pikuri/agent/listener_list.rb +32 -47
  17. data/lib/pikuri/agent/request_instrumenter.rb +102 -0
  18. data/lib/pikuri/agent.rb +1095 -577
  19. data/lib/pikuri/attachment.rb +65 -0
  20. data/lib/pikuri/bundler_env.rb +68 -0
  21. data/lib/pikuri/extractor/passthrough.rb +24 -31
  22. data/lib/pikuri/extractor.rb +125 -155
  23. data/lib/pikuri/file_type.rb +64 -136
  24. data/lib/pikuri/finalizers.rb +32 -47
  25. data/lib/pikuri/paths.rb +104 -13
  26. data/lib/pikuri/sanitizer.rb +46 -67
  27. data/lib/pikuri/subprocess.rb +86 -118
  28. data/lib/pikuri/testing.rb +369 -0
  29. data/lib/pikuri/tool/calculator.rb +168 -74
  30. data/lib/pikuri/tool/execute_context.rb +42 -0
  31. data/lib/pikuri/tool/parameters.rb +31 -29
  32. data/lib/pikuri/tool/result.rb +164 -0
  33. data/lib/pikuri/tool/trifecta_legs.rb +248 -0
  34. data/lib/pikuri/tool.rb +416 -67
  35. data/lib/pikuri/trifecta/contribution.rb +43 -0
  36. data/lib/pikuri/trifecta/node.rb +47 -0
  37. data/lib/pikuri/trifecta/report.rb +228 -0
  38. data/lib/pikuri/trifecta.rb +126 -0
  39. data/lib/pikuri/version.rb +1 -1
  40. data/lib/pikuri-core.rb +70 -92
  41. data/prompts/agent-loop.txt +5 -0
  42. data/prompts/pikuri-chat.txt +3 -12
  43. metadata +26 -72
  44. data/lib/pikuri/agent/context_window_detector.rb +0 -222
  45. data/lib/pikuri/agent/control/step_limit.rb +0 -111
  46. data/lib/pikuri/agent/extension_context.rb +0 -147
  47. data/lib/pikuri/agent/listener/rate_limited.rb +0 -172
  48. data/lib/pikuri/agent/synthesizer.rb +0 -171
  49. data/lib/pikuri/extractor/html.rb +0 -303
  50. data/lib/pikuri/tool/fetch.rb +0 -172
  51. data/lib/pikuri/tool/scraper.rb +0 -186
  52. data/lib/pikuri/tool/search/brave.rb +0 -198
  53. data/lib/pikuri/tool/search/duckduckgo.rb +0 -207
  54. data/lib/pikuri/tool/search/engines.rb +0 -186
  55. data/lib/pikuri/tool/search/exa.rb +0 -229
  56. data/lib/pikuri/tool/search/rate_limiter.rb +0 -92
  57. data/lib/pikuri/tool/search/result.rb +0 -29
  58. data/lib/pikuri/tool/web_scrape.rb +0 -121
  59. data/lib/pikuri/tool/web_search.rb +0 -57
  60. data/lib/pikuri/url_cache.rb +0 -112
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3b034cfd9a32f43694e474444155ea4e18c0c728449f50f33755a789b4879ab6
4
- data.tar.gz: 0fdff7d50e07f52f9063b240db87e67d8bb93ac85a09cbb56b3caace3232478c
3
+ metadata.gz: 7a738319823ef2f5208a2a016af54ecb161082d378f44f5a745ad4fd9fc7044b
4
+ data.tar.gz: 2b2d0bd51009176acd6405b7a4c7e2b7e3127db618269b95f0cb80d597745c29
5
5
  SHA512:
6
- metadata.gz: 25ac79d6951ce4574d6400742bec3603306c72ca334786a13c34c3a3a5ab48de2735be5b5f51b1b6a25aa647c8f3d36da2f53d3bc97072ea276528464d6d4e16
7
- data.tar.gz: 60100a4ab334e08066b29057d0eea4003a6c0db67947cf17a81484308dcd305ef08869b740965d6e81be246fd3ca964ad5afb2ca668bc101eaa867ed63c1bc02
6
+ metadata.gz: cf9adcef0e8c7d148abe59e8f1b010ec75671802eede2fda6eed16d5dacb327af34d4402bedc1042df7c025d64814a5bb37cec9df55f70afceaa434119f4ce67
7
+ data.tar.gz: 23cbdbe94df3a7a74d9d06944718ec77604afe54c130b621e52a2f3fe218aacc8ab14cbf847bc5868c256460a6e51516b68024bb01318eb1b7e3775730d561bd
data/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # pikuri-core
2
2
 
3
- The lean, audit-friendly foundation of the [pikuri](https://codeberg.org/mvysny/pikuri)
3
+ The lean, audit-friendly foundation of the [pikuri](https://github.com/mvysny/pikuri)
4
4
  AI-assistant toolkit:
5
5
 
6
6
  - `Pikuri::Agent` — a thin wrapper around ruby_llm's chat loop with
@@ -10,23 +10,19 @@ AI-assistant toolkit:
10
10
  (`Pikuri::Tool::Parameters`) and LLM-actionable error messages.
11
11
  - Listener stream (`Pikuri::Agent::Listener::*`) for rendering,
12
12
  token accounting, and structured capture.
13
- - Controls (`StepLimit`, `Cancellable`, `Interloper`) for budget
14
- enforcement + cancellation.
15
- - Three stateless bundled tools (`CALCULATOR`, `WEB_SCRAPE`,
16
- `FETCH`) plus a host-configured web-search tool built via
17
- `Pikuri::Tool::WebSearch.build` (provider keys passed in, never
18
- read from the environment).
13
+ - Controls (`Cancellable`, `Interloper`) for cancellation and
14
+ mid-loop injection. The loop itself is unbounded — see
15
+ `design/decisions.md` `D_no_step_limit`.
16
+ - One bundled example tool, `Pikuri::Tool::CALCULATOR`.
19
17
  - A demo binary, `bin/pikuri-chat`.
20
18
 
21
- Extensions (skills, MCP, workspace, coding stack, named-agent
22
- personas) live in sibling gems and opt in à la carte — see
23
- [`pikuri-skills`](../pikuri-skills/README.md),
24
- [`pikuri-mcp`](../pikuri-mcp/README.md),
19
+ Extensions (web tools, skills, MCP, workspace, coding stack,
20
+ named-agent personas) live in sibling gems and opt in à la carte — see
21
+ [`pikuri-web`](../pikuri-web/README.md),
22
+ [`pikuri-skills`](https://github.com/mvysny/pikuri-workshop/blob/master/pikuri-skills/README.md),
23
+ [`pikuri-mcp`](https://github.com/mvysny/pikuri-workshop/blob/master/pikuri-mcp/README.md),
25
24
  [`pikuri-workspace`](../pikuri-workspace/README.md),
26
- [`pikuri-code`](../pikuri-code/README.md),
27
- [`pikuri-assistant`](../pikuri-assistant/README.md). For the
28
- convenience bundle that pulls in everything, see the
29
- [`pikuri`](../pikuri/README.md) metagem.
25
+ [`pikuri-code`](https://github.com/mvysny/pikuri-workshop/blob/master/pikuri-code/README.md).
30
26
 
31
27
  ## Install
32
28
 
@@ -44,22 +40,14 @@ gem install pikuri-core
44
40
  ```ruby
45
41
  require 'pikuri-core'
46
42
 
47
- RubyLLM.configure do |c|
48
- c.openai_api_base = 'http://localhost:8080/v1'
49
- c.openai_api_key = 'not-needed'
50
- end
51
-
52
43
  agent = Pikuri::Agent.new(
53
- transport: Pikuri::Agent::ChatTransport.new(
54
- model: 'unsloth/Qwen3.6-35B-A3B-GGUF',
55
- provider: :openai,
56
- assume_model_exists: true
44
+ transport: Pikuri::Agent::ChatTransport.from_openai_server(
45
+ server: 'http://localhost:8080',
46
+ model: 'ornith-ai/Ornith-1.5-35B-A3B-GGUF'
57
47
  ),
58
- system_prompt: Pikuri.prompt(:'pikuri-chat'),
59
- step_limit: Pikuri::Agent::Control::StepLimit.new(max: 20)
48
+ system_prompt: Pikuri.prompt(:'pikuri-chat')
60
49
  ) do |c|
61
50
  c.add_tool Pikuri::Tool::CALCULATOR
62
- c.add_tool Pikuri::Tool::WebSearch.build
63
51
  c.add_listener Pikuri::Agent::Listener::Terminal.new
64
52
  end
65
53
  agent.run_loop(user_message: 'What is 17 * 23?')
@@ -70,10 +58,9 @@ handling, and cancellation.
70
58
 
71
59
  ## Further reading
72
60
 
73
- - **Narrative walkthrough:** [chapter 1 of the pikuri guide](../docs/guide/01-chat.md)
61
+ - **Narrative walkthrough:** [the first-conversation chapter of the pikuri guide](../book/chat.md)
74
62
  — install llama.cpp, start the server, run `pikuri-chat`, the
75
- agentic loop, the four bundled tools, and search-provider
76
- privacy postures.
63
+ agentic loop, and the tools `pikuri-chat` wires.
77
64
  - **API reference:** browse the YARD docs at
78
65
  <https://rubydoc.info/gems/pikuri-core> (once published), or run
79
66
  `bundle exec yard` in this directory for a local copy.
@@ -2,107 +2,123 @@
2
2
 
3
3
  module Pikuri
4
4
  class Agent
5
- # Everything that has to travel together for a chat to resolve to
6
- # the same model *on the same server* on every construction: the
7
- # model id, the provider hint, the registry-bypass flag, and — when
8
- # the model lives on a server other than the process-global
9
- # +RubyLLM.config+ default — that server's base URL and API key.
10
- #
11
- # Bundling them is structural protection against a recurring bug
12
- # class — every forwarding site (the synthesizer rescue in
13
- # {Agent#run_loop}, the +agent+ tool from +pikuri-subagents+
14
- # spawning a sub-agent, a mid-conversation model switch) used to
15
- # pass the resolution fields individually, and dropping one routed
16
- # the chat to a different server or raised
17
- # +RubyLLM::ModelNotFoundError+ on the unknown model id. With a
18
- # single value object the call site can't silently miss a field.
5
+ # Everything that must travel together for a chat to resolve to the same
6
+ # model *on the same server* on every construction: model id, provider
7
+ # hint, registry-bypass flag, and — when the model lives off the
8
+ # process-global +RubyLLM.config+ default — that server's base URL and API
9
+ # key. One value object so a forwarding site (the synthesizer, a sub-agent
10
+ # spawn, a mid-conversation switch) can't silently drop a field and route
11
+ # the chat to the wrong server or raise +RubyLLM::ModelNotFoundError+.
19
12
  #
20
13
  # == Why +api_base+ / +api_key+ live here
21
14
  #
22
- # +RubyLLM::Chat#with_model+ swaps only the model/provider against
23
- # the chat's *existing* connection config, so switching to a model
24
- # on a different server (a small local llama.cpp vs a big cloud
25
- # model) needs the connection to travel with the model — otherwise
26
- # the new model id is sent to the old server's URL with the old
27
- # key. {Agent} maps these two generic fields onto the provider's
28
- # ruby_llm config slots (+#{provider}_api_base+ /
29
- # +#{provider}_api_key+) via a per-chat +RubyLLM::Context+; both are
30
- # +nil+ for a transport that rides the process-global config.
15
+ # +RubyLLM::Chat#with_model+ swaps only model/provider against the chat's
16
+ # *existing* connection, so switching to a model on a different server
17
+ # needs the connection to travel with the model — else the new id is sent
18
+ # to the old server's URL with the old key. {Agent} maps these two generic
19
+ # fields onto the provider's config slots (+#{provider}_api_base+ /
20
+ # +#{provider}_api_key+) via a per-chat +RubyLLM::Context+; both +nil+ for a
21
+ # transport riding the global config.
22
+ #
23
+ # No +RubyLLM+ references here, so the seam stays in {Agent},
24
+ # +bin/pikuri-chat+, and {Tool}.
25
+ #
26
+ # == Extra request parameters
27
+ #
28
+ # +params+ is an opaque passthrough for a request key pikuri names no field
29
+ # for. It is deep-merged into the chat-completion payload as written:
30
+ #
31
+ # transport.with(params: { chat_template_kwargs: { enable_thinking: false } })
32
+ # # on the wire: {"model":…,"messages":[…],
33
+ # # "chat_template_kwargs":{"enable_thinking":false}}
31
34
  #
32
- # Pure data carrier: no +RubyLLM+ references here, so the seam stays
33
- # in {Agent}, +bin/pikuri-chat+, and {Tool}.
35
+ # It rides the transport rather than a call because the spelling is
36
+ # per-model-per-server, exactly like +context_window+; pikuri translates
37
+ # none of it — a parameter is sent as written or not at all. Why there is no
38
+ # typed +thinking:+ flag instead: +design/decisions.md+
39
+ # +D_opaque_request_params+.
40
+ #
41
+ # Two edges worth knowing. Keys are deep-symbolized on the way in (naming
42
+ # one key in both spellings raises), without which a table read from TOML
43
+ # would land a second +"temperature"+ beside the payload's +:temperature+
44
+ # instead of overriding it. And the merge is unguarded: a table naming
45
+ # +messages+, +tools+ or +stream+ breaks the loop rather than configuring
46
+ # it, and one naming +model+ sends a model this transport does not think it
47
+ # is using.
34
48
  #
35
49
  # @!attribute [r] model
36
- # @return [String, nil] LLM identifier; +nil+ defers to
37
- # +RubyLLM.config.default_model+ at {Agent} construction time
50
+ # @return [String, nil] LLM id; +nil+ defers to
51
+ # +RubyLLM.config.default_model+ at {Agent} construction.
38
52
  # @!attribute [r] provider
39
- # @return [Symbol, nil] forwarded to +RubyLLM.chat+. Required
40
- # together with +assume_model_exists+ when pointing at a local
41
- # OpenAI-compatible server (llama.cpp, gpustack, ...) whose model
42
- # ids are not in ruby_llm's bundled registry; required whenever
43
- # +api_base+ / +api_key+ is set (it names the config slots).
53
+ # @return [Symbol, nil] forwarded to +RubyLLM.chat+. Required with
54
+ # +assume_model_exists+ for a local OpenAI-compatible server whose ids
55
+ # aren't in ruby_llm's registry, and whenever +api_base+/+api_key+ is
56
+ # set (it names the config slots).
44
57
  # @!attribute [r] assume_model_exists
45
- # @return [Boolean] forwarded to +RubyLLM.chat+; +true+ skips
46
- # ruby_llm's registry lookup and trusts the supplied model id.
47
- # Requires +provider+.
58
+ # @return [Boolean] forwarded to +RubyLLM.chat+; +true+ skips the registry
59
+ # lookup and trusts the model id. Requires +provider+.
48
60
  # @!attribute [r] api_base
49
- # @return [String, nil] connection base URL for this model's
50
- # server (e.g. +http://localhost:8080/v1+). +nil+ rides the
51
- # process-global +RubyLLM.config+ base. Mapped to the provider's
52
- # +#{provider}_api_base+ slot by {Agent}.
61
+ # @return [String, nil] this server's base URL (e.g.
62
+ # +http://localhost:8080/v1+); +nil+ rides the global config. Mapped to
63
+ # +#{provider}_api_base+ by {Agent}.
53
64
  # @!attribute [r] api_key
54
- # @return [String, nil] API key for this model's server. +nil+
55
- # rides the process-global config key. Mapped to the provider's
56
- # +#{provider}_api_key+ slot by {Agent}. Redacted in {#inspect}
57
- # so it never leaks into a log line or backtrace.
65
+ # @return [String, nil] API key for this server; +nil+ rides the global
66
+ # config. Mapped to +#{provider}_api_key+ by {Agent}. Redacted in
67
+ # {#inspect}.
58
68
  # @!attribute [r] context_window
59
- # @return [Integer, nil] explicit context-window cap for this
60
- # model on this server, or +nil+ to defer to
61
- # {ContextWindowDetector}'s probe. Travels with the model
62
- # because the cap *is* a per-model-per-server property: a
63
- # {Ctrl+P}-style switch to a different transport must carry its
64
- # own cap, not inherit the previous model's. Never sent to
65
- # ruby_llm (it is neither a {#chat_kwargs} entry nor a
66
- # connection slot) — pure pikuri metadata read by
67
- # {Agent#detect_and_emit_context_cap!}. The cap-inheritance
68
- # channel too: the +agent+ tool from +pikuri-subagents+ and the
69
- # synthesizer hand a spawned agent +parent.transport.with(
70
- # context_window: parent.context_window_cap)+ so the parent's
71
- # *resolved* cap (explicit or probed) rides along without a
72
- # re-probe.
73
- class ChatTransport < Data.define(:model, :provider, :assume_model_exists, :api_base, :api_key, :context_window)
74
- # Build an +:openai+-provider transport for an OpenAI-compatible
75
- # server (a local llama.cpp, a cloud endpoint, ...), carrying that
76
- # server's connection so the agent rides a per-chat
77
- # +RubyLLM::Context+ instead of the process-global +RubyLLM.config+.
78
- # This is the host-boot factory the +bin/pikuri-*+ demos use in
79
- # place of +RubyLLM.configure+ — one isolated connection per agent,
80
- # so several agents pointed at different servers (and different
81
- # keys) don't stomp a shared global.
69
+ # @return [Integer, nil] this model-on-server's context-window cap, or
70
+ # +nil+ when unknown. Travels
71
+ # with the model because the cap *is* per-model-per-server. pikuri
72
+ # never looks it up: the host states it, or a probe the host runs fills
73
+ # it in. Never sent to ruby_llm, and read by nothing in pikuri-core: it
74
+ # is for the host's own display, and a sub-agent inherits it with the
75
+ # transport.
76
+ # @!attribute [r] modalities
77
+ # @return [Hash{Symbol => Boolean}, nil] which input kinds this
78
+ # model-on-server accepts, in llama.cpp's +/props+ vocabulary
79
+ # (+{vision: false, audio: false}+), or +nil+ when unknown. Only a
80
+ # +false+ entry refuses an attachment ({Agent::UnsupportedAttachmentError});
81
+ # a missing key, like +nil+, lets it go out and leaves any error to the
82
+ # server. Stated and inherited like +context_window+.
83
+ # @!attribute [r] faraday_adapter
84
+ # @return [Class, Symbol, nil] a custom Faraday adapter to install on this
85
+ # agent's per-chat +RubyLLM::Context+ (via +config.faraday_adapter=+),
86
+ # or +nil+ for ruby_llm's default (+:net_http+). A generic HTTP seam —
87
+ # inject a VCR / logging / *scripted-fake* adapter without touching the
88
+ # global +RubyLLM.config+. Its worked use is
89
+ # {Pikuri::Testing.fake_transport}, which bakes an anonymous scripted
90
+ # adapter here so the real ruby_llm loop runs against canned HTTP.
91
+ # @!attribute [r] params
92
+ # @return [Hash{Symbol => Object}] extra chat-completion payload keys,
93
+ # merged in verbatim; +{}+ for none. Keys symbolized, and every hash /
94
+ # array node frozen (a value object is *not* deep-frozen: a +String+
95
+ # value the caller still holds stays mutable).
96
+ # See +== Extra request parameters+.
97
+ class ChatTransport < Data.define(:model, :provider, :assume_model_exists, :api_base, :api_key,
98
+ :context_window, :modalities, :faraday_adapter, :params)
99
+ # Build an +:openai+-provider transport for an OpenAI-compatible server
100
+ # (local llama.cpp, cloud endpoint, ...), carrying its connection so the
101
+ # agent rides a per-chat +RubyLLM::Context+ instead of the global config.
102
+ # The +bin/pikuri-*+ host-boot factory in place of +RubyLLM.configure+ —
103
+ # one isolated connection per agent.
82
104
  #
83
- # +server+ is the bare server origin; a trailing +/v1+ (the
84
- # OpenAI-compatible suffix ruby_llm appends to reach
85
- # +/v1/chat/completions+) is stripped and re-appended exactly once,
86
- # so +https://api.x.ai+, +https://api.x.ai/v1+, and
87
- # +https://api.x.ai/v1/+ all normalize to the same +.../v1+ base.
88
- # Without this, a +server+ value that already ended in +/v1+ would
89
- # double to +/v1/v1+ and every request would 404.
105
+ # A trailing +/v1+ on +server+ is stripped and re-appended exactly once,
106
+ # so +https://api.x.ai+, +.../v1+, and +.../v1/+ all normalize to the same
107
+ # +.../v1+ base — without which a +/v1+-terminated value would double to
108
+ # +/v1/v1+ and 404.
90
109
  #
91
- # @param server [String] server origin, with or without a trailing
92
- # +/v1+, e.g. +"http://localhost:8080"+ or +"https://api.x.ai/v1"+
110
+ # @param server [String] server origin, with or without a trailing +/v1+
93
111
  # @param model [String] model id served there, trusted verbatim
94
- # (+assume_model_exists+ is +true+, so it need not appear in
95
- # ruby_llm's bundled registry)
96
- # @param api_key [String] API key for the server; the conventional
97
- # +"not-needed"+ placeholder for a keyless local server
98
- # @param context_window [Integer, nil] explicit context-window cap
99
- # for this model, or +nil+ to defer to {ContextWindowDetector}'s
100
- # +/props+ probe (the right default for a local llama.cpp, which
101
- # reports its launched +n_ctx+; the right *override* for a cloud
102
- # server the probe can't reach, e.g. a 2M-window model on x.ai)
103
- # @return [ChatTransport] a transport whose +api_base+ is the
104
- # normalized +.../v1+ URL and whose +api_key+ is +api_key+
105
- def self.from_openai_server(server:, model:, api_key: 'not-needed', context_window: nil)
112
+ # @param api_key [String] API key; the +"not-needed"+ placeholder for a
113
+ # keyless local server
114
+ # @param context_window [Integer, nil] the model's cap, or +nil+ for
115
+ # unknown
116
+ # @param params [Hash{String, Symbol => Object}] extra payload keys for
117
+ # this connection, e.g.
118
+ # +{'chat_template_kwargs' => {'enable_thinking' => false}}+
119
+ # @return [ChatTransport]
120
+ def self.from_openai_server(server:, model:, api_key: 'not-needed', context_window: nil,
121
+ params: {})
106
122
  base = server.to_s.strip.chomp('/').delete_suffix('/v1')
107
123
  new(
108
124
  model: model,
@@ -110,7 +126,8 @@ module Pikuri
110
126
  assume_model_exists: true,
111
127
  api_base: "#{base}/v1",
112
128
  api_key: api_key,
113
- context_window: context_window
129
+ context_window: context_window,
130
+ params: params
114
131
  )
115
132
  end
116
133
 
@@ -120,47 +137,91 @@ module Pikuri
120
137
  # @param api_base [String, nil]
121
138
  # @param api_key [String, nil]
122
139
  # @param context_window [Integer, nil]
140
+ # @param modalities [Hash{Symbol => Boolean}, nil]
141
+ # @param faraday_adapter [Class, Symbol, nil]
142
+ # @param params [Hash{String, Symbol => Object}]
123
143
  # @raise [ArgumentError] if +api_base+ or +api_key+ is set without
124
144
  # a +provider+ (the provider names the config slots the
125
- # connection overrides map onto)
126
- def initialize(model:, provider: nil, assume_model_exists: false,
127
- api_base: nil, api_key: nil, context_window: nil)
145
+ # connection overrides map onto), or if +params+ is not a Hash, or
146
+ # names one key in both the +String+ and +Symbol+ spelling
147
+ def initialize(model:, provider: nil, assume_model_exists: false, api_base: nil,
148
+ api_key: nil, context_window: nil, modalities: nil, faraday_adapter: nil,
149
+ params: {})
128
150
  if (api_base || api_key) && provider.nil?
129
151
  raise ArgumentError, "api_base/api_key require a provider, got #{provider.inspect}"
130
152
  end
153
+ raise ArgumentError, "params must be a Hash, got #{params.class}" unless params.is_a?(Hash)
131
154
 
132
- super
155
+ super(model: model, provider: provider, assume_model_exists: assume_model_exists,
156
+ api_base: api_base, api_key: api_key, context_window: context_window,
157
+ modalities: modalities&.transform_keys(&:to_sym)&.freeze,
158
+ faraday_adapter: faraday_adapter, params: deep_symbolize(params))
133
159
  end
134
160
 
135
- # The model-resolution kwargs to spread into +RubyLLM.chat+ /
136
- # +RubyLLM::Context#chat+. Excludes the connection fields — those
137
- # configure the +Context+ the chat is built from, not the +chat+
138
- # call itself.
161
+ # Model-resolution kwargs to spread into +RubyLLM.chat+ /
162
+ # +RubyLLM::Context#chat+. Excludes the connection fields (those configure
163
+ # the +Context+, not the +chat+ call) and +params+ (a
164
+ # +with_provider_options+ call on the built chat).
139
165
  #
140
166
  # @return [Hash{Symbol => String, Symbol, Boolean, nil}]
141
167
  def chat_kwargs
142
168
  { model: model, provider: provider, assume_model_exists: assume_model_exists }
143
169
  end
144
170
 
145
- # Whether this transport overrides the process-global connection
146
- # (and so needs a dedicated +RubyLLM::Context+).
171
+ # Default +Data#inspect+ would print +api_key+ verbatim into any log line
172
+ # or backtrace. Redact it.
147
173
  #
148
- # @return [Boolean]
149
- def connection_overrides?
150
- !api_base.nil? || !api_key.nil?
151
- end
152
-
153
- # Default +Data#inspect+ would print +api_key+ verbatim, leaking
154
- # the secret into any log line, +to_s+ interpolation, or backtrace
155
- # that touches the transport. Redact it.
174
+ # +params+ is configuration rather than a credential channel, so it prints
175
+ # verbatim — anything sensitive a host puts there lands in every log line
176
+ # and backtrace that inspects a transport.
156
177
  #
157
178
  # @return [String]
158
179
  def inspect
159
180
  "#<#{self.class} model=#{model.inspect} provider=#{provider.inspect} " \
160
181
  "assume_model_exists=#{assume_model_exists} api_base=#{api_base.inspect} " \
161
- "api_key=#{api_key.nil? ? 'nil' : '[REDACTED]'} context_window=#{context_window.inspect}>"
182
+ "api_key=#{api_key.nil? ? 'nil' : '[REDACTED]'} context_window=#{context_window.inspect} " \
183
+ "modalities=#{modalities.inspect} faraday_adapter=#{faraday_adapter.inspect} params=#{params.inspect}>"
162
184
  end
163
185
  alias to_s inspect
186
+
187
+ private
188
+
189
+ # Recursively symbolize +value+'s hash keys, freezing what it builds.
190
+ # Scalars pass through as they are — only the containers are rebuilt.
191
+ #
192
+ # @param value [Hash, Array, Object] any +params+ subtree.
193
+ # @return [Hash, Array, Object] the same shape, symbol-keyed, with every
194
+ # hash / array node frozen.
195
+ # @raise [ArgumentError] if a hash names one key in both spellings —
196
+ # the merge can send only one of them, and picking silently is the
197
+ # failure mode this whole channel exists to avoid.
198
+ def deep_symbolize(value)
199
+ case value
200
+ when Hash
201
+ symbolized = value.to_h { |k, v| [symbolize_key(k), deep_symbolize(v)] }
202
+ reject_collisions(value) if symbolized.size < value.size
203
+ symbolized.freeze
204
+ when Array
205
+ value.map { |item| deep_symbolize(item) }.freeze
206
+ else
207
+ value
208
+ end
209
+ end
210
+
211
+ # @param key [Object] a +params+ hash key.
212
+ # @return [Object] +key+ as a +Symbol+, or unchanged if it has no
213
+ # symbol form (an +Integer+ key in a provider's own table).
214
+ def symbolize_key(key)
215
+ key.respond_to?(:to_sym) ? key.to_sym : key
216
+ end
217
+
218
+ # @param table [Hash] the pre-symbolize hash whose keys collided.
219
+ # @return [void]
220
+ # @raise [ArgumentError] always, naming the colliding spellings.
221
+ def reject_collisions(table)
222
+ collided = table.keys.group_by { |k| symbolize_key(k) }.select { |_, ks| ks.size > 1 }
223
+ raise ArgumentError, "params names a key twice: #{collided.values.flatten.inspect}"
224
+ end
164
225
  end
165
226
  end
166
227
  end