mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
cherrypick fix
This commit is contained in:
parent
f052047d65
commit
1a46e6a67c
3 changed files with 53 additions and 292 deletions
|
|
@ -776,89 +776,18 @@ class ConnectionHandler:
|
||||||
)
|
)
|
||||||
|
|
||||||
if self.intent_type == "function_call" and functions is not None:
|
if self.intent_type == "function_call" and functions is not None:
|
||||||
# 使用支持functions的streaming接口
|
# 直接使用同步生成器(response_with_functions 是同步方法)
|
||||||
# response_with_functions 是异步生成器,使用队列在线程间传递
|
llm_responses = self.llm.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,
|
self.session_id,
|
||||||
dialogue_history,
|
dialogue_history,
|
||||||
functions=functions,
|
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
|
|
||||||
)
|
|
||||||
|
|
||||||
# 从队列中获取响应
|
|
||||||
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:
|
else:
|
||||||
# response 也是异步生成器,使用队列在线程间传递
|
# 直接使用同步生成器(response 是同步方法)
|
||||||
response_queue = queue.Queue()
|
llm_responses = self.llm.response(
|
||||||
stop_flag = threading.Event()
|
|
||||||
|
|
||||||
async def consume_async_generator():
|
|
||||||
try:
|
|
||||||
async_gen = self.llm.response(
|
|
||||||
self.session_id,
|
self.session_id,
|
||||||
dialogue_history,
|
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
|
|
||||||
)
|
|
||||||
|
|
||||||
# 从队列中获取响应
|
|
||||||
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:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}", exc_info=True)
|
self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}", exc_info=True)
|
||||||
return None
|
return None
|
||||||
|
|
|
||||||
|
|
@ -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))
|
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):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
"""
|
|
||||||
同步流式响应方法
|
|
||||||
注意:保持同步以兼容基类和其他 LLM 提供商
|
|
||||||
"""
|
|
||||||
try:
|
try:
|
||||||
# Create streaming response
|
responses = self.client.chat.completions.create(
|
||||||
# 注意:ChatGLM 等服务可能不支持 responses.create API,改用标准的 chat.completions.create
|
|
||||||
stream = self.client.chat.completions.create(
|
|
||||||
model=self.model_name,
|
model=self.model_name,
|
||||||
messages=dialogue,
|
messages=dialogue,
|
||||||
stream=True,
|
stream=True,
|
||||||
max_tokens=kwargs.get("max_tokens", self.max_tokens),
|
max_tokens=kwargs.get("max_tokens", self.max_tokens),
|
||||||
temperature=kwargs.get("temperature", self.temperature),
|
temperature=kwargs.get("temperature", self.temperature),
|
||||||
top_p=kwargs.get("top_p", self.top_p),
|
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
|
is_active = True
|
||||||
|
for chunk in responses:
|
||||||
for chunk in stream:
|
|
||||||
try:
|
try:
|
||||||
# Handle response choices
|
# 检查是否存在有效的choice且content不为空
|
||||||
if not hasattr(chunk, "choices") or not chunk.choices:
|
delta = (
|
||||||
continue
|
chunk.choices[0].delta
|
||||||
|
if getattr(chunk, "choices", None)
|
||||||
delta = chunk.choices[0].delta
|
else None
|
||||||
content = getattr(delta, "content", None)
|
)
|
||||||
|
content = delta.content if hasattr(delta, "content") else ""
|
||||||
if content is None:
|
except IndexError:
|
||||||
continue
|
content = ""
|
||||||
|
if content:
|
||||||
# Handle thinking tags (for reasoning models like o1)
|
# 处理标签跨多个chunk的情况
|
||||||
# Filter out content between <think>...</think>
|
|
||||||
if "<think>" in content:
|
if "<think>" in content:
|
||||||
is_active = False
|
is_active = False
|
||||||
content = content.split("<think>")[0]
|
content = content.split("<think>")[0]
|
||||||
|
|
@ -91,191 +85,38 @@ class LLMProvider(LLMProviderBase):
|
||||||
if is_active:
|
if is_active:
|
||||||
yield content
|
yield content
|
||||||
|
|
||||||
except (IndexError, AttributeError) as e:
|
|
||||||
continue
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"处理 chunk 时发生未预期错误: {e}", exc_info=True)
|
try:
|
||||||
continue
|
error_msg = repr(e)[:200]
|
||||||
|
except:
|
||||||
except Exception as e:
|
error_msg = "encoding error"
|
||||||
logger.bind(tag=TAG).error(f"Error in response generation: {e}", exc_info=True)
|
logger.bind(tag=TAG).error(f"Error in response generation: {error_msg}")
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
"""
|
|
||||||
同步流式响应方法(支持函数调用)
|
|
||||||
注意:保持同步以兼容基类和其他 LLM 提供商
|
|
||||||
"""
|
|
||||||
try:
|
try:
|
||||||
# Prepare request parameters
|
stream = self.client.chat.completions.create(
|
||||||
request_params = {
|
model=self.model_name, messages=dialogue, stream=True, tools=functions
|
||||||
"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)
|
|
||||||
|
|
||||||
for chunk in stream:
|
for chunk in stream:
|
||||||
try:
|
# 检查是否存在有效的choice且content不为空
|
||||||
# Handle token usage reporting
|
if getattr(chunk, "choices", None):
|
||||||
if hasattr(chunk, "usage") and isinstance(chunk.usage, CompletionUsage):
|
yield chunk.choices[0].delta.content, chunk.choices[
|
||||||
usage_info = chunk.usage
|
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(
|
logger.bind(tag=TAG).info(
|
||||||
f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')},"
|
f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')},"
|
||||||
f"输出 {getattr(usage_info, 'completion_tokens', '未知')},"
|
f"输出 {getattr(usage_info, 'completion_tokens', '未知')},"
|
||||||
f"共计 {getattr(usage_info, 'total_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
|
|
||||||
|
|
||||||
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:
|
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:
|
try:
|
||||||
# 1. Convert ChatContext to OpenAI format
|
error_msg = repr(e)[:200]
|
||||||
messages, _ = chat_ctx.to_provider_format(format="openai")
|
except:
|
||||||
|
error_msg = "encoding error"
|
||||||
logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).error(f"Error in function call streaming: {error_msg}")
|
||||||
f"Starting streaming with model={self.model_name}, "
|
yield "OpenAI service error", None
|
||||||
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)}】"
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
|
||||||
|
|
@ -80,15 +80,6 @@ class WebSocketServer:
|
||||||
"authorization"
|
"authorization"
|
||||||
][0]
|
][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"""
|
"""处理新连接,每次创建独立的ConnectionHandler"""
|
||||||
# 先认证,后建立连接
|
# 先认证,后建立连接
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue