leviath_runtime/pipeline/inference.rs
1//! Inference dispatch: building each ready agent's request and handing it to the async lane.
2
3use super::*;
4
5/// The batch-tool-calls hint, prepended to a stage's system blocks when
6/// `InferenceConfig::batch_tool_hint` is set. Identical across every agent,
7/// stage, and run, so it is a stable cache prefix (`CacheHint::Always`). It tells
8/// the model it may emit several `tool_use` blocks per response and should batch
9/// *independent* operations - while explicitly forbidding batching of dependent
10/// ones.
11pub(crate) const BATCH_TOOL_HINT: &str = "You can call multiple tools in a single response. \
12When operations are independent (reading, editing, or writing different files, or \
13writing a file then running a command that doesn't need its output), batch them in \
14one response to cut round trips. Do NOT batch when a call depends on a previous \
15call's result, or when you must see a command's output before deciding the next step.";
16
17/// What the `shell` tool actually runs on Windows, and the PowerShell commands
18/// that stand in for the POSIX ones a model reaches for by reflex. Prepended to
19/// a shell-granting stage's system blocks when [`shell_guidance_for`] returns
20/// it; see [`InferenceConfig::shell_hint`](crate::components::InferenceConfig).
21pub(crate) const WINDOWS_SHELL_HINT: &str = "The shell tool runs on Windows through `cmd.exe /C`, \
22not a POSIX shell. GNU coreutils are not available: use `type` or PowerShell's `Get-Content` \
23instead of `cat`, `findstr` or `Select-String` instead of `grep`, `dir` or `Get-ChildItem` \
24instead of `ls`, and `Measure-Object -Line` instead of `wc -l`. Run a PowerShell command as \
25`powershell -Command \"...\"`. Paths use backslashes and drive letters, and `%VAR%` (cmd) or \
26`$env:VAR` (PowerShell) expands environment variables.";
27
28/// The shell guidance for `os`, or `None` when the platform's shell needs no
29/// explanation (a POSIX shell is what the model already assumes).
30///
31/// Pure over the OS string rather than `#[cfg]`-switched, following
32/// `leviath_sys::browser::open_command_for`, so every branch is reachable under
33/// test on a single platform. Callers pass [`std::env::consts::OS`].
34pub(crate) fn shell_guidance_for(os: &str) -> Option<&'static str> {
35 match os {
36 "windows" => Some(WINDOWS_SHELL_HINT),
37 _ => None,
38 }
39}
40
41/// The framework-authored system blocks a stage carries ahead of its own
42/// context, in the order they are prepended.
43///
44/// Both hints read the same on every agent, stage, and run of a given host, so
45/// they lead the `Always`-tier prefix (which `assemble` already sorts first) and
46/// leave prefix caching intact. `os` is the host OS string
47/// ([`std::env::consts::OS`] in production) and `tools` the stage's advertised
48/// tools: telling a stage that cannot run commands which shell it would have
49/// gotten is pure overhead, so the shell hint is gated on the tool being there.
50///
51/// Note this is a `build_request` concern, so the request paths that assemble
52/// their own [`InferenceRequest`] - `lev test`, title generation, compaction -
53/// carry no hints. That was already true of the batch hint.
54pub(crate) fn hint_blocks(
55 config: Option<&InferenceConfig>,
56 tools: &[Tool],
57 os: &str,
58) -> Vec<leviath_providers::SystemBlock> {
59 let always = |text: &str| leviath_providers::SystemBlock {
60 text: text.to_string(),
61 cache_hint: leviath_core::CacheHint::Always,
62 };
63 let mut blocks = Vec::new();
64 if config.map(|c| c.batch_tool_hint).unwrap_or(false) {
65 blocks.push(always(BATCH_TOOL_HINT));
66 }
67 if config.map(|c| c.shell_hint).unwrap_or(false)
68 && tools.iter().any(|t| t.name == "shell")
69 && let Some(text) = shell_guidance_for(os)
70 {
71 blocks.push(always(text));
72 }
73 blocks
74}
75
76/// Build the [`InferenceRequest`] for an agent from its context window + stage
77/// data. Pure; no `.await` - a custom region's render hook is a bounded,
78/// synchronous Rhai eval. (Ported from `AgentEngine::build_inference_request`,
79/// with provider resolution lifted into the caller so this stays query-friendly.)
80///
81/// `stage_name` / `stage_iterations` feed custom-region `render(ctx)` hooks;
82/// they change nothing when the window has no custom regions.
83pub(crate) fn build_request(
84 window: &ContextWindow,
85 config: Option<&InferenceConfig>,
86 stage: &StageInference,
87 provider: &Arc<dyn Provider>,
88 stage_name: &str,
89 stage_iterations: usize,
90) -> InferenceRequest {
91 let assembled = window.assemble_with_meta(&crate::custom_region::AssembleMeta {
92 stage_name: stage_name.to_string(),
93 stage_iterations,
94 model: stage.model.clone(),
95 });
96 let remaining = window.max_tokens.saturating_sub(window.current_tokens);
97 let caps = provider.capabilities(&stage.model);
98 let output_cap = config
99 .and_then(|c| c.max_output_tokens)
100 .unwrap_or(caps.max_output_tokens);
101 let max_tokens = remaining.min(output_cap);
102
103 let filtered_tools = match stage.tool_filter.as_deref() {
104 Some(filter) if !filter.is_empty() => stage
105 .tools
106 .iter()
107 .filter(|t| filter.iter().any(|f| f == &t.name))
108 .cloned()
109 .collect(),
110 _ => stage.tools.clone(),
111 };
112
113 let temperature = if caps.supports_temperature {
114 config.and_then(|c| c.temperature).unwrap_or(0.7)
115 } else {
116 0.0
117 };
118
119 // Pass through any extra model parameters (top_p, stop, seed, …) so the
120 // provider can apply them; `Null` when there are none.
121 let extra = match config.map(|c| &c.extra_params) {
122 Some(params) if !params.is_empty() => serde_json::Value::Object(params.clone()),
123 _ => serde_json::Value::Null,
124 };
125
126 let mut system = hint_blocks(config, &filtered_tools, std::env::consts::OS);
127 system.extend(assembled.system_blocks);
128
129 InferenceRequest {
130 system,
131 messages: assembled.messages,
132 model: stage.model.clone(),
133 max_tokens,
134 temperature,
135 tools: filtered_tools,
136 extra,
137 request_timeout_secs: config.and_then(|c| c.request_timeout_secs),
138 }
139}
140
141/// Build the [`RetryPolicy`] for a job, applying a stage's per-stage inference
142/// wall-clock cap when configured. Starts from the default policy and, when the
143/// stage set `request_timeout_secs` (from `[stages.<name>.model]`), overrides its
144/// `job_timeout`; otherwise the default job timeout stands. Pure so the override
145/// branch is unit-testable without driving the ECS dispatch.
146pub(crate) fn retry_policy_for(
147 config: Option<&InferenceConfig>,
148) -> crate::inference_bridge::RetryPolicy {
149 let mut policy = crate::inference_bridge::RetryPolicy::default();
150 if let Some(secs) = config.and_then(|c| c.request_timeout_secs) {
151 policy.job_timeout = std::time::Duration::from_secs(secs);
152 }
153 policy
154}
155
156/// The cancellation handles for an agent's currently in-flight async work (its
157/// inference request, its tool batch). Attached when the work is dispatched,
158/// removed when it lands - so the presence of this component means "there is
159/// something running for this agent that a cancel needs to stop".
160///
161/// Without it, cancelling only stopped *new* work from being dispatched: a
162/// request already handed to the async lanes ran to completion, holding its
163/// inference-pool permit or tool-lane capacity the whole time.
164#[derive(Component, Default, Debug)]
165pub struct InFlightWork(pub Vec<crate::cancel::CancelToken>);
166
167/// Stop the in-flight work of every agent that has reached a terminal state, and
168/// drop the handles. Runs before the dispatch systems each tick, so a cancel
169/// takes effect on the very next tick rather than whenever the provider or tool
170/// happens to answer.
171pub fn abort_terminal_work(
172 agents: Query<(Entity, &AgentState, &InFlightWork)>,
173 mut commands: Commands,
174) {
175 crate::tick_scope::clear();
176 for (entity, state, in_flight) in agents.iter() {
177 if !is_terminal_status(&state.status) {
178 continue;
179 }
180 crate::tick_scope::enter(entity);
181 for token in &in_flight.0 {
182 token.cancel();
183 }
184 commands.entity(entity).remove::<InFlightWork>();
185 }
186}
187
188/// Record `token` as in-flight work for `entity`, keeping any already attached
189/// (an agent can have both a tool batch and an inference outstanding across a
190/// tick boundary).
191pub(crate) fn track_in_flight(
192 commands: &mut Commands,
193 entity: Entity,
194 existing: Option<&InFlightWork>,
195 token: crate::cancel::CancelToken,
196) {
197 let mut tokens = existing.map(|w| w.0.clone()).unwrap_or_default();
198 tokens.push(token);
199 commands.entity(entity).insert(InFlightWork(tokens));
200}
201
202/// Inference-dispatch system: for every `ReadyToInfer` agent, resolve its
203/// provider and, **if a per-model permit is free**, build the request, spawn the
204/// inference job, and move it to `AwaitingInference`. If its provider is missing
205/// or no slot is free, it stays `ReadyToInfer` and is retried on a later tick -
206/// no blocking, no wasted task.
207#[allow(clippy::type_complexity)]
208pub fn dispatch_inference(
209 agents: Query<
210 (
211 Entity,
212 &AgentState,
213 &ContextWindow,
214 Option<&InferenceConfig>,
215 &StageInference,
216 Option<&InFlightWork>,
217 Option<&StageProgress>,
218 Option<&DispatchStall>,
219 ),
220 With<ReadyToInfer>,
221 >,
222 stage: Res<InferenceStage>,
223 providers: Res<Providers>,
224 circuits: Option<Res<ProviderCircuits>>,
225 policy: Option<Res<CircuitPolicy>>,
226 par_commands: ParallelCommands,
227) {
228 // Fan out across ready agents: request assembly (`build_request`) is the
229 // per-agent CPU cost and is independent, so it runs in parallel on the
230 // compute pool. Permit acquisition (an atomic semaphore) and the tokio spawn
231 // are thread-safe; the marker swap is batched via `ParallelCommands`.
232 //
233 // This is the one system whose per-agent body runs off the driver thread, so
234 // the thread-local `tick_scope` can't carry an entity back to the catcher.
235 // Each agent's share runs under `run_agent_parallel`, which catches there -
236 // where the entity is known - and marks that agent for `tick` to fail
237 // (issue #109). Clearing the thread-local keeps a panic in the fan-out
238 // machinery *itself* unattributed rather than blamed on whichever agent a
239 // previous system left recorded.
240 crate::tick_scope::clear();
241 let now = chrono::Utc::now().timestamp();
242 let circuit_policy = policy.map(|p| *p).unwrap_or_default();
243 let circuits = circuits.as_deref();
244 agents.par_iter().for_each(
245 |(entity, state, window, config, si, in_flight, progress, stalled)| {
246 crate::tick_scope::run_agent_parallel(entity, &par_commands, &mut || {
247 if state.status != AgentStatus::Active {
248 return; // paused / waiting / cancelled - don't start new work
249 }
250 // Every decline below records why and since when, so the
251 // watchdog can tell a run that is waiting from one that is
252 // waiting for something that will never happen (issue #190).
253 let stall = |reason| {
254 let noted = note_stall(stalled, reason, now);
255 par_commands.command_scope(|mut commands| {
256 commands.entity(entity).insert(noted);
257 });
258 };
259 // The rotation system already moved this agent onto the best
260 // provider still standing. Reaching a tripped one here means
261 // every candidate is out of service, so park rather than send
262 // a request that is going to fail the same way as the last
263 // three (issue #201). The stall watchdog ends the wait.
264 if circuits.is_some_and(|c| c.is_open(&si.provider_name, now, &circuit_policy)) {
265 tracing::debug!(
266 provider = %si.provider_name,
267 "inference waiting: the provider's circuit is open"
268 );
269 stall(StallReason::ProviderCircuitOpen);
270 return;
271 }
272 let Some(provider) = providers.0.get(&si.provider_name) else {
273 // Leave ready and retry later - but say so. A silently
274 // starved agent reads as a wedged run with no error.
275 tracing::warn!(
276 provider = %si.provider_name,
277 "inference waiting: provider not registered"
278 );
279 stall(StallReason::ProviderMissing);
280 return;
281 };
282 let Some(permit) = stage.pools.try_acquire(&si.model) else {
283 // Every in-flight call on this model holds a permit; if
284 // this repeats for minutes, one of them is stuck (see the
285 // default request timeout in leviath-providers).
286 tracing::debug!(
287 model = %si.model,
288 "inference waiting: per-model pool is full"
289 );
290 stall(StallReason::PoolFull);
291 return;
292 };
293 let request = build_request(
294 window,
295 config,
296 si,
297 &provider,
298 &state.current_stage,
299 progress.map(|p| p.iterations).unwrap_or(0),
300 );
301 let job = InferenceJob {
302 entity,
303 provider,
304 request,
305 permit,
306 exact_token_counting: stage.exact_token_counting,
307 };
308 let cancel = crate::cancel::CancelToken::new();
309 // Supervised: this agent is about to become `AwaitingInference`,
310 // which the driver reads as "busy". A job that died without
311 // reporting would leave it waiting on a completion that can no
312 // longer come, so the supervisor reports one in its place.
313 let lost_outcomes = stage.outcomes.clone();
314 let lost_wake = stage.wake.clone();
315 crate::lane_supervisor::spawn_supervised(
316 &stage.runtime,
317 "inference",
318 run_inference_job(
319 job,
320 stage.outcomes.clone(),
321 stage.wake.clone(),
322 retry_policy_for(config),
323 cancel.clone(),
324 ),
325 move |message| {
326 let _ = lost_outcomes.send(InferenceOutcome {
327 entity,
328 result: Err(leviath_providers::ProviderError::Other(message)),
329 // The job never got to measure itself.
330 latency: std::time::Duration::ZERO,
331 });
332 lost_wake.notify_one();
333 },
334 );
335 par_commands.command_scope(|mut commands| {
336 track_in_flight(&mut commands, entity, in_flight, cancel);
337 commands
338 .entity(entity)
339 .remove::<ReadyToInfer>()
340 // Dispatched: whatever it was waiting for, it isn't
341 // waiting any more.
342 .remove::<DispatchStall>()
343 .insert(AwaitingInference);
344 });
345 });
346 },
347 );
348}