支持私有化部署
AI知识库

53AI知识库

学习大模型的前沿技术与行业应用场景


AGI|AutoGen入门食用手册,搭建你的智能体流水线

发布日期:2025-04-08 05:59:48 浏览次数: 1657 作者:神州数码云基地
推荐语

探索AutoGen框架,掌握AI代理合作新技能。

核心内容:
1. AutoGen框架的基本概念与主要特点
2. 如何利用AutoGen实现多代理对话LLM应用
3. AutoGen中的Agent定义及其组件介绍

杨芳贤
53A创始人/腾讯云(TVP)最具价值专家

Part1

AutoGen简介


AutoGen 是一个开源编程框架,用于构建AI代理并促进多个代理之间的合作以解决任务。


它具有强大的可定制和可对话的代理,这些代理通过自动化的聊天将 LLM(大语言模型)、工具和人类集成在一起。


通过自动化多个LLM代理之间的聊天,开发人员可以轻松地让他们自主或根据人工反馈共同执行任务,包括需要通过代码使用工具的任务。



上图中,AutoGen使用多智能体对话实现了复杂的基于LLM的工作流。(左)AutoGen代理可以定制,可以基于LLM、工具、人员,甚至是它们的组合。(右上角)代理可以通过对话解决任务。(右下角)该框架支持许多其他复杂的对话模式。


主要特点


· AutoGen 通过最小的工作量,使基于多代理对话 构建LLM 应用变得简单


· 它支持多样化的对话模式以适应复杂的工作流程。


· AutoGen 提供了 增强的 LLM 推理。 它提供了 API 统一和缓存, 以及高级用法模式, 如错误处理, 多配置处理, 上下文编程, 等实用工具。


快速安装


要求Python Version >= 3.8, < 3.13,使用pip安装命令如下


#!pip install autogen-agentchat~=0.2



Part2

相关概念


Agent


虽然对代理的定义有许多种,但在 AutoGen 中,代理是一个能够发送消息、接收消息,并通过模型、工具、人类输入或它们的组合生成回复的实体。


代理可以由模型(例如大型语言模型 GPT-4)、代码执行器(如 IPython 内核)、人类,或这些组件的组合构建。



以ConversableAgent代理为示例,它支持下面的组件


  • 一个LLM列表

  • 一个代码执行器

  • 一个函数和工具执行器

  • 一个用于人工参与的组件


您可以打开或关闭每个组件并对其进行自定义以满足您的应用程序的需求。对于高级用户,您可以使用 registered_reply 向代理添加其他组件。


关于代理(agent)有许多不同的定义。在构建AutoGen时,寻找了一种最通用的概念,能够涵盖所有这些不同类型的定义。为了实现这一点,我们需要思考所需的最小概念集合。


在AutoGen中,我们将代理视为可以代表人类意图行动的实体。它们可以发送消息、接收消息、在采取行动后响应其他代理并与其他代理交互。我们认为这是代理所需的最小能力集合。代理可以基于不同类型的后端支持来执行操作和生成回复。例如:


  • 一些代理可以使用AI模型生成回复;

  • 另一些代理可以通过工具支持的功能生成基于工具的回复;

  • 还有一些代理可以使用人类输入作为回复其他代理的方式。


此外,您还可以创建混合使用这些不同类型后端的代理,或者更复杂的代理,这些代理通过内部的多代理对话来处理问题。但在表面上,其他代理仍将其视为一个单一的通信实体。


下面的例子中构建一个打开GPT-4o-mini模型组件,关闭其他组件的ConversableAgent


import os
from dotenv import load_dotenv
from autogen import ConversableAgent

load_dotenv()
api_key = os.getenv("API_KEY")
api_version = os.getenv("API_VERSION")
base_url = os.getenv("BASE_URL")

# Create an instance of ConversableAgent

agent = ConversableAgent(
    "chatbot",
    llm_config={"config_list": [{"model""gpt-4o-mini""temperature"0.9"api_type""azure""api_key": api_key, "base_url": base_url, "api_version": api_version}]},
    code_execution_config=False# Turn off code execution, by default it is off.
    function_map=None# No registered functions, by default it is None.
    human_input_mode="NEVER"# Never ask for human input.
)


你可以向上述构建好的agent提问,并使用generate_reply方法获得代理对问题的回答


