diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 9dc15fcd2..24d62c753 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -776,89 +776,18 @@ class ConnectionHandler: ) if self.intent_type == "function_call" and functions is not None: - # 使用支持functions的streaming接口 - # response_with_functions 是异步生成器,使用队列在线程间传递 - response_queue = queue.Queue() - stop_flag = threading.Event() - - async def consume_async_generator(): - try: - async_gen = self.llm.response_with_functions( - self.session_id, - dialogue_history, - functions=functions, - ) - async for item in async_gen: - if stop_flag.is_set(): - break - response_queue.put(item) - response_queue.put(None) # 结束标记 - except Exception as e: - self.logger.bind(tag=TAG).error(f"异步生成器消费出错: {e}", exc_info=True) - response_queue.put(None) - response_queue.put(("ERROR", str(e))) - - asyncio.run_coroutine_threadsafe( - consume_async_generator(), self.loop + # 直接使用同步生成器(response_with_functions 是同步方法) + llm_responses = self.llm.response_with_functions( + self.session_id, + dialogue_history, + functions=functions, ) - - # 从队列中获取响应 - def get_responses(): - while True: - try: - item = response_queue.get(timeout=300) # 5分钟超时 - if item is None: - break - if isinstance(item, tuple) and item[0] == "ERROR": - raise Exception(item[1]) - yield item - except queue.Empty: - self.logger.bind(tag=TAG).warning("等待 LLM 响应超时") - stop_flag.set() - break - - llm_responses = get_responses() else: - # response 也是异步生成器,使用队列在线程间传递 - response_queue = queue.Queue() - stop_flag = threading.Event() - - async def consume_async_generator(): - try: - async_gen = self.llm.response( - self.session_id, - dialogue_history, - ) - async for item in async_gen: - if stop_flag.is_set(): - break - response_queue.put(item) - response_queue.put(None) # 结束标记 - except Exception as e: - self.logger.bind(tag=TAG).error(f"异步生成器消费出错: {e}", exc_info=True) - response_queue.put(None) - response_queue.put(("ERROR", str(e))) - - asyncio.run_coroutine_threadsafe( - consume_async_generator(), self.loop + # 直接使用同步生成器(response 是同步方法) + llm_responses = self.llm.response( + self.session_id, + dialogue_history, ) - - # 从队列中获取响应 - def get_responses(): - while True: - try: - item = response_queue.get(timeout=300) # 5分钟超时 - if item is None: - break - if isinstance(item, tuple) and item[0] == "ERROR": - raise Exception(item[1]) - yield item - except queue.Empty: - self.logger.bind(tag=TAG).warning("等待 LLM 响应超时") - stop_flag.set() - break - - llm_responses = get_responses() except Exception as e: self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}", exc_info=True) return None diff --git a/main/xiaozhi-server/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py index 18548e4c2..a116a80db 100644 --- a/main/xiaozhi-server/core/providers/llm/openai/openai.py +++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py @@ -49,39 +49,33 @@ class LLMProvider(LLMProviderBase): self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url, timeout=httpx.Timeout(self.timeout)) def response(self, session_id, dialogue, **kwargs): - """ - 同步流式响应方法 - 注意:保持同步以兼容基类和其他 LLM 提供商 - """ try: - # Create streaming response - # 注意:ChatGLM 等服务可能不支持 responses.create API,改用标准的 chat.completions.create - stream = self.client.chat.completions.create( + responses = self.client.chat.completions.create( model=self.model_name, messages=dialogue, stream=True, max_tokens=kwargs.get("max_tokens", self.max_tokens), temperature=kwargs.get("temperature", self.temperature), top_p=kwargs.get("top_p", self.top_p), - frequency_penalty=kwargs.get("frequency_penalty", self.frequency_penalty), + frequency_penalty=kwargs.get( + "frequency_penalty", self.frequency_penalty + ), ) - + is_active = True - - for chunk in stream: + for chunk in responses: try: - # Handle response choices - if not hasattr(chunk, "choices") or not chunk.choices: - continue - - delta = chunk.choices[0].delta - content = getattr(delta, "content", None) - - if content is None: - continue - - # Handle thinking tags (for reasoning models like o1) - # Filter out content between ... + # 检查是否存在有效的choice且content不为空 + delta = ( + chunk.choices[0].delta + if getattr(chunk, "choices", None) + else None + ) + content = delta.content if hasattr(delta, "content") else "" + except IndexError: + content = "" + if content: + # 处理标签跨多个chunk的情况 if "" in content: is_active = False content = content.split("")[0] @@ -90,192 +84,39 @@ class LLMProvider(LLMProviderBase): content = content.split("")[-1] if is_active: yield content - - except (IndexError, AttributeError) as e: - continue - except Exception as e: - logger.bind(tag=TAG).error(f"处理 chunk 时发生未预期错误: {e}", exc_info=True) - continue except Exception as e: - logger.bind(tag=TAG).error(f"Error in response generation: {e}", exc_info=True) + try: + error_msg = repr(e)[:200] + except: + error_msg = "encoding error" + logger.bind(tag=TAG).error(f"Error in response generation: {error_msg}") def response_with_functions(self, session_id, dialogue, functions=None): - """ - 同步流式响应方法(支持函数调用) - 注意:保持同步以兼容基类和其他 LLM 提供商 - """ try: - # Prepare request parameters - request_params = { - "model": self.model_name, - "messages": dialogue, - "stream": True, - } - - # Add tools/functions if provided - if functions: - request_params["tools"] = functions - - # Create streaming response (同步版本,移除 await) - stream = self.client.chat.completions.create(**request_params) + stream = self.client.chat.completions.create( + model=self.model_name, messages=dialogue, stream=True, tools=functions + ) for chunk in stream: - try: - # Handle token usage reporting - if hasattr(chunk, "usage") and isinstance(chunk.usage, CompletionUsage): - usage_info = chunk.usage - logger.bind(tag=TAG).info( - f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')}," - f"输出 {getattr(usage_info, 'completion_tokens', '未知')}," - f"共计 {getattr(usage_info, 'total_tokens', '未知')}" - ) - continue - - # Handle response choices - if not hasattr(chunk, "choices") or not chunk.choices: - continue - - delta = chunk.choices[0].delta - - # Extract content and tool calls - content = getattr(delta, "content", None) - tool_calls = getattr(delta, "tool_calls", None) - - # Yield the chunk - yield content, tool_calls - - except (IndexError, AttributeError) as e: - continue + # 检查是否存在有效的choice且content不为空 + if getattr(chunk, "choices", None): + yield chunk.choices[0].delta.content, chunk.choices[ + 0 + ].delta.tool_calls + # 存在 CompletionUsage 消息时,生成 Token 消耗 log + elif isinstance(getattr(chunk, "usage", None), CompletionUsage): + usage_info = getattr(chunk, "usage", None) + logger.bind(tag=TAG).info( + f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')}," + f"输出 {getattr(usage_info, 'completion_tokens', '未知')}," + f"共计 {getattr(usage_info, 'total_tokens', '未知')}" + ) - except openai.APIError as e: - error_msg = f"OpenAI API error: {e.message if hasattr(e, 'message') else str(e)}" - logger.bind(tag=TAG).error(error_msg) - yield f"【API错误: {error_msg}】", None - - except openai.APIConnectionError as e: - error_msg = f"Connection error: {str(e)}" - logger.bind(tag=TAG).error(error_msg) - yield f"【连接错误: 无法连接到服务】", None - - except openai.RateLimitError as e: - error_msg = f"Rate limit exceeded: {str(e)}" - logger.bind(tag=TAG).error(error_msg) - yield f"【请求过于频繁,请稍后再试】", None - except Exception as e: - error_msg = f"Unexpected error in function calling: {type(e).__name__}: {str(e)}" - logger.bind(tag=TAG).error(error_msg, exc_info=True) - yield f"【OpenAI服务响应异常: {str(e)}】", None - - async def response_stream( - self, - chat_ctx: ChatContext, - **kwargs: Any - ) -> AsyncGenerator[ChatChunk, None]: - """ - New streaming interface using standard protocol - - This method implements the new standard interface defined in LLMProviderBase. - It uses: - - ChatContext as input (standard dialogue protocol) - - ChatChunk as output (standard streaming protocol) - - OpenAI Responses API (modern response.create) - - Args: - chat_ctx: Standard ChatContext with dialogue history - **kwargs: Additional options: - - max_output_tokens: Override max tokens - - temperature: Override temperature - - top_p: Override top_p - - frequency_penalty: Override frequency penalty - - Yields: - ChatChunk: Standardized streaming chunks with deltas and usage - - Example: - async for chunk in provider.response_stream(chat_ctx): - if chunk.delta and chunk.delta.content: - print(chunk.delta.content) - if chunk.usage: - print(f"Tokens: {chunk.usage.total_tokens}") - """ - try: - # 1. Convert ChatContext to OpenAI format - messages, _ = chat_ctx.to_provider_format(format="openai") - - logger.bind(tag=TAG).debug( - f"Starting streaming with model={self.model_name}, " - f"messages_count={len(messages)}" - ) - - # 2. Prepare request parameters - max_output_tokens = kwargs.get("max_output_tokens", self.max_output_tokens) - temperature = kwargs.get("temperature", self.temperature) - top_p = kwargs.get("top_p", self.top_p) - frequency_penalty = kwargs.get("frequency_penalty", self.frequency_penalty) - - # 3. Call OpenAI Responses API - # TODO: system instruction needs to be added - stream: AsyncStream[ResponseStreamEvent] = await self.client.responses.create( - input=messages, - model=self.model_name, - stream=True, - max_output_tokens=max_output_tokens, - temperature=temperature, - top_p=top_p, - frequency_penalty=frequency_penalty, - ) - - # 4. Parse stream and yield ChatChunk (focus on output_item.done + completed) - async for event in stream: - try: - chunk = self._parse_response_event(event) - if chunk: - yield chunk - except (IndexError, AttributeError) as e: - logger.bind(tag=TAG).debug(f"Skipping malformed event: {e}") - continue - - logger.bind(tag=TAG).debug("Stream completed successfully") - - except openai.APIError as e: - error_msg = f"OpenAI API error: {e.message if hasattr(e, 'message') else str(e)}" - logger.bind(tag=TAG).error(error_msg) - # Yield error chunk - yield ChatChunk( - delta=ChatDelta( - role="assistant", - content=f"【API错误: {error_msg}】" - ) - ) - - except openai.APIConnectionError as e: - error_msg = f"Connection error: {str(e)}" - logger.bind(tag=TAG).error(error_msg) - yield ChatChunk( - delta=ChatDelta( - role="assistant", - content="【连接错误: 无法连接到服务】" - ) - ) - - except openai.RateLimitError as e: - error_msg = f"Rate limit exceeded: {str(e)}" - logger.bind(tag=TAG).error(error_msg) - yield ChatChunk( - delta=ChatDelta( - role="assistant", - content="【请求过于频繁,请稍后再试】" - ) - ) - - except Exception as e: - error_msg = f"Unexpected error: {type(e).__name__}: {str(e)}" - logger.bind(tag=TAG).error(error_msg) - yield ChatChunk( - delta=ChatDelta( - role="assistant", - content=f"【服务异常: {str(e)}】" - ) - ) + try: + error_msg = repr(e)[:200] + except: + error_msg = "encoding error" + logger.bind(tag=TAG).error(f"Error in function call streaming: {error_msg}") + yield "OpenAI service error", None diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index 79f21a02d..c0c88fc57 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -80,15 +80,6 @@ class WebSocketServer: "authorization" ][0] - if "sample_rate" in query_params: - websocket.request.headers["audio-sample-rate"] = query_params["sample_rate"][0] - if "channels" in query_params: - websocket.request.headers["audio-channels"] = query_params["channels"][0] - if "codec" in query_params: - websocket.request.headers["audio-codec"] = query_params["codec"][0] - if "frame_duration" in query_params: - websocket.request.headers["audio-frame-duration"] = query_params["frame_duration"][0] - """处理新连接,每次创建独立的ConnectionHandler""" # 先认证,后建立连接 try: