You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AgentExecutor遇ModuleNotFoundError/NameError:已安装TextBlob仍无法调用

解决LangChain Agent中TextBlob导入与NameError问题

针对你在LangChain的ConversationalChatAgent集成数据分析工具时遇到的TextBlob使用问题,以下是具体的排查和解决步骤:

1. 确认TextBlob的正确导入方式

初始的import TextBlob报错是因为TextBlob的正确导入路径是from textblob import TextBlob,这是Python包的标准导入逻辑——包名是textblob,TextBlob是其中的核心类。

2. 排查NameError的核心原因

修改导入后出现NameError,本质是TextBlob对象未在Agent执行的作用域内被正确识别,常见场景和解决方法:

  • 局部作用域限制:如果导入语句写在某个函数内部(或未放在全局作用域),Agent调用工具时会找不到该类。解决:将from textblob import TextBlob放在工具定义的全局作用域,或者直接写在工具函数内部:
    from langchain.tools import tool
    
    @tool
    def analyze_sentiment(text: str) -> float:
        """分析文本情感极性,返回-1(负面)到1(正面)的数值"""
        from textblob import TextBlob  # 在工具函数内导入,确保作用域可达
        blob = TextBlob(text)
        return blob.sentiment.polarity
    
  • 虚拟环境不一致:虽然你安装了TextBlob,但LangChain运行的虚拟环境可能未同步安装。执行以下命令确保环境一致:
    pip install textblob
    python -m textblob.download_corpora  # 下载必要的语料库
    
  • LLM生成代码错误:如果Agent使用PythonREPLTool让LLM动态生成代码,LLM可能遗漏导入步骤或写错类名。解决:在Agent的system prompt中明确规范代码格式:

    分析文本情感时,必须执行以下代码:
    from textblob import TextBlob
    result = TextBlob("待分析文本").sentiment.polarity

3. 验证工具独立性与Agent集成

  • 先单独测试情感分析工具,确认功能正常:
    print(analyze_sentiment("这个服务太差劲了"))  # 应返回接近-1的数值
    
  • 确认Agent正确注册工具:
    from langchain.agents import AgentExecutor, ConversationalChatAgent
    from langchain.memory import ConversationBufferMemory
    
    tools = [analyze_sentiment]
    memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
    agent = ConversationalChatAgent.from_llm_and_tools(
        llm=你的LLM实例,
        tools=tools,
        memory=memory
    )
    agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
    

内容的提问来源于stack exchange,提问作者illuminato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:45:20