首页
/ 使用Strands Agent与OpenAI模型构建智能代理的入门指南

使用Strands Agent与OpenAI模型构建智能代理的入门指南

2025-06-03 05:35:34作者:范靓好Udolf

概述

Strands Agent是一个采用模型驱动方法的SDK,能够帮助开发者用少量代码构建和运行AI代理。该框架支持多种模型提供商,可以灵活地部署在任何环境中。本文将重点介绍如何通过Strands Agent SDK集成OpenAI模型(以Azure托管的gpt-4.1-mini为例)来构建一个具备天气查询和时间查询功能的智能代理。

技术架构解析

Strands Agent采用了简洁而强大的架构设计:

  1. 模型层:通过LiteLLM统一接口支持多种LLM提供商
  2. 工具层:可扩展的工具集,为代理提供特定功能
  3. 代理核心:协调模型推理与工具调用的中枢系统

这种分层架构使得开发者可以灵活地替换模型提供商或添加新工具,而不影响整体系统稳定性。

环境准备

基础要求

  • Python 3.10或更高版本
  • Azure账户权限
  • 可访问gpt-4.1-mini模型的服务端点

依赖安装

首先需要安装必要的Python包:

pip install -r requirements.txt

核心代码实现

1. 导入依赖

import os
from datetime import datetime
from datetime import timezone as tz
from typing import Any
from zoneinfo import ZoneInfo

from strands import Agent, tool
from strands.models.litellm import LiteLLMModel

2. 配置Azure API密钥

os.environ["AZURE_API_KEY"] = "<YOUR_API_KEY>"
os.environ["AZURE_API_BASE"] = "<YOUR_API_BASE>"
os.environ["AZURE_API_VERSION"] = "<YOUR_API_VERSION>"

3. 定义工具函数

我们创建两个示例工具来展示代理能力:

@tool
def current_time(timezone: str = "UTC") -> str:
    """获取指定时区的当前时间"""
    if timezone.upper() == "UTC":
        timezone_obj: Any = tz.utc
    else:
        timezone_obj = ZoneInfo(timezone)
    return datetime.now(timezone_obj).isoformat()

@tool
def current_weather(city: str) -> str:
    """获取指定城市的天气情况(示例返回固定值)"""
    return "sunny"

4. 配置模型参数

model = "azure/gpt-4.1-mini"
litellm_model = LiteLLMModel(
    model_id=model, params={"max_tokens": 32000, "temperature": 0.7}
)

5. 创建代理实例

system_prompt = "You are a simple agent that can tell the time and the weather"
agent = Agent(
    model=litellm_model,
    system_prompt=system_prompt,
    tools=[current_time, current_weather],
)

测试与验证

执行查询

results = agent("What time is it in Seattle? And how is the weather?")

分析结果

  1. 查看完整的对话历史:
agent.messages
  1. 检查资源使用情况:
results.metrics

最佳实践建议

  1. 模型选择:根据任务复杂度选择合适的模型,简单任务可使用轻量级模型
  2. 温度参数:对于确定性任务,建议降低temperature值(如0.2-0.5)
  3. 工具设计:保持工具函数单一职责,提供清晰的文档字符串
  4. 错误处理:在实际应用中应增强工具函数的错误处理能力

扩展思考

通过这个基础示例,开发者可以进一步探索:

  • 集成更复杂的工具链(如数据库查询、API调用)
  • 实现多代理协作系统
  • 添加记忆机制实现上下文感知
  • 开发自定义监控和日志系统

Strands Agent的模块化设计为这些高级功能提供了良好的扩展基础。

登录后查看全文
热门项目推荐