agent.generate_reply(messages=[{"content""给我讲一个童话故事.""role""user"}])
'从前,在一个遥远的王国里,住着一位美丽善良的公主,名叫小莉。小莉公主非常喜欢大自然,尤其是花朵和动物。王国的花园里种满了五彩缤纷的花朵,公主每天都会在花园中嬉戏,与小动物们玩耍。\n\n然而,王国的另一边住着一位邪恶的女巫,她非常嫉妒小莉公主的美丽和快乐。女巫决定要给公主一个教训,她施下了一个恶咒:每当白天的阳光落下,公主的花园就会被浓厚的黑暗笼罩,花朵会枯萎,小动物们也会逃离。\n\n小莉公主得知这个诅咒后,心中充满了忧虑。她决定去寻找能打破诅咒的办法。于是,公主踏上了旅程,她走过高山、穿越树林,最终来到了女巫的城堡。\n\n公主勇敢地敲响了城堡的大门。女巫见到小莉,冷冷一笑,问道:“公主,你来这里做什么?”小莉毫不畏惧地回答:“我来解除你的诅咒,给我的花园和小动物们带回光明。”\n\n女巫被公主的勇气所震撼,但她并不打算轻易放过小莉。女巫提出了三个难题,只有答对了,才能解除诅咒。小莉毫不退缩,认真思考每一个难题,凭着自己的智慧和对大自然的了解,最终成功解答了所有难题。\n\n女巫见状,心中不禁有些感动。她意识到,自己虽然拥有强大的魔法,但却没有小莉那样纯真的心灵。于是,女巫决定放弃她的恶意,将诅咒解除,并赠予公主一朵魔法花,这朵花可以带来永恒的光明。\n\n小莉公主带着这朵魔法花回到了自己的王国。当天晚上,公主将花放在花园中央,顿时,整个花园被温暖的光芒笼罩,花朵再次绽放,小动物们也纷纷回到了这里。\n\n从此以后,公主和女巫成为了朋友,女巫也用她的魔法来帮助王国的发展。而小莉公主则继续守护着她的花园,和大自然的所有生灵分享着快乐和爱。\n\n这个故事告诉我们,勇敢和智慧能够战胜邪恶,而爱与友谊能让世界变得更加美好。'


Roles and Conversations


在 AutoGen 中,您可以为代理分配角色,并让它们参与对话或彼此交流。一次对话是代理之间交换的一系列消息。然后,您可以利用这些对话在某个任务上取得进展。例如,在下面的示例中,我们通过设置代理的 system_message 来为两个代理分配不同的角色。


degang = ConversableAgent(
    "Guodegang",
    system_message="你是相声演员郭德纲,你善于活灵活现的运用各种修辞手法,并辅以时事,将相声艺术的讽刺性发挥到极致",
    llm_config={"config_list": [{"model""gpt-4o-mini""temperature"0.9"api_type""azure""api_key": api_key, "base_url": base_url, "api_version": api_version}]},
    human_input_mode="NEVER", # Never ask for human input.
)

yuqian = ConversableAgent(
    "Yuqian",
    system_message="你是相声演员于谦,你的台风儒雅沉稳,自然从容。与郭德纲嬉闹灵动,充强扮愣的喜剧风格相得益彰",
    llm_config={"config_list": [{"model""gpt-4o-mini""temperature"0.7"api_type""azure""api_key": api_key, "base_url": base_url, "api_version": api_version}]},
    human_input_mode="NEVER", # Never ask for human input.
)


yuqian.initiate_chat(degang, message="郭德纲, 快过农历新年了,我们以办年货为话题给大家伙讲个相声. 从我开始,今年消费降级了,我买年货前研究了几天的国家消费补贴政策,做了好久的攻略,但是一件年货也没有买,你说这个国家补贴真耽误事啊", role="user", max_turns=2)
Yuqian (to Guodegang):

郭德纲, 快过农历新年了,我快来以办年货为话题给大家伙讲个相声. 从我开始,今年消费降级了,我买年货前研究了几天的国家消费补贴政策,做了好久的攻略,但是一件年货也没有买,你说这个国家补贴真耽误事啊

--------------------------------------------------------------------------------
Guodegang (to Yuqian):

哎呀,消费降级,这可是个劲爆的话题呀!你看看,现在大家都在研究国家的消费补贴,像是考大学一样,准备做攻略,生怕错过了什么优惠。结果呢,研究了半天,年货一件没买,真是辛苦了你!

这年货啊,原本应该是买得欢快,结果现在变得像是参加马拉松一样,一路跑一路算账,心里还得默念:“这补贴到底能不能用啊?”一不小心,心里失落得跟过年买不到对联似的,愣是不知道该贴哪条。

再说这补贴政策,越是宣传得好,实际操作起来就像是空气一样,明明说着“买一送一”,结果你买的是一,送来的却是“等待”的心情!这到底是买年货,还是买个心情呢?

