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::time::Instant;
8
9use async_trait::async_trait;
10use tokio_util::sync::CancellationToken;
11
12use rinne_core::worker::{
13    AuthMode, Capability, EventSink, ExecStatus, ExecuteRequest, ExecuteResult, LatencyProfile,
14    QuotaModel, Transport, Worker, WorkerDescriptor, WorkerFamily,
15};
16use rinne_core::Result;
17
18use crate::transport::http::{ChatMessage, ChatRequest, OpenAiClient};
19
20/// An API worker backed by an OpenAI-compatible endpoint, with an optional pool
21/// of keys it rotates across when one is rate-limited (`CONTEXT.md` §13).
22pub struct OpenAiWorker {
23    descriptor: WorkerDescriptor,
24    base_url: String,
25    /// Key pool; rotated on rate-limit. The user's own keys, never pooled across
26    /// users (`CONTEXT.md` §4).
27    keys: Vec<String>,
28    /// Default model when a node doesn't pin one.
29    default_model: String,
30    system_prompt: String,
31    /// Provider-specific params merged into each request.
32    extra_body: Option<serde_json::Value>,
33}
34
35impl OpenAiWorker {
36    /// Build an API worker.
37    ///
38    /// `name` is the Rinne worker name (e.g. `openrouter`, `deepseek`).
39    /// `base_url` includes the version (e.g. `https://api.openai.com/v1`).
40    /// `keys` is the user's key pool (rotated on rate-limit). `models` is the
41    /// ladder cheap→strong; the first is the default. The per-node model
42    /// (conductor's choice or a cascade escalation) overrides the default.
43    pub fn new(
44        name: &str,
45        base_url: &str,
46        keys: Vec<String>,
47        models: Vec<String>,
48        capabilities: Vec<Capability>,
49        extra_body: Option<serde_json::Value>,
50    ) -> Self {
51        let default_model = models.first().cloned().unwrap_or_else(|| "gpt-4o-mini".to_string());
52        Self {
53            extra_body,
54            descriptor: WorkerDescriptor {
55                name: name.to_string(),
56                family: WorkerFamily::Api,
57                capabilities,
58                auth_mode: AuthMode::ApiKey,
59                quota: QuotaModel::unlimited(),
60                latency: LatencyProfile::Fast,
61                transport: Transport::Http,
62                models,
63            },
64            base_url: base_url.to_string(),
65            keys: if keys.is_empty() { vec![String::new()] } else { keys },
66            default_model,
67            system_prompt: "You are a focused worker inside an orchestration system. \
68                Follow the instruction precisely and return only the requested result."
69                .to_string(),
70        }
71    }
72}
73
74/// Whether an error looks like a rate-limit/quota condition worth rotating keys.
75fn is_rate_limited(err: &rinne_core::RinneError) -> bool {
76    let s = err.to_string().to_lowercase();
77    s.contains("429") || s.contains("rate limit") || s.contains("quota") || s.contains("too many requests")
78}
79
80#[async_trait]
81impl Worker for OpenAiWorker {
82    fn descriptor(&self) -> &WorkerDescriptor {
83        &self.descriptor
84    }
85
86    async fn execute(
87        &self,
88        request: ExecuteRequest,
89        events: EventSink,
90        cancel: CancellationToken,
91    ) -> Result<ExecuteResult> {
92        let started = Instant::now();
93        let user = compose_message(&request);
94
95        // The per-node model (conductor's tier choice or a cascade escalation)
96        // wins; otherwise the worker's default model.
97        let model = request
98            .constraints
99            .model
100            .clone()
101            .unwrap_or_else(|| self.default_model.clone());
102
103        let chat = ChatRequest {
104            model,
105            messages: vec![
106                ChatMessage::system(self.system_prompt.clone()),
107                ChatMessage::user(user),
108            ],
109            temperature: None,
110            extra: self.extra_body.clone(),
111        };
112
113        // Try keys in order, rotating to the next on a rate-limit/quota error.
114        let mut last_err = None;
115        let mut resp = None;
116        for (i, key) in self.keys.iter().enumerate() {
117            let client = OpenAiClient::new(&self.base_url, Some(key.clone()));
118            match client.chat_stream(&chat, &events, &cancel).await {
119                Ok(r) => {
120                    resp = Some(r);
121                    break;
122                }
123                Err(e) => {
124                    let rotate = is_rate_limited(&e) && i + 1 < self.keys.len();
125                    if rotate {
126                        rinne_core::worker::emit(
127                            &events,
128                            rinne_core::worker::WorkerEvent::Message(format!(
129                                "key {} rate-limited — rotating to key {}",
130                                i + 1,
131                                i + 2
132                            )),
133                        );
134                        last_err = Some(e);
135                        continue;
136                    }
137                    return Err(e);
138                }
139            }
140        }
141        let resp = match resp {
142            Some(r) => r,
143            None => return Err(last_err.unwrap_or_else(|| {
144                rinne_core::RinneError::Worker("no API key available".into())
145            })),
146        };
147
148        let status = if cancel.is_cancelled() {
149            ExecStatus::Cancelled
150        } else {
151            ExecStatus::Success
152        };
153
154        let mut usage = resp.usage;
155        usage.wall_ms = started.elapsed().as_millis() as u64;
156
157        Ok(ExecuteResult {
158            result: resp.content.clone(),
159            file_diff: None,
160            transcript: resp.content,
161            status,
162            usage,
163            session_id: None,
164        })
165    }
166}
167
168/// Inline the full context an API worker needs: instruction, file contents,
169/// prior context, critique, and steering.
170fn compose_message(request: &ExecuteRequest) -> String {
171    let mut out = String::new();
172    out.push_str(&request.instruction);
173
174    if !request.context.prior_context.is_empty() {
175        out.push_str("\n\n## Context\n");
176        out.push_str(&request.context.prior_context);
177    }
178
179    if let Some(critique) = &request.context.critique {
180        out.push_str("\n\n## Address this feedback from the previous attempt\n");
181        out.push_str(critique);
182    }
183
184    if let Some(steer) = &request.constraints.steer {
185        out.push_str("\n\n## Steering\n");
186        out.push_str(steer);
187    }
188
189    for file in &request.context.inlined_files {
190        out.push_str("\n\n## File: ");
191        out.push_str(&file.path.display().to_string());
192        out.push_str("\n```\n");
193        out.push_str(&file.contents);
194        out.push_str("\n```\n");
195    }
196
197    out
198}