更新时间:2026-04-16 GMT+08:00
分享

Tools SDK

场景介绍

支持CodeInterpreter生命周期管理和Session生命周期管理。

原理优势

用户空间已存在代码解释器时,SDK支持快速拉起代码解释器会话

with code_session("your_region","your_code_interpreter_name") as code_client:
    response = code_client.invoke(
        operate_type="your_operate_type",
        arguments={your_arguments}
    )

前提条件

  • 已开通AgentArts。
  • 已安装Python,且版本不低于3.10。查看Python版本的命令示例:python --version。
  • 拥有华为云AgentArts Tools的访问权限。
  • 拥有创建和管理Tools资源所需的权限。

操作步骤

  1. 执行如下命令或者使用pip install方式进行环境准备。

    # Clone the SDK (use HTTPS or SSH)
    git clone -b release_opensource https://codehub-dg-g.huawei.com/applicationplatform/ServiceStage/AgentRun/AgentRunSDK.git
    # Use Virtual Environment (Recommended)
    python -m venv venv
    source venv/bin/activate
    # Install SDK from the SDK parent directory where pyproject.toml is 
    cd AgentRunSDK
    make install

    pip install方式:

    pip install agentarts-sdk

  2. 配置华为云访问凭证:

    • 管理面(控制面):使用AK/SK认证,通过HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK设置环境变量。获取AK/SK请参考如何获取华为云AK/SK
    • 数据面:使用API_KEY认证,通过HUAWEICLOUD_SDK_CODE_INTERPRETER_API_KEY设置环境变量(可选,也可作为客户端参数传入),SDK内部自动处理。获取API_KEY请参考如何获取沙箱工具的API_KEY

  3. 创建代码解释器

    from agentarts.sdk.tools import CodeInterpreter
    
    client = CodeInterpreter(region="your_region")
    code_interpreter = client.create_code_interpreter(
            name="your_code_interpreter_name",
            api_key_name="your_api_key_name"
        )

  4. 配置工具,这里以代码执行工具为例。用户自定义region信息和需要使用的代码解释器,代码解释器名称和API_KEY一一对应。

    from agentarts-sdk.tools import code_session
    
    @tool
    def execute_python_tool(code: str, description: str = "") -> str | None:
        with code_session("your_region", "your_code_interpreter_name") as code_client:
            response = code_client.invoke(
                operate_type="execute_code",
                arguments={
                    "code": code,
                    "language": "python",
                    "clear_context": False
                }
            )
    
        return json.dumps(response["result"])

  5. 配置集成步骤4中配置的工具,以如下执行代码为例。

    # 创建Agent
    llm = ChatOpenAI(
        model="DeepSeek-V3",
        api_key=os.environ.get("MODEL_API_KEY", ""),
        base_url=os.environ.get("BASE_URL", ""),
        max_tokens=1000,
        temperature=0.7,
    )
    # 创建工具列表
    tools = [execute_python_tool]
    # 工具绑定Agent
    llm.bind_tools(tools)

相关文档