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