使用OpenAI Agents SDK打造你的首个API调用代理:构建交互式天气助手应用
随着大型语言模型(LLMs)的崛起,代理型人工智能(Agentic AI)成为一个备受关注的新趋势。为了帮助科技爱好者和开发者更好地理解和掌握这一新兴领域,作者分享了自己的学习经验和实践过程,重点介绍了基于OpenAI Agents SDK框架的开发方法。从个人背景来看,作者拥有数据与分析的专业背景,他认为熟悉这一领域对于日常工作以及未来的流程变革具有重要意义。 初探Agentic AI:第一个API调用代理 在这篇文章中,作者首先介绍了如何使用OpenAI Agents SDK来搭建一个基本的代理,然后逐步增强其功能,使其能够通过API获取实时天气数据,并最终将所有功能整合到一个简单的Streamlit用户界面中,方便用户交互查询。 环境设置 作者建议创建一个requirements.txt文件,列出必需的包: openai-agents streamlit 接下来,设置一个虚拟环境并安装这些包: python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate pip install -r requirements.txt 还需获取并配置OpenAI的API密钥,将其存储在.env文件中: OPENAI_API_KEY=your_openai_key_here 基本代理 首先,作者创建了一个名为01-single-agent.py的Python脚本,导入必要的库并定义了一个名为“Weather Assistant”的基本代理: ```python from agents import Agent, Runner import asyncio from dotenv import load_dotenv load_dotenv() agent = Agent( name="Weather Assistant", instructions="You provide accurate and concise weather updates based on user queries in plain language." ) ``` 接着,作者编写了一个异步函数run_agent,用以运行代理并处理用户的查询: python async def run_agent(): result = await Runner.run(agent, "What's the weather like today in Jakarta?") print(result.final_output) 最后,在脚本入口处添加执行函数的代码: python if __name__ == "__main__": asyncio.run(run_agent()) 运行该脚本后,由于代理仅依赖于训练数据,而没有访问实时数据的能力,因此它可能无法提供最新的天气信息或产生幻觉回答。 使用工具实现实时数据查询 为了解决上述问题,作者引入了“工具”(Tools)的概念,允许代理调用外部API来获取实时数据。文中选择的API是Open-Meteo,提供免费的非商业天气数据服务。首先,定义一个调用Open-Meteo API的函数: python @function_tool def get_current_weather(latitude: float, longitude: float) -> dict: """ Fetches current weather data for a given location using the Open-Meteo API. """ try: url = "https://api.open-meteo.com/v1/forecast" params = { "latitude": latitude, "longitude": longitude, "current": "temperature_2m,relative_humidity_2m,dew_point_2m,apparent_temperature,precipitation,weathercode,windspeed_10m,winddirection_10m", "timezone": "auto" } response = requests.get(url, params=params) response.raise_for_status() return response.json() except requests.RequestException as e: return {"error": f"Failed to fetch weather data: {e}"} 接下来,创建一个能够使用工具的代理,并在调用API后由LLM进一步处理数据: python weather_specialist_agent = Agent( name="Weather Specialist Agent", instructions="You provide accurate and concise weather updates based on user queries in plain language.", tools=[get_current_weather], tool_use_behavior="run_llm_again" ) 用户界面 为了使应用更加用户友好,作者使用Streamlit构建了一个简单的用户界面。用户可以通过输入框提问关于天气的问题,并点击按钮获取回答。以下是完整的用户界面脚本(03-tooluse-agent-app.py): ```python from agents import Agent, Runner, function_tool import asyncio import streamlit as st from dotenv import load_dotenv import requests load_dotenv() @function_tool def get_current_weather(latitude: float, longitude: float) -> dict: """ Fetches current weather data for a given location using the Open-Meteo API. """ try: url = "https://api.open-meteo.com/v1/forecast" params = { "latitude": latitude, "longitude": longitude, "current": "temperature_2m,relative_humidity_2m,dew_point_2m,apparent_temperature,precipitation,weathercode,windspeed_10m,winddirection_10m", "timezone": "auto" } response = requests.get(url, params=params) response.raise_for_status() return response.json() except requests.RequestException as e: return {"error": f"Failed to fetch weather data: {e}"} weather_specialist_agent = Agent( name="Weather Specialist Agent", instructions=""" You are a weather assistant agent. Given current weather data (including temperature, humidity, wind speed/direction, precipitation, and weather codes), provide: 1. A clear and concise explanation of the current weather conditions. 2. Practical suggestions or precautions for outdoor activities, travel, health, or clothing based on the data. 3. If any severe weather is detected (e.g., heavy rain, thunderstorms, extreme heat), highlight necessary safety measures. Format your response in two sections: Weather Summary: - Briefly describe the weather in plain language. Suggestions: - Offer actionable advice relevant to the weather conditions. """, tools=[get_current_weather], tool_use_behavior="run_llm_again" ) async def run_agent(user_input: str): result = await Runner.run(weather_specialist_agent, user_input) return result.final_output def main(): st.title("Weather Assistant") user_input = st.text_input("Ask about the weather:") if st.button("Get Weather Update"): with st.spinner("Thinking..."): if user_input: agent_response = asyncio.run(run_agent(user_input)) st.write(agent_response) else: st.write("Please enter a question about the weather.") if name == "main": main() ``` 运行此脚本后,用户可以输入城市名称并获取实时天气信息。例如,询问雅加达当前的天气情况,代理会返回清晰的天气摘要及实用建议。 结论 通过这篇文章,作者展示了如何使用OpenAI Agents SDK构建一个能够调用API获取实时天气数据的代理,并通过Streamlit用户界面与用户互动。这个过程不仅提高了代理的实用性,还展示了LLM在集成外部工具后的强大能力。在下一篇中,作者将探讨多代理协作的可能性及其带来的优势。 行业评价与公司背景 OpenAI Agents SDK 是一个基于 Python 的框架,旨在简化代理型 AI 系统的开发。行业专家认为,这一框架不仅降低了入门门槛,还为企业和个人提供了探索 AI 新功能的机会。通过结合外部工具,代理型 AI 能够更好地应对复杂任务和实时需求。Streamlit 则是一个流行的开源库,主要用于快速开发数据驱动的 web 应用程序。这篇文章的完整代码可在以下 GitHub 仓库中找到:agentic-ai-weather | GitHub Repository。如果想直接体验应用效果,还可以访问已部署的 Streamlit 应用:Weather Assistant Streamlit。