Skip to main content
Riza 代码解释器是一个基于 WASM 的隔离环境,用于运行 AI agent 生成的 Python 或 JavaScript 代码。
在本笔记本中,我们将创建一个使用 Python 解决 LLM 无法独立解决问题的 agent 示例: 计算单词”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 模型初始化 agent。
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.