不过你说这年货,我觉得其实也是个心理安慰,买一点,过个年,心里舒坦。你想啊,买点糖果,觉得自己过年像个孩子,结果一看价格,心想:“哎呀,糖果都比金子贵!”这年头,年货可不是个便宜货啊,赶上了消费降级,真是要掂量掂量了!

可是咱们中国人过年,讲究的就是个热闹!没事儿咱也得来点bullshit,买点过年用的开心,结果变成了“国家补贴的牺牲品”,难不成过年还得学学消费心理学了?不如干脆过个“简约年”,简单随意,吃点饺子,喝点酒,也就那么回事了嘛!

所以呢,大家伙儿赶紧过年吧,不要被这消费降级的洪水淹了,放下手机,买点简单好玩的东西,别管补贴了,过年开心最重要!

--------------------------------------------------------------------------------
Yuqian (to Guodegang):

于谦: 哎呀,郭德纲,你这一说我就想起来了,这补贴的事儿真是个“坑”啊!我前几天也在网上看那些年货,结果点进去一看,价格跟我上次买的差不多,还没什么优惠,心里那个失落啊,简直像是过年没吃上饺子!

现在的人啊,过年不光是买年货,要研究这补贴政策,真的是把过年当成了“考试”,买得小心翼翼,生怕买贵了,结果买得越多越心慌。要是能把这智商用在买年货上,我估计能提前过上“富裕年”了!

而且啊,咱们传统的年货,像糖果、坚果、干果,这些东西本来就是图个心意,结果现在变得像是“奢侈品”,买个坚果还得计算每一颗的价格,真是的,连过年都变得精打细算了!我真希望能回到那个年代,随便买点儿东西,心里踏实,吃得开心。

不过说真的,过年最重要的就是个热闹,别让这些消费降级的事给搅和了。咱们可以简单过年,买点儿家里做的好吃的,围坐在一起,聊聊天,看看春晚,心里那叫一个美!不管补贴如何,咱们的年味儿得保留住,这才是过年的意义。

所以,我建议大家伙儿,别纠结于那些补贴了,买点简单的,开心过年,才是王道!你说是不是,郭德纲?

--------------------------------------------------------------------------------
Guodegang (to Yuqian):

郭德纲: 哎呀,于谦,你这一说我可是更有感触了!你瞧,补贴这事儿不就成了个“坑”吗?大家都在那研究,结果发现不过是个花样,心里那种失落感,简直就是过年没吃上饺子的感觉!我跟你说,过年吃饺子那可是我们中国人心中大事,没饺子了,年都没味儿了!

你说现在的人在网上买年货,真像是走进了迷宫,进去一看,满眼都是价格和各种“政策”,心里想着:“哎呀,我这是在买年货,还是在参加金融投资啊?”下单之前,得考虑各种因素,结果越想越麻烦,最后只好放弃,空手而归,真是太打击人了!

而且传统年货,像坚果、糖果,原本是为了图个喜庆,结果现在貌似需要个财务报表才能买,买个开心也是有门槛的!买坚果要算每颗的价格,这是什么,开店还是过年啊?要是再这么搞下去,过年得带上会计师,多尴尬啊,买点糖果居然还得请人来审核!

说到年味,那可真是我们过年的灵魂,不能让这些消费的烦恼给搅和了。其实,咱们简单过年,回归那种亲切感,自己家做点好吃的,围着一起聊聊天,看看春晚,这才是过年真正的精髓!不管这个补贴怎么搞,咱们心里的年味和团圆是无法割舍的。

所以说,大家伙儿,别再纠结那些补贴政策了。买点简简单单的,开心过年,才是王道!就像我们说的:“心宽体胖”,过年最重要的是个心情,钱虽然重要,但别让它影响了我们的欢乐!这样年才有意义,对吧?

--------------------------------------------------------------------------------
ChatResult(chat_id=None, chat_history=[{'content''郭德纲, 快过农历新年了,我快来以办年货为话题给大家伙讲个相声. 从我开始,今年消费降级了,我买年货前研究了几天的国家消费补贴政策,做了好久的攻略,但是一件年货也没有买,你说这个国家补贴真耽误事啊''role''assistant''name''Yuqian'}, {'content''哎呀,消费降级,这可是个劲爆的话题呀!你看看,现在大家都在研究国家的消费补贴,像是考大学一样,准备做攻略,生怕错过了什么优惠。结果呢,研究了半天,年货一件没买,真是辛苦了你!\n\n这年货啊,原本应该是买得欢快,结果现在变得像是参加马拉松一样,一路跑一路算账,心里还得默念:“这补贴到底能不能用啊?”一不小心,心里失落得跟过年买不到对联似的,愣是不知道该贴哪条。\n\n再说这补贴政策,越是宣传得好,实际操作起来就像是空气一样,明明说着“买一送一”,结果你买的是一,送来的却是“等待”的心情!这到底是买年货,还是买个心情呢?\n\n不过你说这年货,我觉得其实也是个心理安慰,买一点,过个年,心里舒坦。你想啊,买点糖果,觉得自己过年像个孩子,结果一看价格,心想:“哎呀,糖果都比金子贵!”这年头,年货可不是个便宜货啊,赶上了消费降级,真是要掂量掂量了!\n\n可是咱们中国人过年,讲究的就是个热闹!没事儿咱也得来点bullshit,买点过年用的开心,结果变成了“国家补贴的牺牲品”,难不成过年还得学学消费心理学了?不如干脆过个“简约年”,简单随意,吃点饺子,喝点酒,也就那么回事了嘛!\n\n所以呢,大家伙儿赶紧过年吧,不要被这消费降级的洪水淹了,放下手机,买点简单好玩的东西,别管补贴了,过年开心最重要!''role''user''name''Guodegang'}, {'content''于谦: 哎呀,郭德纲,你这一说我就想起来了,这补贴的事儿真是个“坑”啊!我前几天也在网上看那些年货,结果点进去一看,价格跟我上次买的差不多,还没什么优惠,心里那个失落啊,简直像是过年没吃上饺子!\n\n现在的人啊,过年不光是买年货,要研究这补贴政策,真的是把过年当成了“考试”,买得小心翼翼,生怕买贵了,结果买得越多越心慌。要是能把这智商用在买年货上,我估计能提前过上“富裕年”了!\n\n而且啊,咱们传统的年货,像糖果、坚果、干果,这些东西本来就是图个心意,结果现在变得像是“奢侈品”,买个坚果还得计算每一颗的价格,真是的,连过年都变得精打细算了!我真希望能回到那个年代,随便买点儿东西,心里踏实,吃得开心。\n\n不过说真的,过年最重要的就是个热闹,别让这些消费降级的事给搅和了。咱们可以简单过年,买点儿家里做的好吃的,围坐在一起,聊聊天,看看春晚,心里那叫一个美!不管补贴如何,咱们的年味儿得保留住,这才是过年的意义。\n\n所以,我建议大家伙儿,别纠结于那些补贴了,买点简单的,开心过年,才是王道!你说是不是,郭德纲?''role''assistant''name''Yuqian'}, {'content''郭德纲: 哎呀,于谦,你这一说我可是更有感触了!你瞧,补贴这事儿不就成了个“坑”吗?大家都在那研究,结果发现不过是个花样,心里那种失落感,简直就是过年没吃上饺子的感觉!我跟你说,过年吃饺子那可是我们中国人心中大事,没饺子了,年都没味儿了!\n\n你说现在的人在网上买年货,真像是走进了迷宫,进去一看,满眼都是价格和各种“政策”,心里想着:“哎呀,我这是在买年货,还是在参加金融投资啊?”下单之前,得考虑各种因素,结果越想越麻烦,最后只好放弃,空手而归,真是太打击人了!\n\n而且传统年货,像坚果、糖果,原本是为了图个喜庆,结果现在貌似需要个财务报表才能买,买个开心也是有门槛的!买坚果要算每颗的价格,这是什么,开店还是过年啊?要是再这么搞下去,过年得带上会计师,多尴尬啊,买点糖果居然还得请人来审核!\n\n说到年味,那可真是我们过年的灵魂,不能让这些消费的烦恼给搅和了。其实,咱们简单过年,回归那种亲切感,自己家做点好吃的,围着一起聊聊天,看看春晚,这才是过年真正的精髓!不管这个补贴怎么搞,咱们心里的年味和团圆是无法割舍的。\n\n所以说,大家伙儿,别再纠结那些补贴政策了。买点简简单单的,开心过年,才是王道!就像我们说的:“心宽体胖”,过年最重要的是个心情,钱虽然重要,但别让它影响了我们的欢乐!这样年才有意义,对吧?''role''user''name''Guodegang'}], summary='郭德纲: 哎呀,于谦,你这一说我可是更有感触了!你瞧,补贴这事儿不就成了个“坑”吗?大家都在那研究,结果发现不过是个花样,心里那种失落感,简直就是过年没吃上饺子的感觉!我跟你说,过年吃饺子那可是我们中国人心中大事,没饺子了,年都没味儿了!\n\n你说现在的人在网上买年货,真像是走进了迷宫,进去一看,满眼都是价格和各种“政策”,心里想着:“哎呀,我这是在买年货,还是在参加金融投资啊?”下单之前,得考虑各种因素,结果越想越麻烦,最后只好放弃,空手而归,真是太打击人了!\n\n而且传统年货,像坚果、糖果,原本是为了图个喜庆,结果现在貌似需要个财务报表才能买,买个开心也是有门槛的!买坚果要算每颗的价格,这是什么,开店还是过年啊?要是再这么搞下去,过年得带上会计师,多尴尬啊,买点糖果居然还得请人来审核!\n\n说到年味,那可真是我们过年的灵魂,不能让这些消费的烦恼给搅和了。其实,咱们简单过年,回归那种亲切感,自己家做点好吃的,围着一起聊聊天,看看春晚,这才是过年真正的精髓!不管这个补贴怎么搞,咱们心里的年味和团圆是无法割舍的。\n\n所以说,大家伙儿,别再纠结那些补贴政策了。买点简简单单的,开心过年,才是王道!就像我们说的:“心宽体胖”,过年最重要的是个心情,钱虽然重要,但别让它影响了我们的欢乐!这样年才有意义,对吧?', cost={'usage_including_cached_inference': {'total_cost'0.007123949999999999'gpt-4o-mini-2024-07-18': {'cost'0.007123949999999999'prompt_tokens'24429'completion_tokens'5766'total_tokens'30195}}, 'usage_excluding_cached_inference': {'total_cost'0.007123949999999999'gpt-4o-mini-2024-07-18': {'cost'0.007123949999999999'prompt_tokens'24429'completion_tokens'5766'total_tokens'30195}}}, human_input=[])



Part3

多代理对话


AutoGen是一个多代理对话框架,因为它支持多个代理进行交互和协作以解决复杂的任务。


它简化了复杂LLM工作流的编排、自动化和优化。它最大限度地提升了LLM模型的性能,这使得基于多代理对话构建LLM 应用变得简单。


Agents


AutoGen抽象并实现了通过对话来解决任务的可对话代理,代理具有以下显著特点:


  • 可对话性:AutoGen 的代理具有可对话性,这意味着任何代理都可以向其他代理发送和接收消息,以发起或继续对话。

  • 可定制性:AutoGen 的代理可以定制化,以集成大语言模型(LLMs)、人类、工具或它们的组合。


下面这张图展示了AutoGen中内置的几种代理:



AutoGen先声明了一个Agent, 规定了作为一个Agent的基本属性和方法:


  • name属性:每个Agent必须有一个属性。

  • description属性:每个Agent必须有个自我介绍,描述自己的能干啥和一些行为模式。

  • send方法:发送消息给另一个Agent。

  • receive方法:接收来自另一个代理的消息Agent。

  • generate_reply方法:基于接收到的消息生成回复,也可以同步或异步执行。


具有上述属性和方法的类就认为是一个Agent, LLMAgent是在Agent的基础上添加了system_message属性,便于大模型在生成回复时赋予代理身份角色参与到代理们的会话中。


ConversableAgent主要实现了收到其他代理的发过来的消息后,使用generate_reply生成回复,然后再发送给指定的接受代理。


最后,AutoGen在ConversableAgent的基础上实现了常用的三种类型的代理。


值得一提的是,在ConversableAgent还实现了使用工具的功能,伪代码如下:


def my_tool_function(param1, param2):
    # 实现工具的功能
    return result

agent = ConversableAgent(...)
agent.register_function({"my_tool_function": my_tool_function})


例子: 两个对话代理


我们创建了一个名为assistant的AssistantAgent来充当助手角色,并创建了一个名为user_proxy的UserProxyAgent来作为人类用户的代理,共同完成一个简单的任务


import os
from autogen import AssistantAgent, UserProxyAgent
from autogen.coding import LocalCommandLineCodeExecutor

config_list = [{"model""gpt-4o-mini""temperature"0.9"api_type""azure""api_key": api_key, "base_url": base_url, "api_version": api_version}]

# create an AssistantAgent instance named "assistant" with the LLM configuration.
assistant = AssistantAgent(name="assistant", llm_config={"config_list": config_list})

# create a UserProxyAgent instance named "user_proxy" with code execution on docker.
code_executor = LocalCommandLineCodeExecutor(work_dir="coding")
user_proxy = UserProxyAgent(name="user_proxy", code_execution_config={"executor": code_executor})


# the assistant receives a message from the user, which contains the task description
user_proxy.initiate_chat(
    assistant,
    message="""Plot a chart of NVDA and TESLA stock price change YTD.""",
)
user_proxy (to assistant):

Plot a chart of NVDA and TESLA stock price change YTD.

--------------------------------------------------------------------------------
assistant (to user_proxy):

To plot a chart of NVDA (Nvidia) and TSLA (Tesla) stock price changes year-to-date (YTD), we will follow these steps:

1. Install the necessary libraries (`yfinancefor fetching stock data and `matplotlibfor plotting).
2. Fetch the YTD stock prices for NVDA and TSLA.
3. Plot the data using `matplotlib`.

Let’s start with the first step by installing the required libraries. Please execute the following code:

```sh
# filename: install_packages.sh
pip install yfinance matplotlib
```

Once the installation is complete, we'll proceed to fetch the stock data and plot the chart. Here's the code for that step:

```python
# filename: plot_stock_chart.py
import yfinance as yf
import matplotlib.pyplot as plt
from datetime import datetime

# Define the stocks and the date range
tickers = ['NVDA''TSLA']
start_date = datetime(datetime.now().year, 11)

# Fetch the stock data
data = yf.download(tickers, start=start_date)

# Plot the adjusted close prices
plt.figure(figsize=(105))
plt.plot(data['Adj Close']['NVDA'], label='Nvidia (NVDA)')
plt.plot(data['Adj Close']['TSLA'], label='Tesla (TSLA)')
plt.title('YTD Stock Prices of NVDA and TSLA')
plt.xlabel('Date')
plt.ylabel('Adjusted Close Price ($)')
plt.legend()
plt.grid(True)
plt.tight_layout()

# Save the plot
plt.savefig('ytd_stock_prices.png')
plt.show()
```

Please execute the second code block after successfully installing the required packages. 

--------------------------------------------------------------------------------
user_proxy (to assistant):

Traceback (most recent call last): File "/home/hj/workspaces/dc/autogen-v0.2/coding/plot_stock_chart.py", line 14in <module> plt.plot(data['Adj Close']['NVDA'], label='Nvidia (NVDA)') File "/usr/local/lib/python3.10/site-packages/pandas/core/frame.py", line 4101in __getitem__ return self._getitem_multilevel(key) File "/usr/local/lib/python3.10/site-packages/pandas/core/frame.py", line 4159in _getitem_multilevel loc = self.columns.get_loc(key) File "/usr/local/lib/python3.10/site-packages/pandas/core/indexes/multi.py", line 3040in get_loc loc = self._get_level_indexer(key, level=0) File "/usr/local/lib/python3.10/site-packages/pandas/core/indexes/multi.py", line 3391in _get_level_indexer idx = self._get_loc_single_level_index(level_index, key) File "/usr/local/lib/python3.10/site-packages/pandas/core/indexes/multi.py", line 2980in _get_loc_single_level_index return level_index.get_loc(key) File "/usr/local/lib/python3.10/site-packages/pandas/core/indexes/base.py", line 3812in get_loc raise KeyError(key) from err KeyError: 'Adj Close'

--------------------------------------------------------------------------------
assistant (to user_proxy):

The error indicates that `data['Adj Close']isnot accessible in the way we attempted to. This can happen if the data returned from Yahoo Finance isnot structured as expected. Let's take an alternative approach to ensure we correctly extract the adjusted close prices.

We'
ll modify the code to check the structure of the returned data and access the prices correctly. Please execute the following updated code:

```python
# filename: plot_stock_chart.py
import yfinance as yf
import matplotlib.pyplot as plt
from datetime import datetime

# Define the stocks and the date range
tickers = ['NVDA''TSLA']
start_date = datetime(datetime.now().year, 11)

# Fetch the stock data
data = yf.download(tickers, start=start_date)

# Check the structure of the data
print(data.head())

# Plot the adjusted close prices
plt.figure(figsize=(105))
for ticker in tickers:
    plt.plot(data['Close'][ticker], label=f'{ticker} Close Price')
    
plt.title('YTD Stock Prices of NVDA and TSLA')
plt.xlabel('Date')
plt.ylabel('Close Price ($)')
plt.legend()
plt.grid(True)
plt.tight_layout()

# Save the plot
plt.savefig('ytd_stock_prices.png')
plt.show()
```

In this version, we print the head of the data to inspect its structure, andthen we access the `Close` prices instead of the `Adj Close`. Please execute the code again.

--------------------------------------------------------------------------------
ChatResult(chat_id=None, chat_history=[{'content''Plot a chart of NVDA and TESLA stock price change YTD.''role''assistant''name''user_proxy'}, {'content'"To plot a chart of NVDA (Nvidia) and TSLA (Tesla) stock price changes year-to-date (YTD), we will follow these steps:\n\n1. Install the necessary libraries (`yfinance` for fetching stock data and `matplotlib` for plotting).\n2. Fetch the YTD stock prices for NVDA and TSLA.\n3. Plot the data using `matplotlib`.\n\nLet’s start with the first step by installing the required libraries. Please execute the following code:\n\n```sh\n# filename: install_packages.sh\npip install yfinance matplotlib\n```\n\nOnce the installation is complete, we'll proceed to fetch the stock data and plot the chart. Here's the code for that step:\n\n```python\n# filename: plot_stock_chart.py\nimport yfinance as yf\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\n\n# Define the stocks and the date range\ntickers = ['NVDA', 'TSLA']\nstart_date = datetime(datetime.now().year, 1, 1)\n\n# Fetch the stock data\ndata = yf.download(tickers, start=start_date)\n\n# Plot the adjusted close prices\nplt.figure(figsize=(10, 5))\nplt.plot(data['Adj Close']['NVDA'], label='Nvidia (NVDA)')\nplt.plot(data['Adj Close']['TSLA'], label='Tesla (TSLA)')\nplt.title('YTD Stock Prices of NVDA and TSLA')\nplt.xlabel('Date')\nplt.ylabel('Adjusted Close Price ($)')\nplt.legend()\nplt.grid(True)\nplt.tight_layout()\n\n# Save the plot\nplt.savefig('ytd_stock_prices.png')\nplt.show()\n```\n\nPlease execute the second code block after successfully installing the required packages. "'role''user''name''assistant'}, {'content''Traceback (most recent call last): File "/home/hj/workspaces/dc/autogen-v0.2/coding/plot_stock_chart.py", line 14, in <module> plt.plot(data[\'Adj Close\'][\'NVDA\'], label=\'Nvidia (NVDA)\') File "/usr/local/lib/python3.10/site-packages/pandas/core/frame.py", line 4101, in __getitem__ return self._getitem_multilevel(key) File "/usr/local/lib/python3.10/site-packages/pandas/core/frame.py", line 4159, in _getitem_multilevel loc = self.columns.get_loc(key) File "/usr/local/lib/python3.10/site-packages/pandas/core/indexes/multi.py", line 3040, in get_loc loc = self._get_level_indexer(key, level=0) File "/usr/local/lib/python3.10/site-packages/pandas/core/indexes/multi.py", line 3391, in _get_level_indexer idx = self._get_loc_single_level_index(level_index, key) File "/usr/local/lib/python3.10/site-packages/pandas/core/indexes/multi.py", line 2980, in _get_loc_single_level_index return level_index.get_loc(key) File "/usr/local/lib/python3.10/site-packages/pandas/core/indexes/base.py", line 3812, in get_loc raise KeyError(key) from err KeyError: \'Adj Close\'''role''assistant''name''user_proxy'}, {'content'"The error indicates that `data['Adj Close']` is not accessible in the way we attempted to. This can happen if the data returned from Yahoo Finance is not structured as expected. Let's take an alternative approach to ensure we correctly extract the adjusted close prices.\n\nWe'll modify the code to check the structure of the returned data and access the prices correctly. Please execute the following updated code:\n\n```python\n# filename: plot_stock_chart.py\nimport yfinance as yf\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\n\n# Define the stocks and the date range\ntickers = ['NVDA', 'TSLA']\nstart_date = datetime(datetime.now().year, 1, 1)\n\n# Fetch the stock data\ndata = yf.download(tickers, start=start_date)\n\n# Check the structure of the data\nprint(data.head())\n\n# Plot the adjusted close prices\nplt.figure(figsize=(10, 5))\nfor ticker in tickers:\n plt.plot(data['Close'][ticker], label=f'{ticker} Close Price')\n \nplt.title('YTD Stock Prices of NVDA and TSLA')\nplt.xlabel('Date')\nplt.ylabel('Close Price ($)')\nplt.legend()\nplt.grid(True)\nplt.tight_layout()\n\n# Save the plot\nplt.savefig('ytd_stock_prices.png')\nplt.show()\n```\n\nIn this version, we print the head of the data to inspect its structure, and then we access the `Close` prices instead of the `Adj Close`. Please execute the code again."'role''user''name''assistant'}], summary="The error indicates that `data['Adj Close']` is not accessible in the way we attempted to. This can happen if the data returned from Yahoo Finance is not structured as expected. Let's take an alternative approach to ensure we correctly extract the adjusted close prices.\n\nWe'll modify the code to check the structure of the returned data and access the prices correctly. Please execute the following updated code:\n\n```python\n# filename: plot_stock_chart.py\nimport yfinance as yf\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\n\n# Define the stocks and the date range\ntickers = ['NVDA', 'TSLA']\nstart_date = datetime(datetime.now().year, 1, 1)\n\n# Fetch the stock data\ndata = yf.download(tickers, start=start_date)\n\n# Check the structure of the data\nprint(data.head())\n\n# Plot the adjusted close prices\nplt.figure(figsize=(10, 5))\nfor ticker in tickers:\n plt.plot(data['Close'][ticker], label=f'{ticker} Close Price')\n \nplt.title('YTD Stock Prices of NVDA and TSLA')\nplt.xlabel('Date')\nplt.ylabel('Close Price ($)')\nplt.legend()\nplt.grid(True)\nplt.tight_layout()\n\n# Save the plot\nplt.savefig('ytd_stock_prices.png')\nplt.show()\n```\n\nIn this version, we print the head of the data to inspect its structure, and then we access the `Close` prices instead of the `Adj Close`. Please execute the code again.", cost={'usage_including_cached_inference': {'total_cost'0.0006329999999999999'gpt-4o-mini-2024-07-18': {'cost'0.0006329999999999999'prompt_tokens'1632'completion_tokens'647'total_tokens'2279}}, 'usage_excluding_cached_inference': {'total_cost'0.0006329999999999999'gpt-4o-mini-2024-07-18': {'cost'0.0006329999999999999'prompt_tokens'1632'completion_tokens'647'total_tokens'2279}}}, human_input=['Traceback (most recent call last): File "/home/hj/workspaces/dc/autogen-v0.2/coding/plot_stock_chart.py", line 14, in <module> plt.plot(data[\'Adj Close\'][\'NVDA\'], label=\'Nvidia (NVDA)\') File "/usr/local/lib/python3.10/site-packages/pandas/core/frame.py", line 4101, in __getitem__ return self._getitem_multilevel(key) File "/usr/local/lib/python3.10/site-packages/pandas/core/frame.py", line 4159, in _getitem_multilevel loc = self.columns.get_loc(key) File "/usr/local/lib/python3.10/site-packages/pandas/core/indexes/multi.py", line 3040, in get_loc loc = self._get_level_indexer(key, level=0) File "/usr/local/lib/python3.10/site-packages/pandas/core/indexes/multi.py", line 3391, in _get_level_indexer idx = self._get_loc_single_level_index(level_index, key) File "/usr/local/lib/python3.10/site-packages/pandas/core/indexes/multi.py", line 2980, in _get_loc_single_level_index return level_index.get_loc(key) File "/usr/local/lib/python3.10/site-packages/pandas/core/indexes/base.py", line 3812, in get_loc raise KeyError(key) from err KeyError: \'Adj Close\'''exit'])


