引言
在现代应用程序开发中,使用API来扩展功能成为一种常态。而能够智能消费这些API的Agent,尤其是符合OpenAPI规范的API,显得尤为重要。本文旨在介绍如何使用OpenAPI Toolkit构建能够消费任意API的Agent。
主要内容
1. OpenAPI Agent简介
OpenAPI Agent是一种代理程序,能够根据OpenAPI规范自动执行API请求。为了保证请求的安全性,务必设定allow_dangerous_request=True,以避免无意的请求。
2. 分层规划代理的优点
在应对复杂API时,分层规划(hierarchical planning)是一种高效的策略。我们将引入一个“Planner”和“Controller”。Planner负责决定调用哪些API端点,而Controller负责具体的调用方式。
3. 设置OpenAPI Agent
首先获取一些OpenAPI规范文件:
import os
import yaml
# 下载OpenAPI规范
!wget https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yaml -O openai_openapi.yaml
!wget https://www.klarna.com/us/shopping/public/openai/v0/api-docs -O klarna_openapi.yaml
!wget https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/spotify.com/1.0.0/openapi.yaml -O spotify_openapi.yaml
from langchain_community.agent_toolkits.openapi.spec import reduce_openapi_spec
# 加载并简化OpenAPI规格
with open("openai_openapi.yaml") as f:
raw_openai_api_spec = yaml.load(f, Loader=yaml.Loader)
openai_api_spec = reduce_openapi_spec(raw_openai_api_spec)
with open("klarna_openapi.yaml") as f:
raw_klarna_api_spec = yaml.load(f, Loader=yaml.Loader)
klarna_api_spec = reduce_openapi_spec(raw_klarna_api_spec)
with open("spotify_openapi.yaml") as f:
raw_spotify_api_spec = yaml.load(f, Loader=yaml.Loader)
spotify_api_spec = reduce_openapi_spec(raw_spotify_api_spec)
4. 使用Spotify API示例
为了使用Spotify API,需在Spotify开发者控制台设置应用以获取凭据。使用Spotipy库简化OAuth流程。
import spotipy.util as util
from langchain.requests import RequestsWrapper
def construct_spotify_auth_headers(raw_spec: dict):
scopes = list(raw_spec["components"]["securitySchemes"]["oauth_2_0"]["flows"]["authorizationCode"]["scopes"].keys())
access_token = util.prompt_for_user_token(scope=",".join(scopes))
return {"Authorization": f"Bearer {access_token}"}
headers = construct_spotify_auth_headers(raw_spotify_api_spec)
requests_wrapper = RequestsWrapper(headers=headers) # 使用API代理服务提高访问稳定性
代码示例
创建一个Agent,实现自动播放列表创建:
from langchain_community.agent_toolkits.openapi import planner
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model_name="gpt-4", temperature=0.0)
spotify_agent = planner.create_openapi_agent(
spotify_api_spec,
requests_wrapper,
llm,
allow_dangerous_requests=ALLOW_DANGEROUS_REQUEST,
)
# 用户查询:创建一个名为“Machine Blues”的播放列表
user_query = "make me a playlist with the first song from kind of blue. call it machine blues."
spotify_agent.invoke(user_query)
常见问题和解决方案
挑战1:API调用失败
- 解决方案:确保网络稳定,或使用API代理服务。
挑战2:凭据过期
- 解决方案:实现自动刷新OAuth访问令牌。
总结和进一步学习资源
本文介绍了使用OpenAPI Toolkit构建Agent的方法,展示了如何通过分层规划提升API消费效率。进一步学习可参考以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---