mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-12-01 01:05:10 +08:00
feat: initialize server structure and database schema
- Added initial server setup with Cargo.toml defining dependencies and project structure. - Created build.rs for generating protobuf bindings and validating wire contracts. - Established database schema with initial migration files for conversations, messages, and runs. - Introduced tools and prompts for Cursor functionality, enhancing user interaction capabilities.
This commit is contained in:
1 parent
d200b3791d
commit
44e2d8057a
206 files changed
+37923
-21
No files matched your search
@@ -0,0 +1,486 @@
|
||||
//! Implements the Anthropic provider adapter.
|
||||
use async_stream::try_stream;
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use eventsource_stream::Eventsource;
|
||||
use futures_util::StreamExt;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::{
|
||||
config::ProviderConfig,
|
||||
model::{ContentPart, ModelInvocation, ProjectedContent, ProjectedMessage, Role, Usage},
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
use super::{
|
||||
merge_extra_params,
|
||||
recorder::recorded_headers,
|
||||
retry::{send_with_retry, Attempt, RetryPolicy},
|
||||
CallRecorder, FinishReason, ModelEvent, Provider, ProviderStream,
|
||||
};
|
||||
|
||||
const DEFAULT_MAX_OUTPUT_TOKENS: u64 = 65_000;
|
||||
|
||||
pub struct AnthropicProvider {
|
||||
client: reqwest::Client,
|
||||
config: ProviderConfig,
|
||||
recorder: Option<CallRecorder>,
|
||||
}
|
||||
|
||||
impl AnthropicProvider {
|
||||
pub fn new(client: reqwest::Client, config: ProviderConfig) -> Self {
|
||||
Self {
|
||||
client,
|
||||
config,
|
||||
recorder: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_recorder(mut self, recorder: Option<CallRecorder>) -> Self {
|
||||
self.recorder = recorder;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Provider for AnthropicProvider {
|
||||
fn stream(
|
||||
&self,
|
||||
invocation: ModelInvocation,
|
||||
cancellation: tokio_util::sync::CancellationToken,
|
||||
) -> ProviderStream {
|
||||
let client = self.client.clone();
|
||||
let config = self.config.clone();
|
||||
let recorder = self.recorder.clone();
|
||||
Box::pin(try_stream! {
|
||||
let ModelInvocation { call_id, request, .. } = invocation;
|
||||
let mut messages = anthropic_messages(&request.history)?;
|
||||
mark_cache_breakpoint(&mut messages);
|
||||
let system = if request.prompt.instructions.is_empty() {
|
||||
Value::String(String::new())
|
||||
} else {
|
||||
json!([{
|
||||
"type": "text",
|
||||
"text": request.prompt.instructions,
|
||||
"cache_control": {"type": "ephemeral"}
|
||||
}])
|
||||
};
|
||||
let max_tokens = request.model.max_output_tokens.or(config.max_output_tokens)
|
||||
.unwrap_or(DEFAULT_MAX_OUTPUT_TOKENS);
|
||||
let mut body = json!({
|
||||
"model": request.model.model_id, "system": system, "messages": messages,
|
||||
"max_tokens": max_tokens, "stream": true
|
||||
});
|
||||
if !request.prompt.tools.is_empty() {
|
||||
let tool_count = request.prompt.tools.len();
|
||||
body["tools"] = json!(request.prompt.tools.iter().enumerate().map(|(index, tool)| {
|
||||
let mut value = json!({
|
||||
"name": tool.name, "description": tool.description, "input_schema": tool.parameters
|
||||
});
|
||||
if index + 1 == tool_count {
|
||||
value["cache_control"] = json!({"type": "ephemeral"});
|
||||
}
|
||||
value
|
||||
}).collect::<Vec<_>>());
|
||||
}
|
||||
apply_model(&mut body, &request.model)?;
|
||||
merge_extra_params(&mut body, &request.model.extra_params)?;
|
||||
let request_headers = recorded_headers(
|
||||
&config,
|
||||
&[("content-type", "application/json"), ("anthropic-version", "2023-06-01")],
|
||||
);
|
||||
if let Some(recorder) = &recorder {
|
||||
recorder.request(request_headers.clone(), &body).await?;
|
||||
}
|
||||
let attempt = send_with_retry(
|
||||
"Anthropic",
|
||||
|| client.post(&config.request_url)
|
||||
.header("x-api-key", &config.api_key).header("anthropic-version", "2023-06-01")
|
||||
.headers(config.custom_headers.clone())
|
||||
.json(&body),
|
||||
RetryPolicy::default(),
|
||||
&cancellation,
|
||||
recorder.as_ref(),
|
||||
request_headers,
|
||||
&body,
|
||||
).await?;
|
||||
let Attempt::Response(response) = attempt else { return };
|
||||
yield ModelEvent::Start { model_call_id: call_id };
|
||||
let chunk_recorder = recorder.clone();
|
||||
let chunks = response.bytes_stream()
|
||||
.map(|chunk| chunk.map_err(Error::from))
|
||||
.then(move |chunk| {
|
||||
let recorder = chunk_recorder.clone();
|
||||
async move {
|
||||
let chunk = chunk?;
|
||||
if let Some(recorder) = recorder { recorder.response_chunk(&chunk).await?; }
|
||||
Ok::<_, Error>(chunk)
|
||||
}
|
||||
});
|
||||
let source = chunks.eventsource();
|
||||
futures_util::pin_mut!(source);
|
||||
let mut block_types = std::collections::BTreeMap::<usize, String>::new();
|
||||
let mut thinking_text = std::collections::HashMap::<usize, String>::new();
|
||||
let mut thinking_signatures = std::collections::HashMap::<usize, String>::new();
|
||||
let mut thinking_blocks = Vec::new();
|
||||
let mut finish = None;
|
||||
let mut saw_tool = false;
|
||||
let mut terminal = false;
|
||||
let mut final_usage = None::<Usage>;
|
||||
while let Some(event) = tokio::select! {
|
||||
_ = cancellation.cancelled() => { return; }
|
||||
event = source.next() => event,
|
||||
} {
|
||||
let event = event.map_err(|error| Error::Provider(format!("Anthropic SSE: {error}")))?;
|
||||
let value: Value = serde_json::from_str(&event.data)?;
|
||||
let data_kind = value.get("type").and_then(Value::as_str);
|
||||
let kind = match event.event.as_str() {
|
||||
"" | "message" => data_kind.unwrap_or(event.event.as_str()),
|
||||
kind => kind,
|
||||
};
|
||||
match kind {
|
||||
"message_start" => if let Some(usage) = value.pointer("/message/usage") {
|
||||
merge_usage(final_usage.get_or_insert_default(), anthropic_usage(usage));
|
||||
},
|
||||
"content_block_start" => {
|
||||
let index = required_u64(&value, "index")? as usize;
|
||||
let block = value.get("content_block").unwrap_or(&Value::Null);
|
||||
let kind = required_string(block, "type")?;
|
||||
block_types.insert(index, kind.into());
|
||||
match kind {
|
||||
"text" => yield ModelEvent::TextStart,
|
||||
"thinking" => {
|
||||
thinking_text.insert(index, String::new());
|
||||
thinking_signatures.insert(index, String::new());
|
||||
yield ModelEvent::ThinkingStart;
|
||||
}
|
||||
"redacted_thinking" => thinking_blocks.push(block.clone()),
|
||||
"tool_use" => {
|
||||
saw_tool = true;
|
||||
yield ModelEvent::ToolCallStart {
|
||||
index,
|
||||
call_id: required_string(block, "id")?.into(),
|
||||
name: required_string(block, "name")?.into(),
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
"content_block_delta" => {
|
||||
let index = required_u64(&value, "index")? as usize;
|
||||
let delta = value.get("delta").unwrap_or(&Value::Null);
|
||||
let delta_kind = required_string(delta, "type")?;
|
||||
if let std::collections::btree_map::Entry::Vacant(entry) = block_types.entry(index) {
|
||||
match delta_kind {
|
||||
"text_delta" => {
|
||||
entry.insert("text".into());
|
||||
yield ModelEvent::TextStart;
|
||||
}
|
||||
"thinking_delta" | "signature_delta" => {
|
||||
entry.insert("thinking".into());
|
||||
thinking_text.insert(index, String::new());
|
||||
thinking_signatures.insert(index, String::new());
|
||||
yield ModelEvent::ThinkingStart;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
match delta_kind {
|
||||
"text_delta" => if let Some(text) = delta.get("text").and_then(Value::as_str) { yield ModelEvent::TextDelta(text.into()); },
|
||||
"thinking_delta" => if let Some(text) = delta.get("thinking").and_then(Value::as_str) {
|
||||
thinking_text.entry(index).or_default().push_str(text);
|
||||
yield ModelEvent::ThinkingDelta(text.into());
|
||||
},
|
||||
"signature_delta" => if let Some(signature) = delta.get("signature").and_then(Value::as_str) {
|
||||
thinking_signatures.entry(index).or_default().push_str(signature);
|
||||
},
|
||||
"input_json_delta" => if let Some(text) = delta.get("partial_json").and_then(Value::as_str) { yield ModelEvent::ToolCallArgumentsDelta { index, delta: text.into() }; },
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
"content_block_stop" => {
|
||||
let index = required_u64(&value, "index")? as usize;
|
||||
if let Some(kind) = block_types.remove(&index) {
|
||||
for event in close_anthropic_block(index, &kind, &mut thinking_text, &mut thinking_signatures, &mut thinking_blocks) {
|
||||
yield event;
|
||||
}
|
||||
}
|
||||
}
|
||||
"message_delta" => {
|
||||
if let Some(usage) = value.get("usage") {
|
||||
merge_usage(final_usage.get_or_insert_default(), anthropic_usage(usage));
|
||||
}
|
||||
finish = match value.pointer("/delta/stop_reason").and_then(Value::as_str) {
|
||||
Some("tool_use") => Some(FinishReason::ToolUse),
|
||||
Some("max_tokens" | "model_context_window_exceeded") => Some(FinishReason::Length),
|
||||
Some("end_turn" | "stop_sequence" | "pause_turn" | "refusal") => Some(FinishReason::Stop),
|
||||
None => finish,
|
||||
Some(_) => Some(if saw_tool { FinishReason::ToolUse } else { FinishReason::Stop }),
|
||||
};
|
||||
}
|
||||
"message_stop" => {
|
||||
for (index, kind) in std::mem::take(&mut block_types) {
|
||||
for event in close_anthropic_block(index, &kind, &mut thinking_text, &mut thinking_signatures, &mut thinking_blocks) {
|
||||
yield event;
|
||||
}
|
||||
}
|
||||
terminal = true;
|
||||
if !thinking_blocks.is_empty() {
|
||||
yield ModelEvent::ProviderReplayState(
|
||||
crate::model::ProviderReplayState {
|
||||
provider_kind: "anthropic".into(),
|
||||
value: json!({"blocks": std::mem::take(&mut thinking_blocks)}),
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Some(usage) = final_usage {
|
||||
yield ModelEvent::Usage(usage);
|
||||
}
|
||||
let finish = match finish {
|
||||
Some(FinishReason::Length) => FinishReason::Length,
|
||||
_ if saw_tool => FinishReason::ToolUse,
|
||||
Some(finish) => finish,
|
||||
None => FinishReason::Stop,
|
||||
};
|
||||
yield ModelEvent::Done(finish);
|
||||
}
|
||||
"error" => Err(Error::Provider(format!("Anthropic stream error: {}", event.data)))?,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !terminal && finish.is_some() {
|
||||
for (index, kind) in std::mem::take(&mut block_types) {
|
||||
for event in close_anthropic_block(index, &kind, &mut thinking_text, &mut thinking_signatures, &mut thinking_blocks) {
|
||||
yield event;
|
||||
}
|
||||
}
|
||||
if !thinking_blocks.is_empty() {
|
||||
yield ModelEvent::ProviderReplayState(crate::model::ProviderReplayState {
|
||||
provider_kind: "anthropic".into(),
|
||||
value: json!({"blocks": std::mem::take(&mut thinking_blocks)}),
|
||||
});
|
||||
}
|
||||
if let Some(usage) = final_usage { yield ModelEvent::Usage(usage); }
|
||||
terminal = true;
|
||||
let finish = match finish {
|
||||
Some(FinishReason::Length) => FinishReason::Length,
|
||||
_ if saw_tool => FinishReason::ToolUse,
|
||||
Some(finish) => finish,
|
||||
None => FinishReason::Stop,
|
||||
};
|
||||
yield ModelEvent::Done(finish);
|
||||
}
|
||||
if !terminal {
|
||||
Err(Error::Provider("Anthropic stream ended without message_stop".into()))?;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn close_anthropic_block(
|
||||
index: usize,
|
||||
kind: &str,
|
||||
thinking_text: &mut std::collections::HashMap<usize, String>,
|
||||
thinking_signatures: &mut std::collections::HashMap<usize, String>,
|
||||
thinking_blocks: &mut Vec<Value>,
|
||||
) -> Vec<ModelEvent> {
|
||||
match kind {
|
||||
"text" => vec![ModelEvent::TextEnd],
|
||||
"thinking" => {
|
||||
let thinking = thinking_text.remove(&index).unwrap_or_default();
|
||||
let signature = thinking_signatures.remove(&index).unwrap_or_default();
|
||||
if !signature.is_empty() {
|
||||
thinking_blocks.push(json!({
|
||||
"type": "thinking",
|
||||
"thinking": thinking,
|
||||
"signature": signature,
|
||||
}));
|
||||
}
|
||||
vec![ModelEvent::ThinkingEnd]
|
||||
}
|
||||
"tool_use" => vec![ModelEvent::ToolCallEnd { index }],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_model(body: &mut Value, model: &crate::model::ModelSpec) -> Result<()> {
|
||||
let object = body
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| Error::Provider("Anthropic request body is not an object".into()))?;
|
||||
if model.reasoning.enabled {
|
||||
object.insert(
|
||||
"thinking".into(),
|
||||
json!({"type":"adaptive", "display":"summarized"}),
|
||||
);
|
||||
}
|
||||
if let Some(effort) = &model.reasoning.effort {
|
||||
object.insert("output_config".into(), json!({"effort":effort}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn merge_usage(total: &mut Usage, update: Usage) {
|
||||
merge_usage_field(&mut total.input_tokens, update.input_tokens);
|
||||
merge_usage_field(&mut total.output_tokens, update.output_tokens);
|
||||
merge_usage_field(&mut total.cache_read_tokens, update.cache_read_tokens);
|
||||
merge_usage_field(&mut total.cache_write_tokens, update.cache_write_tokens);
|
||||
merge_usage_field(&mut total.reasoning_tokens, update.reasoning_tokens);
|
||||
}
|
||||
|
||||
fn merge_usage_field(total: &mut Option<u64>, update: Option<u64>) {
|
||||
if let Some(update) = update {
|
||||
*total = Some(total.map_or(update, |current| current.max(update)));
|
||||
}
|
||||
}
|
||||
|
||||
fn anthropic_messages(messages: &[ProjectedMessage]) -> Result<Vec<Value>> {
|
||||
let mut output = Vec::new();
|
||||
for message in messages {
|
||||
match &message.content {
|
||||
ProjectedContent::Parts(parts) => {
|
||||
let content = anthropic_parts(&message.role, parts)?;
|
||||
if !content.is_empty() {
|
||||
push_anthropic(&mut output, role_name(&message.role), content);
|
||||
}
|
||||
}
|
||||
ProjectedContent::ToolResult(result) => {
|
||||
let content = if result.provider_parts.is_empty() {
|
||||
Value::String(result.content.clone())
|
||||
} else {
|
||||
Value::Array(anthropic_parts(&Role::User, &result.provider_parts)?)
|
||||
};
|
||||
push_anthropic(
|
||||
&mut output,
|
||||
"user",
|
||||
vec![json!({
|
||||
"type": "tool_result",
|
||||
"tool_use_id": result.call_id,
|
||||
"content": content,
|
||||
})],
|
||||
);
|
||||
}
|
||||
ProjectedContent::Assistant {
|
||||
text,
|
||||
replay_state,
|
||||
calls,
|
||||
..
|
||||
} => {
|
||||
let mut content = Vec::new();
|
||||
if let Some(blocks) = replay_state
|
||||
.as_ref()
|
||||
.filter(|state| state.provider_kind == "anthropic")
|
||||
.and_then(|state| state.value.get("blocks"))
|
||||
.and_then(Value::as_array)
|
||||
{
|
||||
content.extend(blocks.iter().cloned());
|
||||
}
|
||||
if !text.is_empty() {
|
||||
content.push(json!({"type": "text", "text": text}));
|
||||
}
|
||||
content.extend(calls.iter().map(|call| {
|
||||
json!({
|
||||
"type": "tool_use",
|
||||
"id": call.call_id,
|
||||
"name": call.name,
|
||||
"input": call.arguments,
|
||||
})
|
||||
}));
|
||||
if !content.is_empty() {
|
||||
push_anthropic(&mut output, "assistant", content);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn mark_cache_breakpoint(messages: &mut [Value]) {
|
||||
let Some(message) = messages
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|message| message.get("role").and_then(Value::as_str) == Some("user"))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(content) = message.get_mut("content").and_then(Value::as_array_mut) else {
|
||||
return;
|
||||
};
|
||||
for block in content.iter_mut().rev() {
|
||||
let kind = block.get("type").and_then(Value::as_str);
|
||||
if !matches!(kind, Some("text" | "image" | "tool_result")) {
|
||||
continue;
|
||||
}
|
||||
if let Some(block) = block.as_object_mut() {
|
||||
block.insert("cache_control".into(), json!({"type": "ephemeral"}));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn anthropic_parts(role: &Role, parts: &[ContentPart]) -> Result<Vec<Value>> {
|
||||
parts
|
||||
.iter()
|
||||
.filter_map(|part| match part {
|
||||
ContentPart::Text { text } if text.is_empty() => None,
|
||||
ContentPart::Text { text } => Some(Ok(json!({"type":"text", "text":text}))),
|
||||
ContentPart::Image { mime_type, data } if *role == Role::User => Some(Ok(json!({
|
||||
"type":"image",
|
||||
"source":{
|
||||
"type":"base64",
|
||||
"media_type":mime_type,
|
||||
"data":STANDARD.encode(data),
|
||||
},
|
||||
}))),
|
||||
ContentPart::Image { .. } => Some(Err(Error::Protocol(
|
||||
"Anthropic only accepts images in user messages".into(),
|
||||
))),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn push_anthropic(output: &mut Vec<Value>, role: &str, mut content: Vec<Value>) {
|
||||
if let Some(last) = output
|
||||
.last_mut()
|
||||
.filter(|last| last.get("role").and_then(Value::as_str) == Some(role))
|
||||
{
|
||||
if let Some(existing) = last.get_mut("content").and_then(Value::as_array_mut) {
|
||||
existing.append(&mut content);
|
||||
return;
|
||||
}
|
||||
}
|
||||
output.push(json!({"role":role, "content":content}));
|
||||
}
|
||||
|
||||
fn role_name(role: &Role) -> &'static str {
|
||||
match role {
|
||||
Role::System => "user",
|
||||
Role::User => "user",
|
||||
Role::Assistant => "assistant",
|
||||
Role::Tool => "user",
|
||||
}
|
||||
}
|
||||
|
||||
fn required_string<'a>(value: &'a Value, name: &str) -> Result<&'a str> {
|
||||
value
|
||||
.get(name)
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| Error::Provider(format!("Anthropic event is missing {name}")))
|
||||
}
|
||||
|
||||
fn required_u64(value: &Value, name: &str) -> Result<u64> {
|
||||
value
|
||||
.get(name)
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or_else(|| Error::Provider(format!("Anthropic event is missing {name}")))
|
||||
}
|
||||
|
||||
fn anthropic_usage(value: &Value) -> Usage {
|
||||
Usage {
|
||||
input_tokens: value.get("input_tokens").and_then(Value::as_u64),
|
||||
output_tokens: value.get("output_tokens").and_then(Value::as_u64),
|
||||
total_tokens: value.get("total_tokens").and_then(Value::as_u64),
|
||||
cache_read_tokens: value.get("cache_read_input_tokens").and_then(Value::as_u64),
|
||||
cache_write_tokens: value
|
||||
.get("cache_creation_input_tokens")
|
||||
.and_then(Value::as_u64),
|
||||
reasoning_tokens: None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Defines normalized provider streaming events.
|
||||
use crate::model::{ProviderReplayState, Usage};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum FinishReason {
|
||||
Stop,
|
||||
Length,
|
||||
ToolUse,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ModelEvent {
|
||||
Start {
|
||||
model_call_id: String,
|
||||
},
|
||||
TextStart,
|
||||
TextDelta(String),
|
||||
TextEnd,
|
||||
ThinkingStart,
|
||||
ThinkingDelta(String),
|
||||
ThinkingEnd,
|
||||
ToolCallStart {
|
||||
index: usize,
|
||||
call_id: String,
|
||||
name: String,
|
||||
},
|
||||
ToolCallArgumentsDelta {
|
||||
index: usize,
|
||||
delta: String,
|
||||
},
|
||||
ToolCallEnd {
|
||||
index: usize,
|
||||
},
|
||||
ProviderReplayState(ProviderReplayState),
|
||||
Usage(Usage),
|
||||
Done(FinishReason),
|
||||
}
|
||||
|
||||
/// Returns whether an event represents the first valid upstream response.
|
||||
/// Transport markers, replay metadata, usage, completion, and provider heartbeats
|
||||
/// are intentionally excluded; empty text/reasoning/tool deltas are valid events.
|
||||
pub fn is_valid_response_event(event: &ModelEvent) -> bool {
|
||||
matches!(
|
||||
event,
|
||||
ModelEvent::TextDelta(_)
|
||||
| ModelEvent::ThinkingStart
|
||||
| ModelEvent::ThinkingDelta(_)
|
||||
| ModelEvent::ThinkingEnd
|
||||
| ModelEvent::ToolCallStart { .. }
|
||||
| ModelEvent::ToolCallArgumentsDelta { .. }
|
||||
| ModelEvent::ToolCallEnd { .. }
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Defines the provider interface and exports provider implementations.
|
||||
mod anthropic;
|
||||
mod event;
|
||||
mod normalize;
|
||||
mod openai_chat;
|
||||
mod openai_responses;
|
||||
mod recorder;
|
||||
mod retry;
|
||||
mod router;
|
||||
|
||||
use std::pin::Pin;
|
||||
|
||||
use futures_util::Stream;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{model::ModelInvocation, Result};
|
||||
|
||||
pub use anthropic::AnthropicProvider;
|
||||
pub use event::*;
|
||||
pub use openai_chat::OpenAiChatProvider;
|
||||
pub use openai_responses::OpenAiResponsesProvider;
|
||||
pub use recorder::CallRecorder;
|
||||
pub use router::{build as build_provider, ProviderRouter};
|
||||
|
||||
pub type ProviderStream = Pin<Box<dyn Stream<Item = Result<ModelEvent>> + Send>>;
|
||||
|
||||
pub trait Provider: Send + Sync {
|
||||
fn stream(
|
||||
&self,
|
||||
invocation: ModelInvocation,
|
||||
cancellation: CancellationToken,
|
||||
) -> ProviderStream;
|
||||
}
|
||||
|
||||
fn merge_extra_params(body: &mut serde_json::Value, extra: &serde_json::Value) -> Result<()> {
|
||||
let extra = extra
|
||||
.as_object()
|
||||
.ok_or_else(|| crate::Error::Config("model extra params must be an object".into()))?;
|
||||
let body = body
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| crate::Error::Provider("provider request body must be an object".into()))?;
|
||||
for (name, value) in extra {
|
||||
if matches!(
|
||||
name.as_str(),
|
||||
"model"
|
||||
| "stream"
|
||||
| "messages"
|
||||
| "input"
|
||||
| "tools"
|
||||
| "system"
|
||||
| "instructions"
|
||||
| "prompt_cache_key"
|
||||
) {
|
||||
return Err(crate::Error::Config(format!(
|
||||
"model extra params cannot replace {name}"
|
||||
)));
|
||||
}
|
||||
body.insert(name.clone(), value.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_openai_prompt_cache_key(body: &mut serde_json::Value, model_id: &str) -> Result<()> {
|
||||
if !model_id.to_ascii_lowercase().contains("gpt") {
|
||||
return Ok(());
|
||||
}
|
||||
body.as_object_mut()
|
||||
.ok_or_else(|| crate::Error::Provider("provider request body must be an object".into()))?
|
||||
.insert(
|
||||
"prompt_cache_key".into(),
|
||||
serde_json::Value::String("cursor-byok".into()),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! Normalizes provider-specific responses.
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::model::{normalize_provider_tool_call_ids, ModelInvocation};
|
||||
|
||||
use super::{Provider, ProviderStream};
|
||||
|
||||
pub(super) struct NormalizedProvider {
|
||||
inner: Arc<dyn Provider>,
|
||||
}
|
||||
|
||||
impl NormalizedProvider {
|
||||
pub(super) fn new(inner: Arc<dyn Provider>) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
|
||||
impl Provider for NormalizedProvider {
|
||||
fn stream(
|
||||
&self,
|
||||
mut invocation: ModelInvocation,
|
||||
cancellation: CancellationToken,
|
||||
) -> ProviderStream {
|
||||
normalize_provider_tool_call_ids(&mut invocation.request.history);
|
||||
self.inner.stream(invocation, cancellation)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
//! Implements the OpenAI Chat Completions provider adapter.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use async_stream::try_stream;
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use eventsource_stream::Eventsource;
|
||||
use futures_util::StreamExt;
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::{
|
||||
config::ProviderConfig,
|
||||
model::{
|
||||
ContentPart, ModelInvocation, ModelLatency, ProjectedContent, ProjectedMessage, Role,
|
||||
ToolCallContent, Usage,
|
||||
},
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
use super::{
|
||||
apply_openai_prompt_cache_key, merge_extra_params,
|
||||
recorder::recorded_headers,
|
||||
retry::{send_with_retry, Attempt, RetryPolicy},
|
||||
CallRecorder, FinishReason, ModelEvent, Provider, ProviderStream,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
struct ChatToolState {
|
||||
call_id: String,
|
||||
name: String,
|
||||
arguments: String,
|
||||
emitted_arguments: usize,
|
||||
started: bool,
|
||||
}
|
||||
|
||||
pub struct OpenAiChatProvider {
|
||||
client: reqwest::Client,
|
||||
config: ProviderConfig,
|
||||
recorder: Option<CallRecorder>,
|
||||
}
|
||||
|
||||
impl OpenAiChatProvider {
|
||||
pub fn new(client: reqwest::Client, config: ProviderConfig) -> Self {
|
||||
Self {
|
||||
client,
|
||||
config,
|
||||
recorder: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_recorder(mut self, recorder: Option<CallRecorder>) -> Self {
|
||||
self.recorder = recorder;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Provider for OpenAiChatProvider {
|
||||
fn stream(
|
||||
&self,
|
||||
invocation: ModelInvocation,
|
||||
cancellation: tokio_util::sync::CancellationToken,
|
||||
) -> ProviderStream {
|
||||
let client = self.client.clone();
|
||||
let config = self.config.clone();
|
||||
let recorder = self.recorder.clone();
|
||||
Box::pin(try_stream! {
|
||||
let ModelInvocation { call_id, request, .. } = invocation;
|
||||
tracing::debug!(
|
||||
model = %request.model.model_id,
|
||||
call_id = %call_id,
|
||||
history_len = request.history.len(),
|
||||
tools_count = request.prompt.tools.len(),
|
||||
"OpenAI Chat provider stream started"
|
||||
);
|
||||
let messages = openai_chat_messages(&request.prompt.instructions, &request.history)?;
|
||||
let mut body = json!({
|
||||
"model": request.model.model_id,
|
||||
"messages": messages,
|
||||
"stream": true,
|
||||
"stream_options": {"include_usage": true}
|
||||
});
|
||||
if !request.prompt.tools.is_empty() {
|
||||
body["tools"] = json!(request.prompt.tools.iter().map(|tool| json!({"type":"function","function":{
|
||||
"name": tool.name, "description": tool.description, "parameters": tool.parameters
|
||||
}})).collect::<Vec<_>>());
|
||||
}
|
||||
apply_model(&mut body, &request.model, config.max_output_tokens)?;
|
||||
merge_extra_params(&mut body, &request.model.extra_params)?;
|
||||
apply_openai_prompt_cache_key(&mut body, &request.model.model_id)?;
|
||||
let request_headers = recorded_headers(&config, &[("content-type", "application/json")]);
|
||||
if let Some(recorder) = &recorder {
|
||||
recorder.request(request_headers.clone(), &body).await?;
|
||||
}
|
||||
let attempt = send_with_retry(
|
||||
"OpenAI Chat",
|
||||
|| client.post(&config.request_url)
|
||||
.bearer_auth(&config.api_key).headers(config.custom_headers.clone()).json(&body),
|
||||
RetryPolicy::default(),
|
||||
&cancellation,
|
||||
recorder.as_ref(),
|
||||
request_headers,
|
||||
&body,
|
||||
).await?;
|
||||
let Attempt::Response(response) = attempt else { return };
|
||||
yield ModelEvent::Start { model_call_id: call_id };
|
||||
let chunk_recorder = recorder.clone();
|
||||
let chunks = response.bytes_stream()
|
||||
.map(|chunk| chunk.map_err(Error::from))
|
||||
.then(move |chunk| {
|
||||
let recorder = chunk_recorder.clone();
|
||||
async move {
|
||||
let chunk = chunk?;
|
||||
if let Some(recorder) = recorder { recorder.response_chunk(&chunk).await?; }
|
||||
Ok::<_, Error>(chunk)
|
||||
}
|
||||
});
|
||||
let source = chunks.eventsource();
|
||||
futures_util::pin_mut!(source);
|
||||
let mut text_open = false;
|
||||
let mut thinking_open = false;
|
||||
let mut reasoning = String::new();
|
||||
let mut tools = BTreeMap::<usize, ChatToolState>::new();
|
||||
let mut final_usage = None;
|
||||
let mut finish = None;
|
||||
let mut saw_done_marker = false;
|
||||
let mut loop_iteration: u64 = 0;
|
||||
loop {
|
||||
loop_iteration += 1;
|
||||
let event = tokio::select! {
|
||||
_ = cancellation.cancelled() => {
|
||||
tracing::debug!(
|
||||
iteration = loop_iteration,
|
||||
saw_done_marker,
|
||||
tool_count = tools.len(),
|
||||
"OpenAI Chat stream cancelled"
|
||||
);
|
||||
return;
|
||||
}
|
||||
event = source.next() => event,
|
||||
};
|
||||
let Some(event) = event else {
|
||||
tracing::debug!(
|
||||
iteration = loop_iteration,
|
||||
saw_done_marker,
|
||||
"OpenAI Chat SSE stream ended"
|
||||
);
|
||||
break;
|
||||
};
|
||||
let event = event.map_err(|error| {
|
||||
let err_msg = error.to_string();
|
||||
tracing::debug!(iteration = loop_iteration, error = %error, "OpenAI Chat SSE event failed");
|
||||
Error::Provider(format!("OpenAI Chat SSE: {err_msg}"))
|
||||
})?;
|
||||
if event.data == "[DONE]" { saw_done_marker = true; break; }
|
||||
let value: Value = serde_json::from_str(&event.data)?;
|
||||
if let Some(usage) = value.get("usage").filter(|value| !value.is_null()) {
|
||||
final_usage = Some(openai_usage(usage));
|
||||
}
|
||||
let Some(choice) = value.get("choices").and_then(Value::as_array).and_then(|values| values.first()) else { continue; };
|
||||
let delta = choice.get("delta").unwrap_or(&Value::Null);
|
||||
if let Some(reasoning_delta) = delta.get("reasoning_content").or_else(|| delta.get("reasoning")).and_then(Value::as_str).filter(|text| !text.is_empty()) {
|
||||
if !thinking_open { thinking_open = true; yield ModelEvent::ThinkingStart; }
|
||||
reasoning.push_str(reasoning_delta);
|
||||
yield ModelEvent::ThinkingDelta(reasoning_delta.into());
|
||||
}
|
||||
if let Some(content) = delta.get("content").and_then(Value::as_str).filter(|text| !text.is_empty()) {
|
||||
if thinking_open { thinking_open = false; yield ModelEvent::ThinkingEnd; }
|
||||
if !text_open { text_open = true; yield ModelEvent::TextStart; }
|
||||
yield ModelEvent::TextDelta(content.into());
|
||||
}
|
||||
if let Some(tool_deltas) = delta.get("tool_calls").and_then(Value::as_array) {
|
||||
for (position, tool) in tool_deltas.iter().enumerate() {
|
||||
let index = tool.get("index").and_then(Value::as_u64).map_or(position, |index| index as usize);
|
||||
let id = tool.get("id").and_then(Value::as_str);
|
||||
let function = tool.get("function").unwrap_or(&Value::Null);
|
||||
let name = function.get("name").and_then(Value::as_str);
|
||||
let arguments = function.get("arguments").and_then(Value::as_str);
|
||||
for event in update_chat_tool(index, id, name, arguments, &mut tools) { yield event; }
|
||||
}
|
||||
}
|
||||
if let Some(reason) = choice.get("finish_reason").and_then(Value::as_str) {
|
||||
finish = Some(map_finish(reason, !tools.is_empty()));
|
||||
}
|
||||
}
|
||||
if thinking_open { yield ModelEvent::ThinkingEnd; }
|
||||
if text_open { yield ModelEvent::TextEnd; }
|
||||
for (index, tool) in &mut tools {
|
||||
if !tool.started {
|
||||
if tool.name.is_empty() {
|
||||
Err(Error::Provider("OpenAI Chat tool call is missing name".into()))?;
|
||||
}
|
||||
if tool.call_id.is_empty() {
|
||||
tool.call_id = format!("call-{index}");
|
||||
}
|
||||
tool.started = true;
|
||||
yield ModelEvent::ToolCallStart { index: *index, call_id: tool.call_id.clone(), name: tool.name.clone() };
|
||||
if !tool.arguments.is_empty() {
|
||||
tool.emitted_arguments = tool.arguments.len();
|
||||
yield ModelEvent::ToolCallArgumentsDelta { index: *index, delta: tool.arguments.clone() };
|
||||
}
|
||||
}
|
||||
yield ModelEvent::ToolCallEnd { index: *index };
|
||||
}
|
||||
if let Some(usage) = final_usage { yield ModelEvent::Usage(usage); }
|
||||
if !reasoning.is_empty() {
|
||||
yield ModelEvent::ProviderReplayState(crate::model::ProviderReplayState {
|
||||
provider_kind: "openai_chat".into(),
|
||||
value: json!({"reasoning_content": reasoning}),
|
||||
});
|
||||
}
|
||||
let finish = finish.or_else(|| saw_done_marker.then_some(if tools.is_empty() { FinishReason::Stop } else { FinishReason::ToolUse }))
|
||||
.ok_or_else(|| Error::Provider("OpenAI Chat stream ended without finish_reason".into()))?;
|
||||
yield ModelEvent::Done(finish);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_model(
|
||||
body: &mut Value,
|
||||
model: &crate::model::ModelSpec,
|
||||
route_max_output_tokens: Option<u64>,
|
||||
) -> Result<()> {
|
||||
let object = body
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| Error::Provider("OpenAI Chat request body is not an object".into()))?;
|
||||
if let Some(max) = model.max_output_tokens.or(route_max_output_tokens) {
|
||||
object.insert("max_completion_tokens".into(), json!(max));
|
||||
}
|
||||
if let Some(effort) = &model.reasoning.effort {
|
||||
object.insert("reasoning_effort".into(), json!(effort));
|
||||
}
|
||||
if model.latency == ModelLatency::Fast {
|
||||
object.insert("service_tier".into(), json!("fast"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn openai_chat_messages(instructions: &str, messages: &[ProjectedMessage]) -> Result<Vec<Value>> {
|
||||
let mut output = Vec::with_capacity(messages.len() + usize::from(!instructions.is_empty()));
|
||||
if !instructions.is_empty() {
|
||||
output.push(json!({"role": "system", "content": instructions}));
|
||||
}
|
||||
for message in messages {
|
||||
let mut value = Map::new();
|
||||
value.insert(
|
||||
"role".into(),
|
||||
Value::String(role_name(&message.role).into()),
|
||||
);
|
||||
match &message.content {
|
||||
ProjectedContent::Parts(parts) => {
|
||||
value.insert("content".into(), chat_content(&message.role, parts)?);
|
||||
}
|
||||
ProjectedContent::Assistant {
|
||||
text,
|
||||
replay_state,
|
||||
calls,
|
||||
..
|
||||
} => {
|
||||
let replay_reasoning = replay_state
|
||||
.as_ref()
|
||||
.filter(|state| state.provider_kind == "openai_chat")
|
||||
.and_then(|state| state.value.get("reasoning_content"))
|
||||
.and_then(Value::as_str)
|
||||
.filter(|reasoning| !reasoning.is_empty());
|
||||
|
||||
// Chat Completions rejects an empty assistant content string. Tool-call
|
||||
// assistant messages use null content, while an assistant with no visible
|
||||
// content at all does not need to be sent.
|
||||
if text.is_empty() && calls.is_empty() && replay_reasoning.is_none() {
|
||||
continue;
|
||||
}
|
||||
value.insert(
|
||||
"content".into(),
|
||||
if text.is_empty() {
|
||||
Value::Null
|
||||
} else {
|
||||
Value::String(text.clone())
|
||||
},
|
||||
);
|
||||
if let Some(reasoning) = replay_reasoning {
|
||||
value.insert("reasoning_content".into(), Value::String(reasoning.into()));
|
||||
}
|
||||
if !calls.is_empty() {
|
||||
value.insert(
|
||||
"tool_calls".into(),
|
||||
Value::Array(
|
||||
calls
|
||||
.iter()
|
||||
.map(openai_tool_call)
|
||||
.collect::<Result<Vec<_>>>()?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
ProjectedContent::ToolResult(result) => {
|
||||
value.insert(
|
||||
"content".into(),
|
||||
if result.provider_parts.is_empty() {
|
||||
Value::String(result.content.clone())
|
||||
} else {
|
||||
chat_content(&Role::User, &result.provider_parts)?
|
||||
},
|
||||
);
|
||||
value.insert("tool_call_id".into(), Value::String(result.call_id.clone()));
|
||||
}
|
||||
}
|
||||
output.push(Value::Object(value));
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn chat_content(_role: &Role, parts: &[ContentPart]) -> Result<Value> {
|
||||
let mut text = String::new();
|
||||
let mut only_text = true;
|
||||
for part in parts {
|
||||
match part {
|
||||
ContentPart::Text { text: part } => text.push_str(part),
|
||||
ContentPart::Image { .. } => {
|
||||
only_text = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if only_text {
|
||||
return Ok(Value::String(text));
|
||||
}
|
||||
Ok(Value::Array(
|
||||
parts
|
||||
.iter()
|
||||
.map(|part| match part {
|
||||
ContentPart::Text { text } => Ok(json!({"type":"text", "text":text})),
|
||||
ContentPart::Image { mime_type, data } => Ok(json!({
|
||||
"type":"image_url",
|
||||
"image_url":{"url":format!(
|
||||
"data:{mime_type};base64,{}",
|
||||
STANDARD.encode(data)
|
||||
)},
|
||||
})),
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?,
|
||||
))
|
||||
}
|
||||
|
||||
fn openai_tool_call(call: &ToolCallContent) -> Result<Value> {
|
||||
Ok(json!({
|
||||
"id": call.call_id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": call.name,
|
||||
"arguments": serde_json::to_string(&call.arguments)?,
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
fn role_name(role: &Role) -> &'static str {
|
||||
match role {
|
||||
Role::System => "system",
|
||||
Role::User => "user",
|
||||
Role::Assistant => "assistant",
|
||||
Role::Tool => "tool",
|
||||
}
|
||||
}
|
||||
|
||||
fn map_finish(value: &str, has_tools: bool) -> FinishReason {
|
||||
match value {
|
||||
"tool_calls" | "function_call" => FinishReason::ToolUse,
|
||||
"length" => FinishReason::Length,
|
||||
"stop" | "content_filter" => FinishReason::Stop,
|
||||
_ if has_tools => FinishReason::ToolUse,
|
||||
_ => FinishReason::Stop,
|
||||
}
|
||||
}
|
||||
|
||||
fn update_chat_tool(
|
||||
index: usize,
|
||||
call_id: Option<&str>,
|
||||
name: Option<&str>,
|
||||
arguments: Option<&str>,
|
||||
tools: &mut BTreeMap<usize, ChatToolState>,
|
||||
) -> Vec<ModelEvent> {
|
||||
let tool = tools.entry(index).or_default();
|
||||
if let Some(call_id) = call_id {
|
||||
merge_chat_fragment(&mut tool.call_id, call_id);
|
||||
}
|
||||
if let Some(name) = name {
|
||||
merge_chat_fragment(&mut tool.name, name);
|
||||
}
|
||||
if let Some(arguments) = arguments {
|
||||
tool.arguments.push_str(arguments);
|
||||
}
|
||||
|
||||
let mut events = Vec::new();
|
||||
if !tool.started && !tool.call_id.is_empty() && !tool.name.is_empty() {
|
||||
tool.started = true;
|
||||
events.push(ModelEvent::ToolCallStart {
|
||||
index,
|
||||
call_id: tool.call_id.clone(),
|
||||
name: tool.name.clone(),
|
||||
});
|
||||
}
|
||||
if tool.started && tool.emitted_arguments < tool.arguments.len() {
|
||||
let delta = tool.arguments[tool.emitted_arguments..].to_string();
|
||||
tool.emitted_arguments = tool.arguments.len();
|
||||
events.push(ModelEvent::ToolCallArgumentsDelta { index, delta });
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
fn merge_chat_fragment(target: &mut String, fragment: &str) {
|
||||
if target == fragment || target.ends_with(fragment) {
|
||||
return;
|
||||
}
|
||||
if fragment.starts_with(target.as_str()) {
|
||||
*target = fragment.into();
|
||||
} else {
|
||||
target.push_str(fragment);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn openai_usage(value: &Value) -> Usage {
|
||||
Usage {
|
||||
input_tokens: value.get("prompt_tokens").and_then(Value::as_u64),
|
||||
output_tokens: value.get("completion_tokens").and_then(Value::as_u64),
|
||||
total_tokens: value.get("total_tokens").and_then(Value::as_u64),
|
||||
cache_read_tokens: value
|
||||
.pointer("/prompt_tokens_details/cached_tokens")
|
||||
.and_then(Value::as_u64),
|
||||
cache_write_tokens: None,
|
||||
reasoning_tokens: value
|
||||
.pointer("/completion_tokens_details/reasoning_tokens")
|
||||
.and_then(Value::as_u64),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
//! Implements the OpenAI Responses provider adapter.
|
||||
use async_stream::try_stream;
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use eventsource_stream::Eventsource;
|
||||
use futures_util::StreamExt;
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::{
|
||||
config::ProviderConfig,
|
||||
model::{
|
||||
ContentPart, ModelInvocation, ModelLatency, ProjectedContent, ProjectedMessage, Role, Usage,
|
||||
},
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
use super::{
|
||||
apply_openai_prompt_cache_key, merge_extra_params,
|
||||
recorder::recorded_headers,
|
||||
retry::{send_with_retry, Attempt, RetryPolicy},
|
||||
CallRecorder, FinishReason, ModelEvent, Provider, ProviderStream,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
struct ResponseToolState {
|
||||
call_id: Option<String>,
|
||||
name: Option<String>,
|
||||
arguments: String,
|
||||
emitted_arguments: usize,
|
||||
started: bool,
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
enum ResponseToolArguments<'a> {
|
||||
None,
|
||||
Delta(&'a str),
|
||||
Snapshot(&'a str),
|
||||
}
|
||||
|
||||
pub struct OpenAiResponsesProvider {
|
||||
client: reqwest::Client,
|
||||
config: ProviderConfig,
|
||||
recorder: Option<CallRecorder>,
|
||||
}
|
||||
|
||||
impl OpenAiResponsesProvider {
|
||||
pub fn new(client: reqwest::Client, config: ProviderConfig) -> Self {
|
||||
Self {
|
||||
client,
|
||||
config,
|
||||
recorder: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_recorder(mut self, recorder: Option<CallRecorder>) -> Self {
|
||||
self.recorder = recorder;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Provider for OpenAiResponsesProvider {
|
||||
fn stream(
|
||||
&self,
|
||||
invocation: ModelInvocation,
|
||||
cancellation: tokio_util::sync::CancellationToken,
|
||||
) -> ProviderStream {
|
||||
let client = self.client.clone();
|
||||
let config = self.config.clone();
|
||||
let recorder = self.recorder.clone();
|
||||
Box::pin(try_stream! {
|
||||
let ModelInvocation { call_id, request, .. } = invocation;
|
||||
let input = responses_input(&request.history)?;
|
||||
let mut body = json!({
|
||||
"model": request.model.model_id, "input": input, "stream": true,
|
||||
"instructions": request.prompt.instructions,
|
||||
"include": ["reasoning.encrypted_content"]
|
||||
});
|
||||
if !request.prompt.tools.is_empty() {
|
||||
body["tools"] = json!(request.prompt.tools.iter().map(|tool| json!({
|
||||
"type":"function", "name":tool.name, "description":tool.description,
|
||||
"parameters":tool.parameters, "strict":false
|
||||
})).collect::<Vec<_>>());
|
||||
}
|
||||
apply_model(&mut body, &request.model, config.max_output_tokens)?;
|
||||
merge_extra_params(&mut body, &request.model.extra_params)?;
|
||||
apply_openai_prompt_cache_key(&mut body, &request.model.model_id)?;
|
||||
let request_headers = recorded_headers(&config, &[("content-type", "application/json")]);
|
||||
if let Some(recorder) = &recorder {
|
||||
recorder.request(request_headers.clone(), &body).await?;
|
||||
}
|
||||
let attempt = send_with_retry(
|
||||
"OpenAI Responses",
|
||||
|| client.post(&config.request_url)
|
||||
.bearer_auth(&config.api_key).headers(config.custom_headers.clone()).json(&body),
|
||||
RetryPolicy::default(),
|
||||
&cancellation,
|
||||
recorder.as_ref(),
|
||||
request_headers,
|
||||
&body,
|
||||
).await?;
|
||||
let Attempt::Response(response) = attempt else { return };
|
||||
yield ModelEvent::Start { model_call_id: call_id };
|
||||
let chunk_recorder = recorder.clone();
|
||||
let chunks = response.bytes_stream()
|
||||
.map(|chunk| chunk.map_err(Error::from))
|
||||
.then(move |chunk| {
|
||||
let recorder = chunk_recorder.clone();
|
||||
async move {
|
||||
let chunk = chunk?;
|
||||
if let Some(recorder) = recorder { recorder.response_chunk(&chunk).await?; }
|
||||
Ok::<_, Error>(chunk)
|
||||
}
|
||||
});
|
||||
let source = chunks.eventsource();
|
||||
futures_util::pin_mut!(source);
|
||||
let mut text_open = false;
|
||||
let mut text = String::new();
|
||||
let mut thinking_open = false;
|
||||
let mut tools = std::collections::BTreeMap::<usize, ResponseToolState>::new();
|
||||
let mut reasoning_items = Vec::new();
|
||||
let mut saw_tool = false;
|
||||
let mut saw_completed_item = false;
|
||||
let mut terminal = false;
|
||||
loop {
|
||||
let event = tokio::select! {
|
||||
_ = cancellation.cancelled() => { return; }
|
||||
event = source.next() => event,
|
||||
};
|
||||
let Some(event) = event else { break };
|
||||
let event = event.map_err(|error| Error::Provider(format!("OpenAI Responses SSE: {error}")))?;
|
||||
if event.data == "[DONE]" { break; }
|
||||
let value: Value = serde_json::from_str(&event.data)?;
|
||||
let kind = value.get("type").and_then(Value::as_str).unwrap_or(&event.event);
|
||||
match kind {
|
||||
"response.output_text.delta" => {
|
||||
if thinking_open { thinking_open = false; yield ModelEvent::ThinkingEnd; }
|
||||
if !text_open { text_open = true; yield ModelEvent::TextStart; }
|
||||
if let Some(delta) = value.get("delta").and_then(Value::as_str) {
|
||||
text.push_str(delta);
|
||||
yield ModelEvent::TextDelta(delta.into());
|
||||
}
|
||||
}
|
||||
"response.output_text.done" => {
|
||||
if let Some(final_text) = value.get("text").and_then(Value::as_str) {
|
||||
for event in reconcile_response_text(&mut text_open, &mut text, final_text) { yield event; }
|
||||
}
|
||||
if text_open { text_open = false; yield ModelEvent::TextEnd; }
|
||||
}
|
||||
"response.reasoning_summary_text.delta" | "response.reasoning_text.delta" => {
|
||||
if !thinking_open { thinking_open = true; yield ModelEvent::ThinkingStart; }
|
||||
if let Some(delta) = value.get("delta").and_then(Value::as_str) { yield ModelEvent::ThinkingDelta(delta.into()); }
|
||||
}
|
||||
"response.reasoning_summary_text.done" | "response.reasoning_text.done" => {
|
||||
if thinking_open { thinking_open = false; yield ModelEvent::ThinkingEnd; }
|
||||
}
|
||||
"response.output_item.added" => {
|
||||
let item = value.get("item").unwrap_or(&Value::Null);
|
||||
if item.get("type").and_then(Value::as_str) == Some("function_call") {
|
||||
let index = required_u64(&value, "output_index")? as usize;
|
||||
saw_tool = true;
|
||||
for event in update_response_tool(index, item, ResponseToolArguments::None, false, &mut tools)? { yield event; }
|
||||
}
|
||||
}
|
||||
"response.output_item.done" => {
|
||||
let item = value.get("item").unwrap_or(&Value::Null);
|
||||
match item.get("type").and_then(Value::as_str) {
|
||||
Some("reasoning") => {
|
||||
if thinking_open { thinking_open = false; yield ModelEvent::ThinkingEnd; }
|
||||
reasoning_items.push(item.clone());
|
||||
}
|
||||
Some("message") => {
|
||||
saw_completed_item = true;
|
||||
if let Some(final_text) = response_item_text(item) {
|
||||
for event in reconcile_response_text(&mut text_open, &mut text, &final_text) { yield event; }
|
||||
}
|
||||
if text_open { text_open = false; yield ModelEvent::TextEnd; }
|
||||
}
|
||||
Some("function_call") => {
|
||||
saw_completed_item = true;
|
||||
let index = required_u64(&value, "output_index")? as usize;
|
||||
saw_tool = true;
|
||||
let arguments = item
|
||||
.get("arguments")
|
||||
.and_then(Value::as_str)
|
||||
.map_or(ResponseToolArguments::None, ResponseToolArguments::Snapshot);
|
||||
for event in update_response_tool(index, item, arguments, true, &mut tools)? { yield event; }
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
"response.function_call_arguments.delta" => {
|
||||
let index = required_u64(&value, "output_index")? as usize;
|
||||
if let Some(delta) = value.get("delta").and_then(Value::as_str) {
|
||||
saw_tool = true;
|
||||
for event in update_response_tool(index, &Value::Null, ResponseToolArguments::Delta(delta), false, &mut tools)? { yield event; }
|
||||
}
|
||||
}
|
||||
"response.function_call_arguments.done" => {
|
||||
let index = required_u64(&value, "output_index")? as usize;
|
||||
match value.get("arguments").and_then(Value::as_str) {
|
||||
Some("") => {
|
||||
for event in update_response_tool(
|
||||
index,
|
||||
&Value::Null,
|
||||
ResponseToolArguments::None,
|
||||
false,
|
||||
&mut tools,
|
||||
)? { yield event; }
|
||||
}
|
||||
arguments => {
|
||||
let arguments = arguments.map_or(
|
||||
ResponseToolArguments::None,
|
||||
ResponseToolArguments::Snapshot,
|
||||
);
|
||||
for event in update_response_tool(index, &Value::Null, arguments, true, &mut tools)? { yield event; }
|
||||
}
|
||||
}
|
||||
}
|
||||
"response.completed" => {
|
||||
if let Some(usage) = value.pointer("/response/usage") { yield ModelEvent::Usage(responses_usage(usage)); }
|
||||
if thinking_open { thinking_open = false; yield ModelEvent::ThinkingEnd; }
|
||||
if text_open { text_open = false; yield ModelEvent::TextEnd; }
|
||||
for (index, tool) in tools.iter_mut().filter(|(_, tool)| tool.started && !tool.ended) {
|
||||
tool.ended = true;
|
||||
yield ModelEvent::ToolCallEnd { index: *index };
|
||||
}
|
||||
if tools.values().any(|tool| !tool.started) {
|
||||
Err(Error::Provider("OpenAI Responses completed with incomplete tool metadata".into()))?;
|
||||
}
|
||||
terminal = true;
|
||||
if !reasoning_items.is_empty() {
|
||||
yield ModelEvent::ProviderReplayState(
|
||||
crate::model::ProviderReplayState {
|
||||
provider_kind: "openai_responses".into(),
|
||||
value: json!({"items": std::mem::take(&mut reasoning_items)}),
|
||||
},
|
||||
);
|
||||
}
|
||||
yield ModelEvent::Done(if saw_tool { FinishReason::ToolUse } else { FinishReason::Stop });
|
||||
}
|
||||
"response.incomplete" => {
|
||||
if thinking_open { thinking_open = false; yield ModelEvent::ThinkingEnd; }
|
||||
if text_open { text_open = false; yield ModelEvent::TextEnd; }
|
||||
for (index, tool) in tools.iter_mut().filter(|(_, tool)| tool.started && !tool.ended) {
|
||||
tool.ended = true;
|
||||
yield ModelEvent::ToolCallEnd { index: *index };
|
||||
}
|
||||
terminal = true;
|
||||
yield ModelEvent::Done(FinishReason::Length);
|
||||
}
|
||||
"response.failed" => Err(Error::Provider(format!("OpenAI Responses failed: {}", event.data)))?,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !terminal && saw_completed_item {
|
||||
if thinking_open { yield ModelEvent::ThinkingEnd; }
|
||||
if text_open { yield ModelEvent::TextEnd; }
|
||||
if tools.values().any(|tool| !tool.ended) {
|
||||
Err(Error::Provider("OpenAI Responses stream ended with an incomplete tool call".into()))?;
|
||||
}
|
||||
terminal = true;
|
||||
if !reasoning_items.is_empty() {
|
||||
yield ModelEvent::ProviderReplayState(crate::model::ProviderReplayState {
|
||||
provider_kind: "openai_responses".into(),
|
||||
value: json!({"items": std::mem::take(&mut reasoning_items)}),
|
||||
});
|
||||
}
|
||||
yield ModelEvent::Done(if saw_tool { FinishReason::ToolUse } else { FinishReason::Stop });
|
||||
}
|
||||
if !terminal {
|
||||
Err(Error::Provider("OpenAI Responses stream ended without response.completed or response.incomplete".into()))?;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn response_item_text(item: &Value) -> Option<String> {
|
||||
let text = item
|
||||
.get("content")?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter(|part| part.get("type").and_then(Value::as_str) == Some("output_text"))
|
||||
.filter_map(|part| part.get("text").and_then(Value::as_str))
|
||||
.collect::<String>();
|
||||
Some(text)
|
||||
}
|
||||
|
||||
fn reconcile_response_text(
|
||||
open: &mut bool,
|
||||
streamed: &mut String,
|
||||
final_text: &str,
|
||||
) -> Vec<ModelEvent> {
|
||||
let mut events = Vec::new();
|
||||
if final_text.starts_with(streamed.as_str()) && final_text.len() > streamed.len() {
|
||||
if !*open {
|
||||
*open = true;
|
||||
events.push(ModelEvent::TextStart);
|
||||
}
|
||||
let suffix = &final_text[streamed.len()..];
|
||||
streamed.push_str(suffix);
|
||||
events.push(ModelEvent::TextDelta(suffix.into()));
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
fn update_response_tool(
|
||||
index: usize,
|
||||
item: &Value,
|
||||
arguments: ResponseToolArguments<'_>,
|
||||
done: bool,
|
||||
tools: &mut std::collections::BTreeMap<usize, ResponseToolState>,
|
||||
) -> Result<Vec<ModelEvent>> {
|
||||
let tool = tools.entry(index).or_default();
|
||||
if let Some(call_id) = item.get("call_id").and_then(Value::as_str) {
|
||||
tool.call_id.get_or_insert_with(|| call_id.into());
|
||||
}
|
||||
if let Some(name) = item.get("name").and_then(Value::as_str) {
|
||||
tool.name.get_or_insert_with(|| name.into());
|
||||
}
|
||||
match arguments {
|
||||
ResponseToolArguments::None => {}
|
||||
ResponseToolArguments::Delta(delta) => tool.arguments.push_str(delta),
|
||||
ResponseToolArguments::Snapshot(snapshot) if snapshot == tool.arguments => {}
|
||||
ResponseToolArguments::Snapshot(snapshot) if snapshot.starts_with(&tool.arguments) => {
|
||||
tool.arguments.push_str(&snapshot[tool.arguments.len()..]);
|
||||
}
|
||||
ResponseToolArguments::Snapshot(_) => {
|
||||
return Err(Error::Provider(
|
||||
"OpenAI Responses final tool arguments do not match streamed arguments".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let mut events = Vec::new();
|
||||
if !tool.started {
|
||||
if let (Some(call_id), Some(name)) = (&tool.call_id, &tool.name) {
|
||||
tool.started = true;
|
||||
events.push(ModelEvent::ToolCallStart {
|
||||
index,
|
||||
call_id: call_id.clone(),
|
||||
name: name.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
if tool.started && tool.emitted_arguments < tool.arguments.len() {
|
||||
let delta = tool.arguments[tool.emitted_arguments..].to_string();
|
||||
tool.emitted_arguments = tool.arguments.len();
|
||||
events.push(ModelEvent::ToolCallArgumentsDelta { index, delta });
|
||||
}
|
||||
if done && !tool.ended {
|
||||
if !tool.started {
|
||||
return Err(Error::Provider(
|
||||
"OpenAI Responses function call is missing call_id or name".into(),
|
||||
));
|
||||
}
|
||||
tool.ended = true;
|
||||
events.push(ModelEvent::ToolCallEnd { index });
|
||||
}
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
fn apply_model(
|
||||
body: &mut Value,
|
||||
model: &crate::model::ModelSpec,
|
||||
route_max_output_tokens: Option<u64>,
|
||||
) -> Result<()> {
|
||||
let object = body
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| Error::Provider("OpenAI Responses request body is not an object".into()))?;
|
||||
if let Some(max) = model.max_output_tokens.or(route_max_output_tokens) {
|
||||
object.insert("max_output_tokens".into(), json!(max));
|
||||
}
|
||||
if model.reasoning.enabled || model.reasoning.effort.is_some() {
|
||||
let mut reasoning = Map::new();
|
||||
reasoning.insert("summary".into(), json!("auto"));
|
||||
if let Some(effort) = &model.reasoning.effort {
|
||||
reasoning.insert("effort".into(), json!(effort));
|
||||
}
|
||||
object.insert("reasoning".into(), Value::Object(reasoning));
|
||||
}
|
||||
if model.latency == ModelLatency::Fast {
|
||||
object.insert("service_tier".into(), json!("fast"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn responses_input(messages: &[ProjectedMessage]) -> Result<Vec<Value>> {
|
||||
let mut input = Vec::new();
|
||||
for message in messages {
|
||||
match &message.content {
|
||||
ProjectedContent::Parts(parts) => {
|
||||
push_responses_parts(&mut input, &message.role, parts)?
|
||||
}
|
||||
ProjectedContent::ToolResult(result) => {
|
||||
let output = if result.provider_parts.is_empty() {
|
||||
Value::String(result.content.clone())
|
||||
} else {
|
||||
Value::Array(responses_content(&result.provider_parts, "input_text")?)
|
||||
};
|
||||
input.push(json!({
|
||||
"type": "function_call_output",
|
||||
"call_id": result.call_id,
|
||||
"output": output,
|
||||
}));
|
||||
}
|
||||
ProjectedContent::Assistant {
|
||||
text,
|
||||
replay_state,
|
||||
calls,
|
||||
..
|
||||
} => {
|
||||
if let Some(state) = replay_state
|
||||
.as_ref()
|
||||
.filter(|state| state.provider_kind == "openai_responses")
|
||||
{
|
||||
let items = state
|
||||
.value
|
||||
.get("items")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| {
|
||||
Error::Protocol("OpenAI Responses replay state is missing items".into())
|
||||
})?;
|
||||
input.extend(items.iter().cloned());
|
||||
}
|
||||
push_responses_text(&mut input, &message.role, text);
|
||||
for call in calls {
|
||||
input.push(json!({
|
||||
"type": "function_call",
|
||||
"call_id": call.call_id,
|
||||
"name": call.name,
|
||||
"arguments": serde_json::to_string(&call.arguments)?,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(input)
|
||||
}
|
||||
|
||||
fn push_responses_parts(input: &mut Vec<Value>, role: &Role, parts: &[ContentPart]) -> Result<()> {
|
||||
let text_type = if *role == Role::Assistant {
|
||||
"output_text"
|
||||
} else {
|
||||
"input_text"
|
||||
};
|
||||
let content = responses_content(parts, text_type)?;
|
||||
if !content.is_empty() {
|
||||
input.push(json!({
|
||||
"type":"message",
|
||||
"role":role_name(role),
|
||||
"content":content,
|
||||
}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn responses_content(parts: &[ContentPart], text_type: &str) -> Result<Vec<Value>> {
|
||||
parts
|
||||
.iter()
|
||||
.filter_map(|part| match part {
|
||||
ContentPart::Text { text } if text.is_empty() => None,
|
||||
ContentPart::Text { text } => Some(Ok(json!({"type":text_type, "text":text}))),
|
||||
ContentPart::Image { mime_type, data } => Some(Ok(json!({
|
||||
"type":"input_image",
|
||||
"detail":"auto",
|
||||
"image_url":format!("data:{mime_type};base64,{}", STANDARD.encode(data)),
|
||||
}))),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn push_responses_text(input: &mut Vec<Value>, role: &Role, text: &str) {
|
||||
if text.is_empty() {
|
||||
return;
|
||||
}
|
||||
let content_type = if *role == Role::Assistant {
|
||||
"output_text"
|
||||
} else {
|
||||
"input_text"
|
||||
};
|
||||
input.push(json!({
|
||||
"type": "message",
|
||||
"role": role_name(role),
|
||||
"content": [{"type": content_type, "text": text}],
|
||||
}));
|
||||
}
|
||||
|
||||
fn role_name(role: &Role) -> &'static str {
|
||||
match role {
|
||||
Role::System => "system",
|
||||
Role::User => "user",
|
||||
Role::Assistant => "assistant",
|
||||
Role::Tool => "tool",
|
||||
}
|
||||
}
|
||||
|
||||
fn required_u64(value: &Value, name: &str) -> Result<u64> {
|
||||
value
|
||||
.get(name)
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or_else(|| Error::Provider(format!("OpenAI Responses event is missing {name}")))
|
||||
}
|
||||
|
||||
fn responses_usage(value: &Value) -> Usage {
|
||||
Usage {
|
||||
input_tokens: value.get("input_tokens").and_then(Value::as_u64),
|
||||
output_tokens: value.get("output_tokens").and_then(Value::as_u64),
|
||||
total_tokens: value.get("total_tokens").and_then(Value::as_u64),
|
||||
cache_read_tokens: value
|
||||
.pointer("/input_tokens_details/cached_tokens")
|
||||
.and_then(Value::as_u64),
|
||||
cache_write_tokens: None,
|
||||
reasoning_tokens: value
|
||||
.pointer("/output_tokens_details/reasoning_tokens")
|
||||
.and_then(Value::as_u64),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
//! Records provider requests, responses, usage, and timing.
|
||||
use std::{
|
||||
sync::{
|
||||
atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering},
|
||||
Arc,
|
||||
},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::{
|
||||
model::{NewLlmCall, Usage},
|
||||
store::{BufferedLlmChunk, Store},
|
||||
Result,
|
||||
};
|
||||
|
||||
use super::{is_valid_response_event, FinishReason, ModelEvent};
|
||||
|
||||
pub(crate) fn recorded_headers(
|
||||
config: &crate::config::ProviderConfig,
|
||||
defaults: &[(&str, &str)],
|
||||
) -> serde_json::Value {
|
||||
let mut output = serde_json::Map::new();
|
||||
for (name, value) in defaults {
|
||||
output.insert((*name).into(), (*value).into());
|
||||
}
|
||||
for (name, value) in &config.custom_headers {
|
||||
if crate::model::is_sensitive_header(name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if let Ok(value) = value.to_str() {
|
||||
output.insert(name.as_str().into(), value.into());
|
||||
}
|
||||
}
|
||||
serde_json::Value::Object(output)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CallRecorder {
|
||||
inner: Arc<Inner>,
|
||||
}
|
||||
|
||||
pub(super) struct CancelOnDrop {
|
||||
recorder: CallRecorder,
|
||||
}
|
||||
|
||||
impl Drop for CancelOnDrop {
|
||||
fn drop(&mut self) {
|
||||
if self.recorder.is_finished() {
|
||||
return;
|
||||
}
|
||||
let recorder = self.recorder.clone();
|
||||
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
|
||||
tracing::warn!(
|
||||
call_id = recorder.call_id(),
|
||||
"unfinished LLM call dropped outside Tokio runtime"
|
||||
);
|
||||
return;
|
||||
};
|
||||
runtime.spawn(async move {
|
||||
if let Err(error) = recorder.cancelled().await {
|
||||
tracing::warn!(call_id = recorder.call_id(), %error, "failed to mark dropped LLM call cancelled");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
store: Store,
|
||||
base_call: NewLlmCall,
|
||||
detailed: bool,
|
||||
attempt: Mutex<AttemptState>,
|
||||
next_attempt: AtomicU32,
|
||||
next_generation: AtomicU64,
|
||||
finished: AtomicBool,
|
||||
}
|
||||
|
||||
struct AttemptState {
|
||||
call_id: String,
|
||||
started: Instant,
|
||||
next_chunk: AtomicI64,
|
||||
chunks: ChunkBuffer,
|
||||
first_text_recorded: AtomicBool,
|
||||
first_valid_response_recorded: AtomicBool,
|
||||
}
|
||||
|
||||
impl AttemptState {
|
||||
fn new(call_id: String) -> Self {
|
||||
Self {
|
||||
call_id,
|
||||
started: Instant::now(),
|
||||
next_chunk: AtomicI64::new(0),
|
||||
chunks: ChunkBuffer::default(),
|
||||
first_text_recorded: AtomicBool::new(false),
|
||||
first_valid_response_recorded: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ChunkBuffer {
|
||||
chunks: Vec<BufferedLlmChunk>,
|
||||
bytes: usize,
|
||||
first_chunk_at: Option<Instant>,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
const MAX_BUFFERED_CHUNKS: usize = 32;
|
||||
const MAX_BUFFERED_BYTES: usize = 256 * 1024;
|
||||
const MAX_BUFFER_AGE: std::time::Duration = std::time::Duration::from_millis(50);
|
||||
|
||||
impl CallRecorder {
|
||||
pub async fn start(store: Store, mut call: NewLlmCall) -> Result<Self> {
|
||||
call.detailed = store.detailed_logging().await?;
|
||||
store.start_llm_call(&call).await?;
|
||||
Ok(Self {
|
||||
inner: Arc::new(Inner {
|
||||
store,
|
||||
base_call: call.clone(),
|
||||
detailed: call.detailed,
|
||||
attempt: Mutex::new(AttemptState::new(call.call_id.clone())),
|
||||
next_attempt: AtomicU32::new(0),
|
||||
next_generation: AtomicU64::new(0),
|
||||
finished: AtomicBool::new(false),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn detailed(&self) -> bool {
|
||||
self.inner.detailed
|
||||
}
|
||||
|
||||
pub fn is_finished(&self) -> bool {
|
||||
self.inner.finished.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub(super) fn cancel_on_drop(&self) -> CancelOnDrop {
|
||||
CancelOnDrop {
|
||||
recorder: self.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn request(
|
||||
&self,
|
||||
headers: serde_json::Value,
|
||||
body: &serde_json::Value,
|
||||
) -> Result<()> {
|
||||
let attempt = self.inner.attempt.lock().await;
|
||||
self.inner
|
||||
.store
|
||||
.record_llm_request(&attempt.call_id, &headers, body, self.inner.detailed)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn response_headers(&self, status: u16) -> Result<()> {
|
||||
let attempt = self.inner.attempt.lock().await;
|
||||
self.inner
|
||||
.store
|
||||
.record_llm_response_headers(&attempt.call_id, elapsed_ms(attempt.started), status)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn response_chunk(&self, data: &[u8]) -> Result<()> {
|
||||
let mut attempt = self.inner.attempt.lock().await;
|
||||
if self.is_finished() {
|
||||
return Ok(());
|
||||
}
|
||||
let seq = attempt.next_chunk.fetch_add(1, Ordering::Relaxed);
|
||||
let schedule_flush = if attempt.chunks.chunks.is_empty() {
|
||||
attempt.chunks.generation = self
|
||||
.inner
|
||||
.next_generation
|
||||
.fetch_add(1, Ordering::Relaxed)
|
||||
.wrapping_add(1);
|
||||
attempt.chunks.first_chunk_at = Some(Instant::now());
|
||||
Some(attempt.chunks.generation)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
attempt.chunks.bytes += data.len();
|
||||
let elapsed = elapsed_ms(attempt.started);
|
||||
attempt.chunks.chunks.push(if self.inner.detailed {
|
||||
BufferedLlmChunk::new(seq, elapsed, data)
|
||||
} else {
|
||||
BufferedLlmChunk::metrics(seq, elapsed, data.len())
|
||||
});
|
||||
let expired = attempt
|
||||
.chunks
|
||||
.first_chunk_at
|
||||
.is_some_and(|started| started.elapsed() >= MAX_BUFFER_AGE);
|
||||
if attempt.chunks.chunks.len() >= MAX_BUFFERED_CHUNKS
|
||||
|| attempt.chunks.bytes >= MAX_BUFFERED_BYTES
|
||||
|| expired
|
||||
{
|
||||
self.flush_locked(&mut attempt).await?;
|
||||
}
|
||||
drop(attempt);
|
||||
if let Some(generation) = schedule_flush {
|
||||
let recorder = self.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(MAX_BUFFER_AGE).await;
|
||||
if let Err(error) = recorder.flush_generation(generation).await {
|
||||
tracing::warn!(call_id = recorder.call_id(), %error, "failed to flush LLM response chunks");
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn event(&self, event: &ModelEvent) -> Result<()> {
|
||||
let attempt = self.inner.attempt.lock().await;
|
||||
if is_valid_response_event(event)
|
||||
&& attempt
|
||||
.first_valid_response_recorded
|
||||
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
|
||||
.is_ok()
|
||||
{
|
||||
if let Err(error) = self
|
||||
.inner
|
||||
.store
|
||||
.record_llm_first_valid_response(&attempt.call_id, elapsed_ms(attempt.started))
|
||||
.await
|
||||
{
|
||||
attempt
|
||||
.first_valid_response_recorded
|
||||
.store(false, Ordering::Release);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
drop(attempt);
|
||||
|
||||
match event {
|
||||
ModelEvent::TextDelta(delta) if !delta.trim().is_empty() => {
|
||||
let attempt = self.inner.attempt.lock().await;
|
||||
if attempt
|
||||
.first_text_recorded
|
||||
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
|
||||
.is_ok()
|
||||
{
|
||||
if let Err(error) = self
|
||||
.inner
|
||||
.store
|
||||
.record_llm_first_text(&attempt.call_id, elapsed_ms(attempt.started))
|
||||
.await
|
||||
{
|
||||
attempt.first_text_recorded.store(false, Ordering::Release);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
ModelEvent::Usage(usage) => self.usage(*usage).await?,
|
||||
ModelEvent::Done(reason) => self.completed(*reason).await?,
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn usage(&self, usage: Usage) -> Result<()> {
|
||||
let attempt = self.inner.attempt.lock().await;
|
||||
self.inner
|
||||
.store
|
||||
.record_llm_usage(&attempt.call_id, usage)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn completed(&self, reason: FinishReason) -> Result<()> {
|
||||
self.finish("completed", Some(finish_reason(reason)), None, None)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn failed(&self, error: &crate::Error) -> Result<()> {
|
||||
self.finish(
|
||||
"error",
|
||||
None,
|
||||
Some(error_kind(error)),
|
||||
Some(&error.to_string()),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn cancelled(&self) -> Result<()> {
|
||||
self.finish("cancelled", None, None, None).await
|
||||
}
|
||||
|
||||
pub async fn retry(
|
||||
&self,
|
||||
error: &crate::Error,
|
||||
headers: serde_json::Value,
|
||||
body: &serde_json::Value,
|
||||
) -> Result<()> {
|
||||
self.failed(error).await?;
|
||||
|
||||
let attempt_number = self.inner.next_attempt.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
let mut call = self.inner.base_call.clone();
|
||||
call.call_id = format!("{}:retry-{attempt_number}", self.inner.base_call.call_id);
|
||||
{
|
||||
let mut attempt = self.inner.attempt.lock().await;
|
||||
*attempt = AttemptState::new(call.call_id.clone());
|
||||
self.inner.finished.store(false, Ordering::Release);
|
||||
if let Err(error) = self.inner.store.start_llm_call(&call).await {
|
||||
self.inner.finished.store(true, Ordering::Release);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(error) = self.request(headers, body).await {
|
||||
self.failed(&error).await?;
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn finish(
|
||||
&self,
|
||||
status: &str,
|
||||
reason: Option<&str>,
|
||||
error_kind: Option<&str>,
|
||||
error_message: Option<&str>,
|
||||
) -> Result<()> {
|
||||
if self.is_finished() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut attempt = self.inner.attempt.lock().await;
|
||||
if self.is_finished() {
|
||||
return Ok(());
|
||||
}
|
||||
self.flush_locked(&mut attempt).await?;
|
||||
self.inner
|
||||
.store
|
||||
.finish_llm_call(
|
||||
&attempt.call_id,
|
||||
status,
|
||||
reason,
|
||||
elapsed_ms(attempt.started),
|
||||
error_kind,
|
||||
error_message,
|
||||
)
|
||||
.await?;
|
||||
self.inner.finished.store(true, Ordering::Release);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn flush_generation(&self, generation: u64) -> Result<()> {
|
||||
let mut attempt = self.inner.attempt.lock().await;
|
||||
if attempt.chunks.generation != generation {
|
||||
return Ok(());
|
||||
}
|
||||
self.flush_locked(&mut attempt).await
|
||||
}
|
||||
|
||||
async fn flush_locked(&self, attempt: &mut AttemptState) -> Result<()> {
|
||||
let buffer = &mut attempt.chunks;
|
||||
if buffer.chunks.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let chunks = std::mem::take(&mut buffer.chunks);
|
||||
buffer.bytes = 0;
|
||||
buffer.first_chunk_at = None;
|
||||
if let Err(error) = self
|
||||
.inner
|
||||
.store
|
||||
.record_llm_chunks(&attempt.call_id, &chunks, self.inner.detailed)
|
||||
.await
|
||||
{
|
||||
buffer.bytes = chunks.iter().map(|chunk| chunk.byte_count).sum();
|
||||
buffer.first_chunk_at = Some(Instant::now());
|
||||
buffer.chunks = chunks;
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn call_id(&self) -> String {
|
||||
self.inner
|
||||
.attempt
|
||||
.try_lock()
|
||||
.map(|attempt| attempt.call_id.clone())
|
||||
.unwrap_or_else(|_| self.inner.base_call.call_id.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn elapsed_ms(started: Instant) -> i64 {
|
||||
started.elapsed().as_millis().min(i64::MAX as u128) as i64
|
||||
}
|
||||
|
||||
fn finish_reason(reason: FinishReason) -> &'static str {
|
||||
match reason {
|
||||
FinishReason::Stop => "stop",
|
||||
FinishReason::Length => "length",
|
||||
FinishReason::ToolUse => "tool_use",
|
||||
}
|
||||
}
|
||||
|
||||
fn error_kind(error: &crate::Error) -> &'static str {
|
||||
match error {
|
||||
crate::Error::Provider(_) | crate::Error::Http(_) => "provider",
|
||||
crate::Error::Cancelled => "cancelled",
|
||||
crate::Error::Database(_) | crate::Error::Store(_) => "store",
|
||||
_ => "internal",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::model::{
|
||||
ModelConfigInput, ModelType, NewLlmCall, ProviderType, OPENAI_CHAT_ENDPOINT,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_an_unfinished_call_guard_marks_the_call_cancelled() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let store = Store::connect(&format!(
|
||||
"sqlite://{}",
|
||||
directory.path().join("test.db").display()
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let model = store
|
||||
.create_model(&ModelConfigInput {
|
||||
sort_order: 0,
|
||||
display_name: "Test Model".into(),
|
||||
model_type: ModelType::OpenAi,
|
||||
base_url: "https://example.com/v1/chat/completions".into(),
|
||||
use_full_url: true,
|
||||
api_key: "test-key".into(),
|
||||
tooltip_data: "Test Model".into(),
|
||||
model_id: "test-model".into(),
|
||||
reasoning_effort: None,
|
||||
openai_endpoint: OPENAI_CHAT_ENDPOINT.into(),
|
||||
openai_extra_params_enabled: false,
|
||||
openai_extra_params: serde_json::json!({}),
|
||||
custom_headers_enabled: false,
|
||||
custom_headers: serde_json::json!({}),
|
||||
anthropic_extra_params_enabled: false,
|
||||
anthropic_extra_params: serde_json::json!({}),
|
||||
context_window_tokens: None,
|
||||
max_completion_tokens: None,
|
||||
anthropic_max_tokens: None,
|
||||
anthropic_thinking_effort: None,
|
||||
thinking_budget_tokens: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let recorder = CallRecorder::start(
|
||||
store.clone(),
|
||||
NewLlmCall {
|
||||
call_id: "cancel-on-drop".into(),
|
||||
run_id: "run".into(),
|
||||
conversation_id: "conversation".into(),
|
||||
provider_call_index: 0,
|
||||
model_hash: model.model_hash,
|
||||
provider_type: ProviderType::OpenAiChat,
|
||||
provider_url: "https://example.com".into(),
|
||||
request_type: ProviderType::OpenAiChat,
|
||||
request_url: "https://example.com/v1/chat/completions".into(),
|
||||
model_id: "test-model".into(),
|
||||
display_name: "Test Model".into(),
|
||||
reasoning_effort: None,
|
||||
fast: false,
|
||||
message_count: 1,
|
||||
tool_count: 0,
|
||||
detailed: false,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
drop(recorder.cancel_on_drop());
|
||||
|
||||
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(1);
|
||||
loop {
|
||||
let status: String =
|
||||
sqlx::query_scalar("SELECT status FROM llm_calls WHERE call_id = ?")
|
||||
.bind("cancel-on-drop")
|
||||
.fetch_one(store.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
if status == "cancelled" {
|
||||
break;
|
||||
}
|
||||
assert!(
|
||||
tokio::time::Instant::now() < deadline,
|
||||
"unfinished recorder stayed running after its stream was dropped"
|
||||
);
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Applies provider retry and backoff behavior.
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
use super::CallRecorder;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct RetryPolicy {
|
||||
pub retries: u32,
|
||||
pub delay: Duration,
|
||||
}
|
||||
|
||||
impl Default for RetryPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
retries: 5,
|
||||
delay: Duration::from_secs(5),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum Attempt {
|
||||
Response(reqwest::Response),
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
pub(crate) async fn send_with_retry<F>(
|
||||
label: &str,
|
||||
build: F,
|
||||
policy: RetryPolicy,
|
||||
cancellation: &CancellationToken,
|
||||
recorder: Option<&CallRecorder>,
|
||||
request_headers: serde_json::Value,
|
||||
request_body: &serde_json::Value,
|
||||
) -> Result<Attempt>
|
||||
where
|
||||
F: Fn() -> reqwest::RequestBuilder,
|
||||
{
|
||||
for attempt in 0..=policy.retries {
|
||||
let response = tokio::select! {
|
||||
_ = cancellation.cancelled() => return Ok(Attempt::Cancelled),
|
||||
response = build().send() => response,
|
||||
}?;
|
||||
if let Some(recorder) = recorder {
|
||||
recorder
|
||||
.response_headers(response.status().as_u16())
|
||||
.await?;
|
||||
}
|
||||
if response.status().is_success() {
|
||||
return Ok(Attempt::Response(response));
|
||||
}
|
||||
let status = response.status();
|
||||
let bytes = response.bytes().await?;
|
||||
let error = Error::Provider(format!(
|
||||
"{label} {status}: {}",
|
||||
String::from_utf8_lossy(&bytes)
|
||||
));
|
||||
if attempt == policy.retries {
|
||||
if let Some(recorder) = recorder {
|
||||
recorder.failed(&error).await?;
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
tracing::warn!(
|
||||
provider = label,
|
||||
status = status.as_u16(),
|
||||
attempt = attempt + 1,
|
||||
retries = policy.retries,
|
||||
delay_ms = policy.delay.as_millis(),
|
||||
"provider returned a non-success status, retrying"
|
||||
);
|
||||
if let Some(recorder) = recorder {
|
||||
recorder
|
||||
.retry(&error, request_headers.clone(), request_body)
|
||||
.await?;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = cancellation.cancelled() => return Ok(Attempt::Cancelled),
|
||||
_ = tokio::time::sleep(policy.delay) => {}
|
||||
}
|
||||
}
|
||||
unreachable!("the retry loop returns on the final attempt")
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
//! Routes model requests to the configured provider.
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use async_stream::try_stream;
|
||||
use futures_util::StreamExt;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{
|
||||
config::{ProviderConfig, ProviderKind},
|
||||
model::{ModelInvocation, ModelLatency, NewLlmCall, ProviderType},
|
||||
store::Store,
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
use super::{
|
||||
normalize::NormalizedProvider, AnthropicProvider, CallRecorder, OpenAiChatProvider,
|
||||
OpenAiResponsesProvider, Provider, ProviderStream,
|
||||
};
|
||||
|
||||
pub struct ProviderRouter {
|
||||
store: Store,
|
||||
request_timeout: Duration,
|
||||
}
|
||||
|
||||
impl ProviderRouter {
|
||||
pub fn new(store: Store, request_timeout: Duration) -> Self {
|
||||
Self {
|
||||
store,
|
||||
request_timeout,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Provider for ProviderRouter {
|
||||
fn stream(
|
||||
&self,
|
||||
mut invocation: ModelInvocation,
|
||||
cancellation: CancellationToken,
|
||||
) -> ProviderStream {
|
||||
let store = self.store.clone();
|
||||
let request_timeout = self.request_timeout;
|
||||
Box::pin(try_stream! {
|
||||
let selected = invocation.request.model.model_id.clone();
|
||||
let model = store
|
||||
.model(&selected)
|
||||
.await?
|
||||
.ok_or_else(|| Error::Provider(format!("unknown model: {selected}")))?;
|
||||
let provider_type = model.provider_type();
|
||||
let request_url = model.request_url()?;
|
||||
model.configure(&mut invocation.request.model);
|
||||
invocation.request.model.extra_params = model.extra_params().clone();
|
||||
invocation.request.model.model_id = model.model_id.clone();
|
||||
let recorder = CallRecorder::start(store.clone(), NewLlmCall {
|
||||
call_id: invocation.call_id.clone(),
|
||||
run_id: invocation.run_id.clone(),
|
||||
conversation_id: invocation.conversation_id.clone(),
|
||||
provider_call_index: invocation.provider_call_index.min(i64::MAX as u64) as i64,
|
||||
model_hash: model.model_hash.clone(),
|
||||
provider_type,
|
||||
provider_url: model.base_url.clone(),
|
||||
request_type: provider_type,
|
||||
request_url: request_url.clone(),
|
||||
model_id: model.model_id.clone(),
|
||||
display_name: model.display_name.clone(),
|
||||
reasoning_effort: invocation.request.model.reasoning.effort.clone(),
|
||||
fast: invocation.request.model.latency == ModelLatency::Fast,
|
||||
message_count: invocation.request.history.len(),
|
||||
tool_count: invocation.request.prompt.tools.len(),
|
||||
detailed: false,
|
||||
}).await?;
|
||||
let _cancel_on_drop = recorder.cancel_on_drop();
|
||||
let config = ProviderConfig {
|
||||
kind: match provider_type {
|
||||
ProviderType::OpenAiChat => ProviderKind::OpenAiChat,
|
||||
ProviderType::OpenAiResponses => ProviderKind::OpenAiResponses,
|
||||
ProviderType::Anthropic => ProviderKind::Anthropic,
|
||||
},
|
||||
request_url,
|
||||
api_key: model.api_key.clone(),
|
||||
custom_headers: if model.custom_headers_enabled {
|
||||
custom_headers(&model.custom_headers)?
|
||||
} else {
|
||||
reqwest::header::HeaderMap::new()
|
||||
},
|
||||
max_output_tokens: model.max_output_tokens(),
|
||||
request_timeout,
|
||||
};
|
||||
let client = crate::network::client_builder(&store)
|
||||
.await?
|
||||
.timeout(config.request_timeout)
|
||||
.build()?;
|
||||
let provider = build_observed(&config, recorder.clone(), client)?;
|
||||
let stream_cancellation = cancellation.clone();
|
||||
let mut stream = provider.stream(invocation, cancellation);
|
||||
let stream_started = std::time::Instant::now();
|
||||
tracing::debug!(
|
||||
model = %selected,
|
||||
provider_type = ?provider_type,
|
||||
timeout_ms = config.request_timeout.as_millis() as u64,
|
||||
"provider stream created"
|
||||
);
|
||||
let mut last_event_time = std::time::Instant::now();
|
||||
let mut event_count: u64 = 0;
|
||||
while let Some(event) = stream.next().await {
|
||||
let now = std::time::Instant::now();
|
||||
let gap_ms = now.duration_since(last_event_time).as_millis() as u64;
|
||||
let elapsed_ms = now.duration_since(stream_started).as_millis() as u64;
|
||||
event_count += 1;
|
||||
match event {
|
||||
Ok(event) => {
|
||||
let event_name = match &event {
|
||||
super::ModelEvent::Start { .. } => "Start",
|
||||
super::ModelEvent::TextStart => "TextStart",
|
||||
super::ModelEvent::TextDelta(_) => "TextDelta",
|
||||
super::ModelEvent::TextEnd => "TextEnd",
|
||||
super::ModelEvent::ThinkingStart => "ThinkingStart",
|
||||
super::ModelEvent::ThinkingDelta(_) => "ThinkingDelta",
|
||||
super::ModelEvent::ThinkingEnd => "ThinkingEnd",
|
||||
super::ModelEvent::ToolCallStart { .. } => "ToolCallStart",
|
||||
super::ModelEvent::ToolCallArgumentsDelta { .. } => "ToolCallArgsDelta",
|
||||
super::ModelEvent::ToolCallEnd { .. } => "ToolCallEnd",
|
||||
super::ModelEvent::ProviderReplayState(_) => "ReplayState",
|
||||
super::ModelEvent::Usage(_) => "Usage",
|
||||
super::ModelEvent::Done(_) => "Done",
|
||||
};
|
||||
if gap_ms > 5000 {
|
||||
tracing::debug!(
|
||||
gap_ms,
|
||||
elapsed_ms,
|
||||
event = event_name,
|
||||
event_count,
|
||||
"slow gap detected between provider events"
|
||||
);
|
||||
}
|
||||
recorder.event(&event).await?;
|
||||
last_event_time = now;
|
||||
yield event;
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::debug!(
|
||||
error = %error,
|
||||
elapsed_ms,
|
||||
gap_ms,
|
||||
event_count,
|
||||
"provider stream error"
|
||||
);
|
||||
recorder.failed(&error).await?;
|
||||
Err(error)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !recorder.is_finished() {
|
||||
let elapsed_ms = stream_started.elapsed().as_millis() as u64;
|
||||
if stream_cancellation.is_cancelled() {
|
||||
tracing::debug!(elapsed_ms, event_count, "provider stream ended after cancellation");
|
||||
recorder.cancelled().await?;
|
||||
} else {
|
||||
let error = Error::Provider("provider stream ended without Done".into());
|
||||
tracing::warn!(
|
||||
elapsed_ms,
|
||||
event_count,
|
||||
"provider stream ended without Done"
|
||||
);
|
||||
recorder.failed(&error).await?;
|
||||
Err(error)?;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn custom_headers(value: &serde_json::Value) -> Result<reqwest::header::HeaderMap> {
|
||||
let object = value
|
||||
.as_object()
|
||||
.ok_or_else(|| Error::Config("custom headers must be an object".into()))?;
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
for (name, value) in object {
|
||||
let name = reqwest::header::HeaderName::from_bytes(name.as_bytes())
|
||||
.map_err(|error| Error::Config(format!("invalid custom header name: {error}")))?;
|
||||
let value = value
|
||||
.as_str()
|
||||
.ok_or_else(|| Error::Config("custom header values must be strings".into()))?;
|
||||
let value = reqwest::header::HeaderValue::from_str(value)
|
||||
.map_err(|error| Error::Config(format!("invalid custom header value: {error}")))?;
|
||||
headers.insert(name, value);
|
||||
}
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
pub fn build(config: &ProviderConfig) -> Result<Arc<dyn Provider>> {
|
||||
build_inner(config, None, None)
|
||||
}
|
||||
|
||||
fn build_observed(
|
||||
config: &ProviderConfig,
|
||||
recorder: CallRecorder,
|
||||
client: reqwest::Client,
|
||||
) -> Result<Arc<dyn Provider>> {
|
||||
build_inner(config, Some(recorder), Some(client))
|
||||
}
|
||||
|
||||
fn build_inner(
|
||||
config: &ProviderConfig,
|
||||
recorder: Option<CallRecorder>,
|
||||
client: Option<reqwest::Client>,
|
||||
) -> Result<Arc<dyn Provider>> {
|
||||
let client = match client {
|
||||
Some(client) => client,
|
||||
None => reqwest::Client::builder()
|
||||
.timeout(config.request_timeout)
|
||||
.build()?,
|
||||
};
|
||||
let provider: Arc<dyn Provider> = match config.kind {
|
||||
ProviderKind::OpenAiChat => {
|
||||
Arc::new(OpenAiChatProvider::new(client, config.clone()).with_recorder(recorder))
|
||||
}
|
||||
ProviderKind::OpenAiResponses => {
|
||||
Arc::new(OpenAiResponsesProvider::new(client, config.clone()).with_recorder(recorder))
|
||||
}
|
||||
ProviderKind::Anthropic => {
|
||||
Arc::new(AnthropicProvider::new(client, config.clone()).with_recorder(recorder))
|
||||
}
|
||||
};
|
||||
Ok(Arc::new(NormalizedProvider::new(provider)))
|
||||
}
|
||||
Reference in new issue
Block a user