Skip to content

grok搜索返回TypeError #47

Description

@Cyriak173

核心原因

grok.py 第 250 行,流式响应解析时 delta["content"] 为 None,导致 content += None 抛出 TypeError。

###脚本重现

import os, sys, asyncio, traceback, logging

# -------------------------- 加载 .env --------------------------
try:
    from dotenv import load_dotenv
    env_path = '/root/GrokSearchMCP/WebSearchMCP/.env'
    if os.path.exists(env_path):
        load_dotenv(env_path)
        print("✅ 已从 .env 加载环境变量")
    else:
        print(f"❌ 找不到 .env 文件: {env_path}")
        sys.exit(1)
except ImportError:
    print("❌ 请先安装 python-dotenv: pip install python-dotenv")
    sys.exit(1)

api_key = os.getenv("GROK_API_KEY")
if not api_key:
    print("❌ GROK_API_KEY 未设置,请检查 .env")
    sys.exit(1)

api_url = os.getenv("GROK_API_URL", "")
effective_model = os.getenv("GROK_MODEL", "grok-3")
print(f"✅ API Key 前8位: {api_key[:8]}...  模型: {effective_model}")

# -------------------------- 添加项目路径 --------------------------
sys.path.insert(0, '/root/GrokSearchMCP/WebSearchMCP/src')

from web_search.providers.grok import GrokSearchProvider

grok = GrokSearchProvider(api_url, api_key, effective_model)

# -------------------------- 触发错误的查询列表 --------------------------
queries = [
    "linux.do GPT搜索很强 智商高 梗 MCP深入思考",
    "linux.do gpt 能get梗 智商高 搜索 很强",
    'linux.do "GPT" "搜索" "智商高" "梗" 帖子推荐',
    "linux.do GPT 搜索能力 很强 智商 例子",
    'linux.do "gpt" "搜索" "梗" "智商" "MCP" 帖子链接',
    "linux.do GPT搜索很强 智商 梗 例子 MCP 深入思考",
    'linux.do "openai" "玩梗" GPT 搜索 智商 MCP',
    "linux.do GPT 搜索 很强 'sequential thinking' MCP 智商",
    'linux.do "GPT可以" 梗',
]

async def test_query(q):
    print(f"\n--- 测试查询: {q} ---")
    try:
        result = await grok.search(q)
        print(f"✅ 成功,结果长度: {len(str(result))}")
        return True
    except TypeError as e:
        if "can only concatenate str" in str(e):
            print("\n🔥🔥🔥 复现 TypeError!🔥🔥🔥")
            traceback.print_exc()
            # 提取 grok.py 中的出错信息
            exc = traceback.TracebackException.from_exception(e)
            for frame in exc.stack:
                if 'grok.py' in frame.filename:
                    print(f"\n❌ 出错文件: {frame.filename}")
                    print(f"   行号: {frame.lineno}")
                    print(f"   代码: {frame.line}")
                    break
            return False
        else:
            raise
    except Exception as e:
        print(f"其他异常: {type(e).__name__}: {e}")
        traceback.print_exc()
        return False

async def main():
    for query in queries:
        success = await test_query(query)
        if not success:
            print("\n已捕获目标错误,停止测试。")
            return
    print("\n所有查询均未复现 TypeError,可能需要更多样本或延长测试。")

if __name__ == "__main__":
    asyncio.run(main())

报错

✅ 已从 .env 加载环境变量
✅ API Key 前8位: sk-LhkAu...  模型: grok-4.1-fast

--- 测试查询: linux.do GPT搜索很强 智商高 梗 MCP深入思考 ---
✅ 成功,结果长度: 167

--- 测试查询: linux.do gpt 能get梗 智商高 搜索 很强 ---
✅ 成功,结果长度: 546

--- 测试查询: linux.do "GPT" "搜索" "智商高" "梗" 帖子推荐 ---

🔥🔥🔥 复现 TypeError!🔥🔥🔥
Traceback (most recent call last):
  File "/root/GrokSearchMCP/WebSearchMCP/src/web_search/debug_grok.py", line 52, in test_query
    result = await grok.search(q)
  File "/root/GrokSearchMCP/WebSearchMCP/src/web_search/providers/grok.py", line 207, in search
    return await self._execute_stream_with_retry(headers, payload, ctx)
  File "/root/GrokSearchMCP/WebSearchMCP/src/web_search/providers/grok.py", line 273, in _execute_stream_with_retry
    async for attempt in AsyncRetrying(
  File "/usr/local/lib/python3.10/dist-packages/tenacity/asyncio/__init__.py", line 170, in __anext__
    do = await self.iter(retry_state=self._retry_state)
  File "/usr/local/lib/python3.10/dist-packages/tenacity/asyncio/__init__.py", line 157, in iter
    result = await action(retry_state)
  File "/usr/local/lib/python3.10/dist-packages/tenacity/_utils.py", line 111, in inner
    return call(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/tenacity/__init__.py", line 393, in <lambda>
    self._add_action_func(lambda rs: rs.outcome.result())
  File "/usr/lib/python3.10/concurrent/futures/_base.py", line 451, in result
    return self.__get_result()
  File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result
    raise self._exception
  File "/root/GrokSearchMCP/WebSearchMCP/src/web_search/providers/grok.py", line 287, in _execute_stream_with_retry
    return await self._parse_streaming_response(response, ctx)
  File "/root/GrokSearchMCP/WebSearchMCP/src/web_search/providers/grok.py", line 250, in _parse_streaming_response
    content += delta["content"]
TypeError: can only concatenate str (not "NoneType") to str

临时解决办法

grok.py 中的

if "content" in delta:
    content += delta["content"]

更改后变为

if "content" in delta:
    content += delta["content"] or ""

后续正常使用搜索无任何报错。

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions