feat(llm): 添加 tracing 日志与 ContentField 扩展
为 OpenAI 消息类型引入 ContentField 以支持 string 和 array 两种 content 格式,新增 reasoning_content 字段;添加 tracing 日志初始化函数及请求 /响应日志;修正多处文件末尾换行与 import 顺序。
This commit is contained in:
@@ -2,10 +2,11 @@ use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use reqwest::Client;
|
||||
use tracing::{debug, error, info};
|
||||
|
||||
use super::LlmProvider;
|
||||
use crate::llm::error::LlmError;
|
||||
use crate::llm::types::{ChatRequest, ChatResponse, OpenaiChatResponse};
|
||||
use super::LlmProvider;
|
||||
|
||||
pub struct OpenaiProvider {
|
||||
http_client: Client,
|
||||
@@ -50,6 +51,8 @@ impl LlmProvider for OpenaiProvider {
|
||||
async fn chat(&self, request: ChatRequest) -> Result<ChatResponse, LlmError> {
|
||||
let url = format!("{}/chat/completions", self.base_url.trim_end_matches('/'));
|
||||
|
||||
info!(model = %request.model, max_tokens = request.max_tokens, temperature = request.temperature, "发送 LLM 请求");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
.post(&url)
|
||||
@@ -57,7 +60,10 @@ impl LlmProvider for OpenaiProvider {
|
||||
.json(&request)
|
||||
.send()
|
||||
.await
|
||||
.map_err(Self::map_reqwest_error)?;
|
||||
.map_err(|e| {
|
||||
error!(error = %e, "请求失败");
|
||||
Self::map_reqwest_error(e)
|
||||
})?;
|
||||
|
||||
let status = response.status();
|
||||
let status_code: u16 = status.as_u16();
|
||||
@@ -71,6 +77,8 @@ impl LlmProvider for OpenaiProvider {
|
||||
.map(Duration::from_secs);
|
||||
let body_text = response.text().await.unwrap_or_default();
|
||||
|
||||
error!(status = status_code, body = %body_text, "请求失败");
|
||||
|
||||
return match status_code {
|
||||
401 => Err(LlmError::Authentication(body_text)),
|
||||
429 => Err(LlmError::RateLimit { retry_after }),
|
||||
@@ -91,11 +99,16 @@ impl LlmProvider for OpenaiProvider {
|
||||
};
|
||||
}
|
||||
|
||||
let chat_response: OpenaiChatResponse = response
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| LlmError::Other(format!("响应解析失败: {}", e)))?;
|
||||
let body_text = response.text().await.unwrap_or_default();
|
||||
debug!(body = %body_text, "收到响应体");
|
||||
|
||||
let chat_response: OpenaiChatResponse = serde_json::from_str(&body_text).map_err(|e| {
|
||||
error!(error = %e, body = %body_text, "响应解析失败");
|
||||
LlmError::Other(format!("响应解析失败: {}", e))
|
||||
})?;
|
||||
|
||||
debug!(response = ?chat_response, "收到 LLM 响应");
|
||||
|
||||
Ok(ChatResponse::from(chat_response))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user