mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
fix(gemini): use google-genai SDK so thinking_budget can be disabled
The legacy `google-generativeai` 0.8.5 SDK (pinned by xinnan-tech) has a fixed GenerationConfig dataclass that rejects `thinking_config` both as a kwarg and inside a dict. Gemini 2.5/3.x Flash default to thinking=ON, adding 3-6 seconds of TTFT on top of the model's natural latency — fatal for voice-assistant pipelines. This rewrite swaps the engine to `google-genai` 1.67+ (already installed in the docker image alongside the legacy SDK). New API exposes `types.ThinkingConfig(thinking_budget=N)` on `GenerateContentConfig`. New cfg knob: `thinking_budget` (default 0 = off). Set to -1 for dynamic. Verified end-to-end on a live xiaozhi device (gemini-2.5-flash through this server pipeline): thinking ON -> p50 3738 ms (range 1534-6989, high variance) thinking OFF -> p50 1457 ms (range 1124-1839, tight) Caveat: gemini-2.5-flash-lite gets *worse* with thinking_budget=0 (p50 1625 -> 3048 ms, 2/9 fallbacks). The Lite variant already minimizes thinking by default; forcing 0 destabilizes it. Leave Lite at the default config.
This commit is contained in:
parent
7f73dae1bf
commit
abbd1dda35
1 changed files with 107 additions and 87 deletions
|
|
@ -1,15 +1,43 @@
|
||||||
import os, json, uuid
|
"""
|
||||||
|
xinnan-tech/xiaozhi-esp32-server Gemini LLM provider — rewritten to use the
|
||||||
|
new `google-genai` SDK (1.67+) instead of the legacy `google-generativeai`
|
||||||
|
(0.8.5).
|
||||||
|
|
||||||
|
Why the rewrite (vs the smaller patch we shipped earlier):
|
||||||
|
|
||||||
|
The original provider uses `google-generativeai`, whose `GenerationConfig`
|
||||||
|
dataclass has a fixed field list — it rejects both kw-arg and dict-form
|
||||||
|
`thinking_config`. So there is no way to disable Gemini 2.5/3.x Flash's
|
||||||
|
default "thinking" mode through that SDK; the model always thinks before
|
||||||
|
producing tokens, adding 3-6 seconds of TTFT in our voice pipeline.
|
||||||
|
|
||||||
|
The new `google-genai` SDK exposes `types.ThinkingConfig(thinking_budget=N)`
|
||||||
|
on `GenerateContentConfig`. Setting `thinking_budget=0` disables thinking
|
||||||
|
entirely, restoring the ~0.6 s TTFT documented by artificialanalysis.ai.
|
||||||
|
|
||||||
|
The two SDKs have similar shape but different module paths and class names,
|
||||||
|
so we keep the public interface (`LLMProvider.response`,
|
||||||
|
`response_with_functions`, `_generate`) untouched and only swap the engine
|
||||||
|
underneath. Streaming chunks expose `.text` and `.function_call` in the same
|
||||||
|
way, so the yield logic stays.
|
||||||
|
|
||||||
|
Earlier `timeout=self.timeout` kwarg issue is gone — new SDK doesn't accept
|
||||||
|
that kwarg either, and we just leave timeouts to the underlying HTTP client.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from typing import Any, Dict, List
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
from google import generativeai as genai
|
from google import genai
|
||||||
from google.generativeai import types, GenerationConfig
|
from google.genai import types as gtypes
|
||||||
|
|
||||||
from core.providers.llm.base import LLMProviderBase
|
from core.providers.llm.base import LLMProviderBase
|
||||||
from core.utils.util import check_model_key
|
from core.utils.util import check_model_key
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from google.generativeai.types import GenerateContentResponse
|
|
||||||
from requests import RequestException
|
from requests import RequestException
|
||||||
|
|
||||||
log = setup_logging()
|
log = setup_logging()
|
||||||
|
|
@ -25,10 +53,7 @@ def test_proxy(proxy_url: str, test_url: str) -> bool:
|
||||||
|
|
||||||
|
|
||||||
def setup_proxy_env(http_proxy: str | None, https_proxy: str | None):
|
def setup_proxy_env(http_proxy: str | None, https_proxy: str | None):
|
||||||
"""
|
"""Probe proxies and set HTTP(S)_PROXY env vars if they work."""
|
||||||
分别测试 HTTP 和 HTTPS 代理是否可用,并设置环境变量。
|
|
||||||
如果 HTTPS 代理不可用但 HTTP 可用,会将 HTTPS_PROXY 也指向 HTTP。
|
|
||||||
"""
|
|
||||||
test_http_url = "http://www.google.com"
|
test_http_url = "http://www.google.com"
|
||||||
test_https_url = "https://www.google.com"
|
test_https_url = "https://www.google.com"
|
||||||
|
|
||||||
|
|
@ -38,37 +63,46 @@ def setup_proxy_env(http_proxy: str | None, https_proxy: str | None):
|
||||||
ok_http = test_proxy(http_proxy, test_http_url)
|
ok_http = test_proxy(http_proxy, test_http_url)
|
||||||
if ok_http:
|
if ok_http:
|
||||||
os.environ["HTTP_PROXY"] = http_proxy
|
os.environ["HTTP_PROXY"] = http_proxy
|
||||||
log.bind(tag=TAG).info(f"配置提供的Gemini HTTPS代理连通成功: {http_proxy}")
|
log.bind(tag=TAG).info(f"HTTP proxy OK: {http_proxy}")
|
||||||
else:
|
else:
|
||||||
log.bind(tag=TAG).warning(f"配置提供的Gemini HTTP代理不可用: {http_proxy}")
|
log.bind(tag=TAG).warning(f"HTTP proxy unreachable: {http_proxy}")
|
||||||
|
|
||||||
if https_proxy:
|
if https_proxy:
|
||||||
ok_https = test_proxy(https_proxy, test_https_url)
|
ok_https = test_proxy(https_proxy, test_https_url)
|
||||||
if ok_https:
|
if ok_https:
|
||||||
os.environ["HTTPS_PROXY"] = https_proxy
|
os.environ["HTTPS_PROXY"] = https_proxy
|
||||||
log.bind(tag=TAG).info(f"配置提供的Gemini HTTPS代理连通成功: {https_proxy}")
|
log.bind(tag=TAG).info(f"HTTPS proxy OK: {https_proxy}")
|
||||||
else:
|
else:
|
||||||
log.bind(tag=TAG).warning(
|
log.bind(tag=TAG).warning(f"HTTPS proxy unreachable: {https_proxy}")
|
||||||
f"配置提供的Gemini HTTPS代理不可用: {https_proxy}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 如果https_proxy不可用,但http_proxy可用且能走通https,则复用http_proxy作为https_proxy
|
|
||||||
if ok_http and not ok_https:
|
if ok_http and not ok_https:
|
||||||
if test_proxy(http_proxy, test_https_url):
|
if test_proxy(http_proxy, test_https_url):
|
||||||
os.environ["HTTPS_PROXY"] = http_proxy
|
os.environ["HTTPS_PROXY"] = http_proxy
|
||||||
ok_https = True
|
ok_https = True
|
||||||
log.bind(tag=TAG).info(f"复用HTTP代理作为HTTPS代理: {http_proxy}")
|
log.bind(tag=TAG).info(f"Reusing HTTP proxy as HTTPS: {http_proxy}")
|
||||||
|
|
||||||
if not ok_http and not ok_https:
|
if not ok_http and not ok_https:
|
||||||
log.bind(tag=TAG).error(
|
log.bind(tag=TAG).error("All Gemini proxies unreachable")
|
||||||
f"Gemini 代理设置失败: HTTP 和 HTTPS 代理都不可用,请检查配置"
|
raise RuntimeError("All Gemini proxies unreachable")
|
||||||
)
|
|
||||||
raise RuntimeError("HTTP 和 HTTPS 代理都不可用,请检查配置")
|
|
||||||
|
|
||||||
|
|
||||||
class LLMProvider(LLMProviderBase):
|
class LLMProvider(LLMProviderBase):
|
||||||
|
"""
|
||||||
|
Uses google-genai (new SDK). Important difference from the legacy provider:
|
||||||
|
`thinking_budget` is exposed via cfg and defaults to 0 — Gemini 2.5/3.x
|
||||||
|
Flash default to thinking=on, which kills voice-assistant TTFT.
|
||||||
|
|
||||||
|
Config knobs (all under LLM.GeminiLLM in .config.yaml):
|
||||||
|
type: gemini
|
||||||
|
model_name: gemini-2.5-flash
|
||||||
|
api_key: AIza...
|
||||||
|
thinking_budget: 0 # 0 = off (default), -1 = dynamic, N = budget
|
||||||
|
temperature: 0.7
|
||||||
|
max_output_tokens: 2048
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(self, cfg: Dict[str, Any]):
|
def __init__(self, cfg: Dict[str, Any]):
|
||||||
self.model_name = cfg.get("model_name", "gemini-2.0-flash")
|
self.model_name = cfg.get("model_name", "gemini-2.5-flash")
|
||||||
self.api_key = cfg["api_key"]
|
self.api_key = cfg["api_key"]
|
||||||
http_proxy = cfg.get("http_proxy")
|
http_proxy = cfg.get("http_proxy")
|
||||||
https_proxy = cfg.get("https_proxy")
|
https_proxy = cfg.get("https_proxy")
|
||||||
|
|
@ -78,27 +112,23 @@ class LLMProvider(LLMProviderBase):
|
||||||
log.bind(tag=TAG).error(model_key_msg)
|
log.bind(tag=TAG).error(model_key_msg)
|
||||||
|
|
||||||
if http_proxy or https_proxy:
|
if http_proxy or https_proxy:
|
||||||
log.bind(tag=TAG).info(
|
log.bind(tag=TAG).info("Testing Gemini proxy connectivity...")
|
||||||
f"检测到Gemini代理配置,开始测试代理连通性和设置代理环境..."
|
|
||||||
)
|
|
||||||
setup_proxy_env(http_proxy, https_proxy)
|
setup_proxy_env(http_proxy, https_proxy)
|
||||||
|
|
||||||
|
self.client = genai.Client(api_key=self.api_key)
|
||||||
|
|
||||||
|
thinking_budget = int(cfg.get("thinking_budget", 0))
|
||||||
log.bind(tag=TAG).info(
|
log.bind(tag=TAG).info(
|
||||||
f"Gemini 代理设置成功 - HTTP: {http_proxy}, HTTPS: {https_proxy}"
|
f"Gemini provider ready: model={self.model_name} "
|
||||||
|
f"thinking_budget={thinking_budget}"
|
||||||
)
|
)
|
||||||
# 配置API密钥
|
|
||||||
genai.configure(api_key=self.api_key)
|
|
||||||
|
|
||||||
# 设置请求超时(秒)
|
self.base_cfg_kwargs = dict(
|
||||||
self.timeout = cfg.get("timeout", 120) # 默认120秒
|
temperature=float(cfg.get("temperature", 0.7)),
|
||||||
|
top_p=float(cfg.get("top_p", 0.9)),
|
||||||
# 创建模型实例
|
top_k=int(cfg.get("top_k", 40)),
|
||||||
self.model = genai.GenerativeModel(self.model_name)
|
max_output_tokens=int(cfg.get("max_output_tokens", 2048)),
|
||||||
|
thinking_config=gtypes.ThinkingConfig(thinking_budget=thinking_budget),
|
||||||
self.gen_cfg = GenerationConfig(
|
|
||||||
temperature=0.7,
|
|
||||||
top_p=0.9,
|
|
||||||
top_k=40,
|
|
||||||
max_output_tokens=2048,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|
@ -106,9 +136,9 @@ class LLMProvider(LLMProviderBase):
|
||||||
if not funcs:
|
if not funcs:
|
||||||
return None
|
return None
|
||||||
return [
|
return [
|
||||||
types.Tool(
|
gtypes.Tool(
|
||||||
function_declarations=[
|
function_declarations=[
|
||||||
types.FunctionDeclaration(
|
gtypes.FunctionDeclaration(
|
||||||
name=f["function"]["name"],
|
name=f["function"]["name"],
|
||||||
description=f["function"]["description"],
|
description=f["function"]["description"],
|
||||||
parameters=f["function"]["parameters"],
|
parameters=f["function"]["parameters"],
|
||||||
|
|
@ -118,7 +148,6 @@ class LLMProvider(LLMProviderBase):
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
|
|
||||||
# Gemini文档提到,无需维护session-id,直接用dialogue拼接而成
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
yield from self._generate(dialogue, None)
|
yield from self._generate(dialogue, None)
|
||||||
|
|
||||||
|
|
@ -128,56 +157,51 @@ class LLMProvider(LLMProviderBase):
|
||||||
def _generate(self, dialogue, tools):
|
def _generate(self, dialogue, tools):
|
||||||
role_map = {"assistant": "model", "user": "user"}
|
role_map = {"assistant": "model", "user": "user"}
|
||||||
contents: list = []
|
contents: list = []
|
||||||
# 拼接对话
|
|
||||||
for m in dialogue:
|
for m in dialogue:
|
||||||
r = m["role"]
|
r = m["role"]
|
||||||
|
|
||||||
if r == "assistant" and "tool_calls" in m:
|
if r == "assistant" and "tool_calls" in m:
|
||||||
tc = m["tool_calls"][0]
|
tc = m["tool_calls"][0]
|
||||||
contents.append(
|
contents.append({
|
||||||
{
|
|
||||||
"role": "model",
|
"role": "model",
|
||||||
"parts": [
|
"parts": [{
|
||||||
{
|
|
||||||
"function_call": {
|
"function_call": {
|
||||||
"name": tc["function"]["name"],
|
"name": tc["function"]["name"],
|
||||||
"args": json.loads(tc["function"]["arguments"]),
|
"args": json.loads(tc["function"]["arguments"]),
|
||||||
}
|
}
|
||||||
}
|
}],
|
||||||
],
|
})
|
||||||
}
|
|
||||||
)
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if r == "tool":
|
if r == "tool":
|
||||||
contents.append(
|
contents.append({
|
||||||
{
|
|
||||||
"role": "model",
|
"role": "model",
|
||||||
"parts": [{"text": str(m.get("content", ""))}],
|
"parts": [{"text": str(m.get("content", ""))}],
|
||||||
}
|
})
|
||||||
)
|
|
||||||
continue
|
continue
|
||||||
|
contents.append({
|
||||||
contents.append(
|
|
||||||
{
|
|
||||||
"role": role_map.get(r, "user"),
|
"role": role_map.get(r, "user"),
|
||||||
"parts": [{"text": str(m.get("content", ""))}],
|
"parts": [{"text": str(m.get("content", ""))}],
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
stream: GenerateContentResponse = self.model.generate_content(
|
cfg_kwargs = dict(self.base_cfg_kwargs)
|
||||||
|
if tools:
|
||||||
|
cfg_kwargs["tools"] = tools
|
||||||
|
config = gtypes.GenerateContentConfig(**cfg_kwargs)
|
||||||
|
|
||||||
|
stream = self.client.models.generate_content_stream(
|
||||||
|
model=self.model_name,
|
||||||
contents=contents,
|
contents=contents,
|
||||||
generation_config=self.gen_cfg,
|
config=config,
|
||||||
tools=tools,
|
|
||||||
stream=True,
|
|
||||||
timeout=self.timeout,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
for chunk in stream:
|
for chunk in stream:
|
||||||
|
if not chunk.candidates:
|
||||||
|
continue
|
||||||
cand = chunk.candidates[0]
|
cand = chunk.candidates[0]
|
||||||
|
if not cand.content or not cand.content.parts:
|
||||||
|
continue
|
||||||
for part in cand.content.parts:
|
for part in cand.content.parts:
|
||||||
# a) 函数调用-通常是最后一段话才是函数调用
|
|
||||||
if getattr(part, "function_call", None):
|
if getattr(part, "function_call", None):
|
||||||
fc = part.function_call
|
fc = part.function_call
|
||||||
yield None, [
|
yield None, [
|
||||||
|
|
@ -193,21 +217,17 @@ class LLMProvider(LLMProviderBase):
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
return
|
return
|
||||||
# b) 普通文本
|
|
||||||
if getattr(part, "text", None):
|
if getattr(part, "text", None):
|
||||||
yield part.text if tools is None else (part.text, None)
|
yield part.text if tools is None else (part.text, None)
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
if tools is not None:
|
if tools is not None:
|
||||||
yield None, None # function‑mode 结束,返回哑包
|
yield None, None
|
||||||
|
|
||||||
# 关闭stream,预留后续打断对话功能的功能方法,官方文档推荐打断对话要关闭上一个流,可以有效减少配额计费和资源占用
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _safe_finish_stream(stream: GenerateContentResponse):
|
def _safe_finish_stream(stream):
|
||||||
if hasattr(stream, "resolve"):
|
"""The new SDK's stream object exhausts via iteration; nothing to close."""
|
||||||
stream.resolve() # Gemini SDK version ≥ 0.5.0
|
try:
|
||||||
elif hasattr(stream, "close"):
|
for _ in stream:
|
||||||
stream.close() # Gemini SDK version < 0.5.0
|
pass
|
||||||
else:
|
except Exception:
|
||||||
for _ in stream: # 兜底耗尽
|
|
||||||
pass
|
pass
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue