Skip to main content

rinne_workers/adapters/
openai_api.rs

1//! OpenAI-compatible API worker adapter (`CONTEXT.md` §8, §16).
2//!
3//! A raw model on the user's own key. Unlike a harness, it sees only what is
4//! sent, so the context assembler inlines file *contents* here, not paths
5//! (`CONTEXT.md` §8 behavioral split, §12). Always metered (`CONTEXT.md` §9).
6
7use std::sync::Arc;
8use std::time::Instant;
9
10use async_trait::async_trait;
11use tokio_util::sync::CancellationToken;
12
13use rinne_core::worker::{
14    emit, AuthMode, Capability, EventSink, ExecStatus, ExecuteRequest, ExecuteResult,
15    LatencyProfile, QuotaModel, ToolExecutor, Transport, Usage, Worker, WorkerDescriptor,
16    WorkerEvent, WorkerFamily,
17};
18use rinne_core::{Result, RinneError};
19
20use crate::adapters::common::render_symbol_map;
21use crate::transport::http::{ChatMessage, ChatRequest, ChatTurn, OpenAiClient};
22
23/// An API worker backed by an OpenAI-compatible endpoint, with an optional pool
24/// of keys it rotates across when one is rate-limited (`CONTEXT.md` §13).
25pub struct OpenAiWorker {
26    descriptor: WorkerDescriptor,
27    base_url: String,
28    /// Key pool; rotated on rate-limit. The user's own keys, never pooled across
29    /// users (`CONTEXT.md` §4).
30    keys: Vec<String>,
31    /// Default model when a node doesn't pin one.
32    default_model: String,
33    system_prompt: String,
34    /// Provider-specific params merged into each request.
35    extra_body: Option<serde_json::Value>,
36    /// Executes MCP tool calls for the host agentic loop (`MCP_SKILLS.md` §6).
37    /// `None` means no tools are wired; the worker then always runs the plain
38    /// streaming path regardless of a node's `tools`.
39    tool_executor: Option<Arc<dyn ToolExecutor>>,
40}
41
42impl OpenAiWorker {
43    /// Build an API worker.
44    ///
45    /// `name` is the Rinne worker name (e.g. `openrouter`, `deepseek`).
46    /// `base_url` includes the version (e.g. `https://api.openai.com/v1`).
47    /// `keys` is the user's key pool (rotated on rate-limit). `models` is the
48    /// ladder cheap→strong; the first is the default. The per-node model
49    /// (conductor's choice or a cascade escalation) overrides the default.
50    pub fn new(
51        name: &str,
52        base_url: &str,
53        keys: Vec<String>,
54        models: Vec<String>,
55        capabilities: Vec<Capability>,
56        extra_body: Option<serde_json::Value>,
57    ) -> Self {
58        let default_model = models
59            .first()
60            .cloned()
61            .unwrap_or_else(|| "gpt-4o-mini".to_string());
62        Self {
63            extra_body,
64            tool_executor: None,
65            descriptor: WorkerDescriptor {
66                name: name.to_string(),
67                family: WorkerFamily::Api,
68                capabilities,
69                auth_mode: AuthMode::ApiKey,
70                quota: QuotaModel::unlimited(),
71                latency: LatencyProfile::Fast,
72                transport: Transport::Http,
73                models,
74            },
75            base_url: base_url.to_string(),
76            keys: if keys.is_empty() {
77                vec![String::new()]
78            } else {
79                keys
80            },
81            default_model,
82            system_prompt: "You are a focused worker inside an orchestration system. \
83                Follow the instruction precisely and return only the requested result."
84                .to_string(),
85        }
86    }
87
88    /// Wire an MCP tool executor so nodes that attach `tools` get the host
89    /// agentic loop (`MCP_SKILLS.md` §6). Without one the worker ignores tools.
90    pub fn with_tool_executor(mut self, executor: Arc<dyn ToolExecutor>) -> Self {
91        self.tool_executor = Some(executor);
92        self
93    }
94}
95
96/// Whether an error looks like a rate-limit/quota condition worth rotating keys.
97fn is_rate_limited(err: &rinne_core::RinneError) -> bool {
98    let s = err.to_string().to_lowercase();
99    s.contains("429")
100        || s.contains("rate limit")
101        || s.contains("quota")
102        || s.contains("too many requests")
103}
104
105#[async_trait]
106impl Worker for OpenAiWorker {
107    fn descriptor(&self) -> &WorkerDescriptor {
108        &self.descriptor
109    }
110
111    /// An API worker serves MCP tools when a tool executor is wired (the host
112    /// agentic loop, `MCP_SKILLS.md` §6).
113    fn serves_mcp_tools(&self) -> bool {
114        self.tool_executor.is_some()
115    }
116
117    async fn execute(
118        &self,
119        request: ExecuteRequest,
120        events: EventSink,
121        cancel: CancellationToken,
122    ) -> Result<ExecuteResult> {
123        let started = Instant::now();
124
125        // The per-node model (conductor's tier choice or a cascade escalation)
126        // wins; otherwise the worker's default model.
127        let model = request
128            .constraints
129            .model
130            .clone()
131            .unwrap_or_else(|| self.default_model.clone());
132
133        // Host path: a node that attaches tools, with an executor wired, runs the
134        // agentic loop instead of a single streamed completion (`MCP_SKILLS.md` §6).
135        if !request.tools.is_empty() {
136            if let Some(executor) = self.tool_executor.clone() {
137                return self
138                    .run_tool_loop(&request, model, executor, &events, &cancel)
139                    .await;
140            }
141        }
142
143        let user = compose_message(&request);
144        let chat = ChatRequest {
145            model,
146            messages: vec![
147                ChatMessage::system(self.system_prompt.clone()),
148                ChatMessage::user(user),
149            ],
150            temperature: None,
151            extra: self.extra_body.clone(),
152        };
153
154        // Try keys in order, rotating to the next on a rate-limit/quota error.
155        let mut last_err = None;
156        let mut resp = None;
157        for (i, key) in self.keys.iter().enumerate() {
158            let client = OpenAiClient::new(&self.base_url, Some(key.clone()));
159            match client.chat_stream(&chat, &events, &cancel).await {
160                Ok(r) => {
161                    resp = Some(r);
162                    break;
163                }
164                Err(e) => {
165                    let rotate = is_rate_limited(&e) && i + 1 < self.keys.len();
166                    if rotate {
167                        rinne_core::worker::emit(
168                            &events,
169                            rinne_core::worker::WorkerEvent::Message(format!(
170                                "key {} rate-limited — rotating to key {}",
171                                i + 1,
172                                i + 2
173                            )),
174                        );
175                        last_err = Some(e);
176                        continue;
177                    }
178                    return Err(e);
179                }
180            }
181        }
182        let resp = match resp {
183            Some(r) => r,
184            None => {
185                return Err(last_err.unwrap_or_else(|| {
186                    rinne_core::RinneError::Worker("no API key available".into())
187                }))
188            }
189        };
190
191        let status = if cancel.is_cancelled() {
192            ExecStatus::Cancelled
193        } else {
194            ExecStatus::Success
195        };
196
197        let mut usage = resp.usage;
198        usage.wall_ms = started.elapsed().as_millis() as u64;
199
200        Ok(ExecuteResult {
201            result: resp.content.clone(),
202            file_diff: None,
203            transcript: resp.content,
204            status,
205            usage,
206            session_id: None,
207        })
208    }
209}
210
211/// The largest number of model↔tool round-trips before the loop gives up and
212/// returns whatever it has. A backstop against a model that never stops calling.
213const MAX_TOOL_ROUNDS: usize = 8;
214
215impl OpenAiWorker {
216    /// The host agentic loop: offer the node's tools, execute the model's tool
217    /// calls against the live MCP pool, feed results back, repeat until the model
218    /// answers in text or the round cap is hit (`MCP_SKILLS.md` §6).
219    async fn run_tool_loop(
220        &self,
221        request: &ExecuteRequest,
222        model: String,
223        executor: Arc<dyn ToolExecutor>,
224        events: &EventSink,
225        cancel: &CancellationToken,
226    ) -> Result<ExecuteResult> {
227        let started = Instant::now();
228        let mut messages = vec![
229            ChatMessage::system(self.system_prompt.clone()),
230            ChatMessage::user(compose_message(request)),
231        ];
232        let mut usage = Usage::default();
233        let mut transcript = String::new();
234        let mut answer = String::new();
235        let mut answered = false;
236
237        for _ in 0..MAX_TOOL_ROUNDS {
238            if cancel.is_cancelled() {
239                break;
240            }
241            let chat = ChatRequest {
242                model: model.clone(),
243                messages: messages.clone(),
244                temperature: None,
245                extra: self.extra_body.clone(),
246            };
247            let turn = self
248                .chat_tools_rotating(&chat, &request.tools, events)
249                .await?;
250            usage.prompt_tokens += turn.usage.prompt_tokens;
251            usage.completion_tokens += turn.usage.completion_tokens;
252
253            if turn.tool_calls.is_empty() {
254                // The model answered — done.
255                answer = turn.content;
256                answered = true;
257                if !answer.is_empty() {
258                    emit(events, WorkerEvent::Token(answer.clone()));
259                }
260                transcript.push_str(&answer);
261                break;
262            }
263
264            // Echo the assistant's tool calls, then run each and feed results back.
265            messages.push(ChatMessage::assistant_tool_calls(turn.tool_calls.clone()));
266            for call in &turn.tool_calls {
267                emit(
268                    events,
269                    WorkerEvent::ToolUse(format!(
270                        "{}({})",
271                        call.function.name,
272                        truncate(&call.function.arguments, 120)
273                    )),
274                );
275                transcript.push_str(&format!(
276                    "\n[tool] {} {}\n",
277                    call.function.name, call.function.arguments
278                ));
279                // Empty args are valid (a no-arg tool); only non-empty garbage is
280                // an error we hand back so the model can retry with valid JSON.
281                let trimmed = call.function.arguments.trim();
282                let result = if trimmed.is_empty() {
283                    executor
284                        .call(
285                            &call.function.name,
286                            serde_json::Value::Object(Default::default()),
287                        )
288                        .await
289                        .unwrap_or_else(|e| format!("tool error: {e}"))
290                } else {
291                    match serde_json::from_str::<serde_json::Value>(trimmed) {
292                        Ok(args) => executor
293                            .call(&call.function.name, args)
294                            .await
295                            .unwrap_or_else(|e| format!("tool error: {e}")),
296                        Err(e) => format!("tool error: arguments were not valid JSON ({e})"),
297                    }
298                };
299                transcript.push_str(&format!("[result] {}\n", truncate(&result, 400)));
300                messages.push(ChatMessage::tool_result(call.id.clone(), result));
301            }
302        }
303
304        emit(events, WorkerEvent::Done);
305        usage.wall_ms = started.elapsed().as_millis() as u64;
306        // A loop that ran out of rounds still calling tools never converged —
307        // fail it cleanly (the engine can loop back / replan) rather than report
308        // an empty success that silently starves downstream nodes.
309        let status = if cancel.is_cancelled() {
310            ExecStatus::Cancelled
311        } else if !answered {
312            emit(
313                events,
314                WorkerEvent::Message(format!(
315                    "tool loop hit the {MAX_TOOL_ROUNDS}-round limit without a final answer"
316                )),
317            );
318            ExecStatus::Failed(format!(
319                "model did not finish within {MAX_TOOL_ROUNDS} tool rounds"
320            ))
321        } else {
322            ExecStatus::Success
323        };
324        Ok(ExecuteResult {
325            result: answer,
326            file_diff: None,
327            transcript,
328            status,
329            usage,
330            session_id: None,
331        })
332    }
333
334    /// One non-streaming tool-aware completion, rotating keys on a rate-limit
335    /// just like the streaming path.
336    async fn chat_tools_rotating(
337        &self,
338        chat: &ChatRequest,
339        tools: &[rinne_core::worker::ToolSpec],
340        events: &EventSink,
341    ) -> Result<ChatTurn> {
342        let mut last_err = None;
343        for (i, key) in self.keys.iter().enumerate() {
344            let client = OpenAiClient::new(&self.base_url, Some(key.clone()));
345            match client.chat_with_tools(chat, tools).await {
346                Ok(turn) => return Ok(turn),
347                Err(e) => {
348                    if is_rate_limited(&e) && i + 1 < self.keys.len() {
349                        emit(
350                            events,
351                            WorkerEvent::Message(format!(
352                                "key {} rate-limited — rotating to key {}",
353                                i + 1,
354                                i + 2
355                            )),
356                        );
357                        last_err = Some(e);
358                        continue;
359                    }
360                    return Err(e);
361                }
362            }
363        }
364        Err(last_err.unwrap_or_else(|| RinneError::Worker("no API key available".into())))
365    }
366}
367
368/// Shorten a string for an event line / transcript, marking elision.
369fn truncate(s: &str, max: usize) -> String {
370    let one_line = s.replace('\n', " ");
371    if one_line.chars().count() > max {
372        let kept: String = one_line.chars().take(max).collect();
373        format!("{kept}…")
374    } else {
375        one_line
376    }
377}
378
379/// Inline the full context an API worker needs: instruction, file contents,
380/// prior context, critique, and steering.
381fn compose_message(request: &ExecuteRequest) -> String {
382    let mut out = String::new();
383    out.push_str(&request.instruction);
384
385    if !request.context.skill_text.is_empty() {
386        out.push_str("\n\n");
387        out.push_str(&request.context.skill_text);
388    }
389
390    if !request.context.prior_context.is_empty() {
391        out.push_str("\n\n## Context\n");
392        out.push_str(&request.context.prior_context);
393    }
394
395    if let Some(critique) = &request.context.critique {
396        out.push_str("\n\n## Address this feedback from the previous attempt\n");
397        out.push_str(critique);
398    }
399
400    if let Some(steer) = &request.constraints.steer {
401        out.push_str("\n\n## Steering\n");
402        out.push_str(steer);
403    }
404
405    for file in &request.context.inlined_files {
406        out.push_str("\n\n## File: ");
407        out.push_str(&file.path.display().to_string());
408        out.push_str("\n```\n");
409        out.push_str(&file.contents);
410        out.push_str("\n```\n");
411    }
412
413    out.push_str(&render_symbol_map(&request.context.symbol_map));
414
415    out
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421    use rinne_core::worker::{Constraints, ContextPacket, Role};
422    use std::path::PathBuf;
423
424    fn req(instruction: &str) -> ExecuteRequest {
425        ExecuteRequest {
426            role: Role::Generator,
427            instruction: instruction.into(),
428            context: ContextPacket::default(),
429            workspace: PathBuf::from("/tmp"),
430            constraints: Constraints::default(),
431            tools: Vec::new(),
432            mcp_servers: Vec::new(),
433        }
434    }
435
436    #[test]
437    fn symbol_map_is_rendered_into_api_message() {
438        use rinne_types::graph::{Neighborhood, SymbolRef};
439        let nb = Neighborhood {
440            definition: SymbolRef {
441                name: "helper".into(),
442                file: "m.rs".into(),
443                line: 1,
444                end_line: 1,
445            },
446            callers: vec![SymbolRef {
447                name: "main".into(),
448                file: "main.rs".into(),
449                line: 5,
450                end_line: 5,
451            }],
452            callees: vec![],
453            imports: vec![],
454            stale: false,
455        };
456        let mut r = req("do the task");
457        r.context.symbol_map = vec![nb];
458        let msg = compose_message(&r);
459        assert!(
460            msg.contains("## Relevant code structure"),
461            "section header missing"
462        );
463        assert!(msg.contains("helper"), "definition name missing");
464        assert!(msg.contains("m.rs:1"), "definition file:line missing");
465        assert!(msg.contains("main"), "caller name missing");
466    }
467}