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

Langchain中Fake LLM调用PythonAstREPLTool报错,求正确实现方案

代码错误原因及修复

错误根源

错误源于工具名称不匹配:PythonAstREPLTool的默认工具名称是python_repl_ast,但你在FakeListLLM的响应里写的是Action: Python REPL,Agent无法识别这个未注册的工具名称,因此抛出错误。

修复方案(两种任选其一)

方案1:修改FakeLLM响应中的工具名称

将响应里的工具名称改为工具默认的python_repl_ast:

from langchain.agents import initialize_agent
from langchain.llms.fake import FakeListLLM
from langchain.agents import AgentType
from langchain_experimental.tools import PythonAstREPLTool

# 调整Action后的工具名称为默认值
res = ["Action: python_repl_ast\nAction Input: print(2.2 + 2.22)", "Final Answer: 4.42"]
llm = FakeListLLM(responses=res)
agent = initialize_agent(tools=[PythonAstREPLTool()],
                         llm=llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
                        )
agent.run("what is 2.2 + 2.22?")

方案2:给工具自定义名称

初始化PythonAstREPLTool时指定name参数为"Python REPL",和响应里的名称保持一致:

from langchain.agents import initialize_agent
from langchain.llms.fake import FakeListLLM
from langchain.agents import AgentType
from langchain_experimental.tools import PythonAstREPLTool

res = ["Action: Python REPL\nAction Input: print(2.2 + 2.22)", "Final Answer: 4.42"]
llm = FakeListLLM(responses=res)
# 给工具设置自定义名称
tool = PythonAstREPLTool(name="Python REPL")
agent = initialize_agent(tools=[tool],
                         llm=llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
                        )
agent.run("what is 2.2 + 2.22?")

FakeListLLM的更优实现方式

FakeListLLM核心用于离线测试,无需调用真实LLM,以下是几种更适配测试场景的实现思路:

1. 按输入场景映射响应

针对多输入测试场景,自定义LLM类实现输入与响应的映射,替代固定顺序的列表:

from langchain.llms.base import LLM
from typing import List, Optional

class CustomFakeLLM(LLM):
    # 定义输入到响应的映射表
    input_response_map: dict = {}
    
    @property
    def _llm_type(self) -> str:
        return "custom-fake"
    
    def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
        # 匹配输入返回对应响应,无匹配则返回默认值
        return self.input_response_map.get(prompt, "默认测试响应")

# 使用示例
llm = CustomFakeLLM(
    input_response_map={
        "what is 2.2 + 2.22?": "Action: python_repl_ast\nAction Input: print(2.2 + 2.22)",
        "what is 3*5?": "Action: python_repl_ast\nAction Input: print(3*5)",
        "hello": "Final Answer: Hello there!"
    }
)

2. 模拟流式输出

若需要测试流式响应逻辑,自定义支持流式输出的Fake LLM:

from langchain.llms.base import LLM
from typing import Iterator, List, Optional

class StreamingFakeLLM(LLM):
    response: str = ""
    
    @property
    def _llm_type(self) -> str:
        return "streaming-fake"
    
    def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
        return self.response
    
    def _stream(self, prompt: str, stop: Optional[List[str]] = None) -> Iterator[str]:
        # 逐字符返回,模拟流式输出效果
        for char in self.response:
            yield char

# 使用示例
llm = StreamingFakeLLM(response="Final Answer: 4.42")
for chunk in llm.stream("what is 2.2 + 2.22?"):
    print(chunk, end="")

3. 动态生成响应模板

针对Agent的工具调用测试,预定义响应模板,根据输入参数动态填充内容,避免硬编码:

from langchain.llms.fake import FakeListLLM

def get_calculation_responses(num1: float, num2: float, operator: str):
    result = eval(f"{num1}{operator}{num2}")
    return [
        f"Action: python_repl_ast\nAction Input: print({num1}{operator}{num2})",
        f"Final Answer: {result}"
    ]

# 使用示例
res = get_calculation_responses(2.2, 2.22, "+")
llm = FakeListLLM(responses=res)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 12:21:24