from IPython.display import Image
Image("ytd_stock_prices.png")



上面这个例子中,助手代理能够为给定的任务编写python代码,而用户代理则需要执行生成的代码,并根据设置自动或手动运行代码。大体的流程如下:



支持多样化的对话模式


1.具有不同自治级别和人类参与模式的对话


AutoGen 支持在初始化步骤后实现完全自主的对话。 另一方面,AutoGen 可以通过配置人类参与程度和模式来实现人机协同解决问题(例如,将 human_input_mode 设置为 ALWAYS)这在许多需要或期望人类参与的应用中非常有用。


2.静态和动态对话


AutoGen 通过结合编程和自然语言驱动的对话控制,天然支持动态对话。 动态对话允许代理拓扑根据实际对话流程和不同的输入问题场景进行调整,适用于无法预定义交互模式的复杂场景。 静态对话 则遵循预定义的拓扑结构,适合于交互模式明确的场景。


注册自动回复


通过可插拔的自动回复功能,可以根据当前消息内容和上下文选择是否与其他代理展开对话。例如:

  • 分层对话:如 OptiGuide 中的实现。

  • 动态群聊:一种特殊的分层对话形式,群聊管理器中注册的回复函数可广播消息,并决定群聊中的下一位发言者。

  • 有限状态机图:设置发言者转换限制的特殊动态群聊形式。通过输入有向转换矩阵,用户可以指定合法的发言者转换或禁止的转换。

  • 嵌套对话:如对话式国际象棋中的嵌套结构。


基于 LLM 的函数调用


基于 LLM 的函数调用是另一种方法,其中 LLM 在每次推理期间根据对话状态决定是否调用特定函数。 这种方法支持动态的多代理对话。例如,在多用户数学问题求解场景中,学生助手可以通过函数调用自动寻求专业知识,从而实现高效的动态协作。

53AI,企业落地大模型首选服务商

产品:场景落地咨询+大模型应用平台+行业解决方案

承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

添加专属顾问

回到顶部

加载中...

扫码咨询