use crate::types::{Content, ModelSpec, StopReason, Usage, WebCitation, WebSearchResult};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use tracing::{debug, warn};
#[derive(Debug, Default, Serialize)]
pub(in crate::openai) struct OpenAiRequest {
pub model: String,
pub input: Vec<InputItem>,
pub tools: Vec<OpenAiTool>,
pub tool_choice: OpenAiToolChoice,
pub parallel_tool_calls: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_output_tokens: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub temperature: Option<f32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoning: Option<ReasoningConfig>,
pub stream: bool,
pub include: Vec<String>,
pub store: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(in crate::openai) enum OpenAiToolChoice {
#[default]
Auto,
None,
Required,
Function {
name: String,
},
}
impl Serialize for OpenAiToolChoice {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
match self {
Self::Auto => serializer.serialize_str("auto"),
Self::None => serializer.serialize_str("none"),
Self::Required => serializer.serialize_str("required"),
Self::Function { name } => {
let mut map = serializer.serialize_map(Some(2))?;
map.serialize_entry("type", "function")?;
map.serialize_entry("name", name)?;
map.end()
}
}
}
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::openai) enum InputItem {
Message {
content: Vec<MessageContentPart>,
role: String,
#[serde(skip_serializing_if = "Option::is_none")]
phase: Option<String>,
},
FunctionCall {
call_id: String,
name: String,
arguments: String,
},
FunctionCallOutput {
call_id: String,
output: FunctionOutput,
},
Reasoning {
summary: Vec<String>,
encrypted_content: String,
},
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub(in crate::openai) enum FunctionOutput {
Text(String),
Parts(Vec<MessageContentPart>),
}
impl InputItem {
pub(in crate::openai) fn message(role: &str, content: Vec<MessageContentPart>) -> Self {
Self::Message { content, role: role.to_string(), phase: None }
}
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::openai) enum MessageContentPart {
#[serde(rename = "input_text")]
Text { text: String },
#[serde(rename = "output_text")]
OutputText { text: String },
#[serde(rename = "input_image")]
Image { image_url: String },
#[serde(rename = "input_file")]
File {
#[serde(skip_serializing_if = "Option::is_none")]
filename: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
file_data: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
file_url: Option<String>,
},
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::openai) enum OpenAiTool {
#[serde(rename = "function")]
Function {
name: String,
#[serde(skip_serializing_if = "Option::is_none")]
description: Option<String>,
parameters: serde_json::Value,
},
#[serde(rename = "web_search")]
WebSearch,
}
#[derive(Debug, Serialize)]
pub(in crate::openai) struct ReasoningConfig {
pub effort: ReasoningEffort,
#[serde(skip_serializing_if = "Option::is_none")]
pub summary: Option<&'static str>,
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub(in crate::openai) enum ReasoningEffort {
None,
Low,
Medium,
High,
XHigh,
Max,
}
#[derive(Debug, Deserialize)]
pub(in crate::openai) struct OpenAiResponseCompletion {
pub status: String,
pub output: Vec<OutputItem>,
}
#[derive(Debug, Deserialize)]
#[serde(tag = "type")]
pub(in crate::openai) enum OutputItem {
#[serde(rename = "message")]
Message { content: Vec<OutputContent> },
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize)]
#[serde(tag = "type")]
pub(in crate::openai) enum OutputContent {
#[serde(rename = "output_text")]
OutputText {
text: String,
#[serde(default)]
annotations: Vec<OutputAnnotation>,
},
#[serde(rename = "text")]
Text {
text: String,
#[serde(default)]
annotations: Vec<OutputAnnotation>,
},
#[serde(other)]
Unknown,
}
impl OutputContent {
fn text(&self) -> Option<&str> {
match self {
OutputContent::OutputText { text, .. } | OutputContent::Text { text, .. } => Some(text),
OutputContent::Unknown => None,
}
}
fn annotations(&self) -> &[OutputAnnotation] {
match self {
OutputContent::OutputText { annotations, .. }
| OutputContent::Text { annotations, .. } => annotations,
OutputContent::Unknown => &[],
}
}
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub(in crate::openai) enum OutputAnnotation {
UrlCitation(UrlCitationAnnotation),
Other(#[allow(dead_code)] serde_json::Value), }
#[derive(Debug, Deserialize)]
pub(in crate::openai) struct UrlCitationAnnotation {
#[serde(default)]
title: Option<String>,
#[serde(default)]
url: Option<String>,
#[serde(default)]
text: Option<String>,
}
#[derive(Debug, Deserialize, Default)]
pub(in crate::openai) struct OpenAiInputTokensDetails {
#[serde(default)]
cached_tokens: u32,
#[serde(default)]
cache_write_tokens: Option<u32>,
}
#[derive(Debug, Deserialize, Default)]
pub(in crate::openai) struct OpenAiUsage {
#[serde(default)]
pub input_tokens: u32,
#[serde(default)]
pub output_tokens: u32,
#[serde(default)]
pub input_tokens_details: Option<OpenAiInputTokensDetails>,
}
#[derive(Debug, Deserialize)]
pub(in crate::openai) struct ListModelsResponse {
pub data: Vec<OpenAiModel>,
}
#[derive(Debug, Deserialize)]
pub(in crate::openai) struct OpenAiModel {
id: String,
#[serde(default)]
created: Option<i64>,
#[serde(default)]
owned_by: Option<String>,
}
impl From<OpenAiModel> for ModelSpec {
fn from(model: OpenAiModel) -> Self {
let description = openai_model_description(&model);
ModelSpec { id: model.id, description, ..Default::default() }
}
}
fn openai_model_description(model: &OpenAiModel) -> Option<String> {
let mut parts = Vec::new();
if let Some(owner) = model.owned_by.as_deref().map(str::trim).filter(|owner| !owner.is_empty())
{
parts.push(format!("Owned by {owner}"));
}
if let Some(created) = model.created.and_then(format_created_date) {
parts.push(format!("created {created}"));
}
if parts.is_empty() { None } else { Some(parts.join(", ")) }
}
fn format_created_date(timestamp: i64) -> Option<String> {
chrono::DateTime::from_timestamp(timestamp, 0).map(|dt| dt.date_naive().to_string())
}
#[derive(Debug, Deserialize, Default)]
pub(in crate::openai) struct ResponseStreamEvent {
#[serde(rename = "type", default)]
pub kind: String,
#[serde(default)]
pub response: Option<serde_json::Value>,
#[serde(default)]
pub item: Option<serde_json::Value>,
#[serde(default)]
pub delta: Option<String>,
}
impl From<OpenAiUsage> for Usage {
fn from(usage: OpenAiUsage) -> Self {
let details = usage.input_tokens_details;
Usage {
input_tokens: usage.input_tokens,
output_tokens: usage.output_tokens,
cache_read_tokens: details.as_ref().map(|d| d.cached_tokens),
cache_write_tokens: details.and_then(|d| d.cache_write_tokens),
}
}
}
pub(in crate::openai) fn stop_reason_from_status(value: &str) -> StopReason {
match value {
"completed" => StopReason::EndTurn,
"incomplete" => StopReason::MaxTokens,
other => StopReason::Other(other.to_string()),
}
}
fn extract_text_from_messages(output: &[OutputItem]) -> Vec<String> {
let mut text_parts = Vec::new();
for item in output {
if let OutputItem::Message { content, .. } = item {
for content_item in content {
if let Some(text) = content_item.text().filter(|text| !text.is_empty()) {
text_parts.push(text.to_string());
}
}
}
}
text_parts
}
impl TryFrom<OpenAiResponseCompletion> for WebSearchResult {
type Error = anyhow::Error;
fn try_from(completion: OpenAiResponseCompletion) -> Result<Self> {
let OpenAiResponseCompletion { status, output, .. } = completion;
if status != "completed" {
anyhow::bail!("Response not completed, status: {status}");
}
let text_parts = extract_text_from_messages(&output);
if text_parts.is_empty() {
warn!("No text content found in web search response. Output items: {}", output.len());
for (idx, item) in output.iter().enumerate() {
debug!("Output item {idx}: {item:?}");
}
}
let mut citations: Vec<WebCitation> = Vec::new();
let mut seen_urls: HashSet<String> = HashSet::new();
for item in &output {
if let OutputItem::Message { content, .. } = item {
for content_item in content {
for annotation in content_item.annotations() {
let OutputAnnotation::UrlCitation(UrlCitationAnnotation {
url,
title,
text: annotation_text,
..
}) = annotation
else {
continue;
};
let Some(url) = url else { continue };
let trimmed = url.trim();
if trimmed.is_empty() {
continue;
}
if !seen_urls.insert(trimmed.to_string()) {
continue;
}
let citation_title = title
.as_ref()
.filter(|t| !t.trim().is_empty())
.or_else(|| {
annotation_text
.as_ref()
.filter(|txt| !txt.trim().is_empty() && txt.as_str() != "{}")
})
.cloned()
.unwrap_or_else(|| trimmed.to_string());
citations
.push(WebCitation { title: citation_title, uri: trimmed.to_string() });
}
}
}
}
let content = Content::Text(text_parts.join("\n"));
Ok(WebSearchResult { content, citations })
}
}