diff --git a/src/gateway/execution.rs b/src/gateway/execution.rs index b58792f..24e8bcc 100644 --- a/src/gateway/execution.rs +++ b/src/gateway/execution.rs @@ -110,15 +110,42 @@ impl AgentExecutionService { // 将结果消息保存到确定的话题 if let Some(topic_id) = target_topic_id { - if let Err(err) = session.append_messages_to_topic( + if is_current_turn { + // 如果是最新回合,使用 append_persisted_messages 保存到数据库并更新内存历史 + if let Err(err) = session.append_persisted_messages( + request.chat_id, + request.result.emitted_messages.clone(), + ) { + tracing::error!( + error = %err, + chat_id = %request.chat_id, + "Failed to append messages to session history" + ); + } + } else { + // 如果用户已切换话题,只保存到原始话题(不更新内存历史) + if let Err(err) = session.append_messages_to_topic( + request.chat_id, + topic_id, + &request.result.emitted_messages, + ) { + tracing::error!( + error = %err, + topic_id = %topic_id, + "Failed to append messages to topic" + ); + } + } + } else if is_current_turn { + // 如果没有话题,直接更新内存历史(append_persisted_messages 会处理持久化) + if let Err(err) = session.append_persisted_messages( request.chat_id, - topic_id, - &request.result.emitted_messages, + request.result.emitted_messages.clone(), ) { tracing::error!( error = %err, - topic_id = %topic_id, - "Failed to append messages to topic" + chat_id = %request.chat_id, + "Failed to append messages to session history" ); } } diff --git a/src/providers/openai.rs b/src/providers/openai.rs index 1766a82..35e93a7 100644 --- a/src/providers/openai.rs +++ b/src/providers/openai.rs @@ -235,12 +235,13 @@ impl OpenAIProvider { let normalized = self.normalize_tool_arguments(arguments); if self.uses_json_tool_arguments() { - // Model expects JSON object format + // Model expects JSON object format (e.g., some code models) normalized } else { // Standard OpenAI format: arguments as JSON string // But ensure we serialize valid JSON, not null match normalized { + Value::Null => Value::String("{}".to_string()), Value::String(raw) => { // If the string is already valid JSON, keep it as-is // Otherwise, ensure it's a proper JSON string