自定义输出格式
默认情况下,代理返回纯文本输出。但你可以定义一个结构化的输出格式,以便简化后续处理。
自定义输出格式
通过这个示例,你可以定义代理应返回的输出格式。
代码示例
from pydantic import BaseModel# 定义输出格式,使用 Pydantic 模型class Post(BaseModel):post_title: strpost_url: strnum_comments: inthours_since_post: intclass Posts(BaseModel):posts: List[Post]controller = Controller(output_model=Posts)async def main():task = '访问 Hacker News 的 Show HN 页面,并获取前 5 篇帖子'model = ChatOpenAI(model='gpt-4o')agent = Agent(task=task, llm=model, controller=controller)history = await agent.run()result = history.final_result()if result:parsed: Posts = Posts.model_validate_json(result)for post in parsed.posts:print('\n--------------------------------')print(f'标题: {post.post_title}')print(f'链接: {post.post_url}')print(f'评论数: {post.num_comments}')print(f'发布时长 (小时): {post.hours_since_post}')else:print('无结果')if __name__ == '__main__':asyncio.run(main())
说明
Post类定义了每个帖子的结构,包括标题、链接、评论数和发布时间(小时数)。Posts类是Post的列表,用于存储多个帖子的信息。Controller通过output_model=Posts指定了自定义输出格式。- 在
main()函数中,代理执行任务并返回结果,然后使用Posts.model_validate_json(result)解析 JSON 数据。 - 最后,遍历解析后的数据并打印结果。
