跳到主要内容
Riza 代码解释器是一个基于 WASM 的隔离环境,用于运行由 AI 代理生成的 Python 或 JavaScript 代码。
在本 Notebook 中,我们将创建一个代理示例,该代理使用 Python 解决 LLM 无法独立解决的问题:计算单词“strawberry”中“r”的个数。 开始之前,请从 Riza 控制面板获取一个 API 密钥。有关更多指南和完整的 API 参考,请访问 Riza 代码解释器 API 文档 确保已安装必要的依赖项。
pip install -qU langchain-community rizaio
将您的 API 密钥设置为环境变量。
%env ANTHROPIC_API_KEY=<your_anthropic_api_key_here>
%env RIZA_API_KEY=<your_riza_api_key_here>
from langchain_community.tools.riza.command import ExecPython
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_anthropic import ChatAnthropic
from langchain_core.prompts import ChatPromptTemplate
初始化 ExecPython 工具。
tools = [ExecPython()]
使用 Anthropic 的 Claude Haiku 模型初始化一个代理。
llm = ChatAnthropic(model="claude-haiku-4-5-20251001", temperature=0)

prompt_template = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "You are a helpful assistant. Make sure to use a tool if you need to solve a problem.",
        ),
        ("human", "{input}"),
        ("placeholder", "{agent_scratchpad}"),
    ]
)

agent = create_tool_calling_agent(llm, tools, prompt_template)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# Ask a tough question
result = agent_executor.invoke({"input": "how many rs are in strawberry?"})
print(result["output"][0]["text"])
> Entering new AgentExecutor chain...

Invoking: `riza_exec_python` with `{'code': 'word = "strawberry"\nprint(word.count("r"))'}`
responded: [{'id': 'toolu_01JwPLAAqqCNCjVuEnK8Fgut', 'input': {}, 'name': 'riza_exec_python', 'type': 'tool_use', 'index': 0, 'partial_json': '{"code": "word = \\"strawberry\\"\\nprint(word.count(\\"r\\"))"}'}]

3
[{'text': '\n\nThe word "strawberry" contains 3 "r" characters.', 'type': 'text', 'index': 0}]

> Finished chain.


The word "strawberry" contains 3 "r" characters.

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.