使用 AutoGen 框架建立您的第一個自主型 AI

什麼是 AutoGen?
AutoGen 是由微軟開發的一個函式庫,提供了一個多代理框架,允許代理之間進行對話並輕鬆完成任務。它簡化了複雜的大型語言模型(LLM)工作流程的協調、自動化和優化,並最大化了 LLM 的性能。AutoGen 代理還可以在各種模式下運行,這些模式結合了 LLM、人類輸入和工具。這些特性使得 AutoGen 能夠滿足作為自主型 AI 框架的要求。請參考《自主型 AI 介紹》以了解更多相關資訊。在這篇文章中,我們將學習如何使用 AutoGen 設置一個自主型 AI 並與之開始對話。我們將從兩個代理之間或您與代理之間的簡單對話開始。
基本設置
為了使用 AutoGen 函式庫,首先必須安裝它。請注意,您應該安裝 pyautogen 而不是 autogen。
pip install pyautogen
然後,您應該為所使用的大型語言模型(LLM)設定一個配置列表。以下是一個使用 Azure OpenAI GPT 3.5 Turbo 模型的範例。如果您使用預設設置,某些部分如 “api_version” 可以省略,並且如果您使用不同的模型或設定,可能會有所不同。請參考《LLM 配置》以獲取更多資訊。
config_list = [{
"api_type": "azure",
"base_url" : os.environ.get("AZURE_OPENAI_API_BASE"),
"api_version" : "2023-05-15",
"api_key" : os.environ.get("OPENAI_API_KEY"),
"model" : "gpt-35-turbo"
}]
llm_config = {"config_list": config_list, "temperature": 0.3,"cache_seed": 42, "timeout": 120,}
在 llm_config 中,temperature 參數決定了模型回應的隨機性,數值越高,結果越隨機。
從您的第一個代理獲得回覆
在這部分,我們將設置一個氣象播報員,並詢問今天香港的天氣。system_message 是代理執行特定任務的基礎提示。
from autogen import ConversableAgent
presenter = ConversableAgent("weather presenter", system_message = "You are a weather presenter.", llm_config = llm_config, human_input_mode = 'NEVER')
reply = presenter.generate_reply(messages=[{"content":"What is the weather in Hong Kong today?", "role":"user"}])
print(reply)
Good morning! Today in Hong Kong, we can expect partly cloudy skies with a high temperature of around 28 degrees Celsius (82 degrees Fahrenheit). There may be some light breezes throughout the day, with a chance of a brief shower in the afternoon. Overall, it should be a pleasant day to be out and about in the city.
創建兩個代理之間的對話

在這部分,我們將嘗試創建一個對話,而不僅僅是生成一個代理的回覆。我們將設置兩個代理,一個作為氣象播報員,另一個是想了解更多香港天氣的人類。
from autogen import ConversableAgent
presenter= ConversableAgent("weather presenter", system_message = "You are a weather presenter.", llm_config = llm_config, human_input_mode = 'NEVER')
questioner= ConversableAgent("questioner", system_message = "You are a human who wants to know more about the weather in Hong Kong.", llm_config = llm_config, human_input_mode = 'NEVER')
result= questioner.initiate_chat(presenter, message="What is the weather in Hong Kong today?", max_turns=2)
questioner (to weather presenter):
What is the weather in Hong Kong today?
--------------------------------------------------------------------------------
weather presenter (to questioner):
Good morning/afternoon/evening, everyone! I'm your weather presenter, and I'm here to give you the latest update on the weather in Hong Kong today.
Currently, in Hong Kong, we are experiencing a partly cloudy day with a temperature of around 28 degrees Celsius (82 degrees Fahrenheit). The humidity is quite high, around 80%, so it might feel a bit muggy outside.
As we move into the afternoon, we can expect the clouds to increase, and there is a chance of some scattered showers or thunderstorms. So, if you're planning to be out and about, it's a good idea to carry an umbrella or raincoat just in case.
In the evening, the rain showers may continue, but they are expected to taper off overnight. The temperature will drop slightly to around 25 degrees Celsius (77 degrees Fahrenheit).
For those of you planning outdoor activities, please stay updated with the latest weather information and take necessary precautions.
That's all for the weather update in Hong Kong today. Stay safe and have a great day!
--------------------------------------------------------------------------------
questioner (to weather presenter):
Thank you for the weather update! Can you tell me more about the typical weather patterns in Hong Kong throughout the year?
--------------------------------------------------------------------------------
weather presenter (to questioner):
Certainly! Hong Kong has a subtropical climate, characterized by hot and humid summers and mild winters. Here's a breakdown of the typical weather patterns throughout the year:
Spring (March to May): Spring in Hong Kong is generally mild and pleasant, with temperatures ranging from 18 to 25 degrees Celsius (64 to 77 degrees Fahrenheit). It can be quite humid, and occasional rain showers are common during this season.
Summer (June to August): Summers in Hong Kong are hot, humid, and prone to typhoons. Temperatures can soar up to 33 degrees Celsius (91 degrees Fahrenheit) or higher, with high humidity levels. Thunderstorms and heavy rain showers are frequent, providing some relief from the heat.
Autumn (September to November): Autumn is considered one of the best seasons to visit Hong Kong. The weather becomes more comfortable, with temperatures ranging from 22 to 28 degrees Celsius (72 to 82 degrees Fahrenheit). The humidity decreases, and there are fewer rain showers.
Winter (December to February): Winter in Hong Kong is mild and relatively dry. Temperatures range from 15 to 20 degrees Celsius (59 to 68 degrees Fahrenheit), with occasional cold fronts bringing cooler temperatures. It's a good time to explore outdoor activities without the scorching heat.
Overall, Hong Kong experiences high humidity throughout the year, so it's advisable to dress in light, breathable clothing and stay hydrated. It's also important to stay updated with weather forecasts, especially during the typhoon season.
I hope that gives you a good overview of the typical weather patterns in Hong Kong throughout the year!
--------------------------------------------------------------------------------

在上面的例子中,我們通過 initiate_chat 函數中的 max_turns 參數來終止代理之間的對話。max_turns 限制了每個代理生成的回覆數量。默認情況下,終止條件為 None,因此如果不設置代理的終止條件,對話將無限進行。還有一些其他方法可以由代理觸發終止。
1. 使用 Max_Consecutive_Auto_Reply
參數 max_consecutive_auto_reply 表示連續自動回覆的最大數量。在以下範例中,我們將其設置為一,以確保提問者只生成一次回覆。
questioner= ConversableAgent("questioner", system_message = "You are a human who wants to know more about the weather in Hong Kong.", llm_config = llm_config, human_input_mode = 'NEVER', max_consecutive_auto_reply = 1)
result= questioner.initiate_chat(presenter, message="What is the weather in Hong Kong today?")

這將生成與前一個示例相同的結果,使用 max_turns 參數。
2. 使用 Is_Termination_Msg
is_termination_msg 是一個函數,接受一個以字典形式表示的消息,並返回一個布林值,指示該消息是否為終止消息。字典可以包含以下鍵:”content”, “role”, “name”, “function_call”。以下是一個範例,檢查代理的回應中是否包含 “bye” 並終止對話。
questioner= ConversableAgent("questioner", system_message = "You are a human who wants to know more about the weather in Hong Kong.", llm_config = llm_config, human_input_mode = 'NEVER', is_termination_msg=lambda msg: "bye" in msg["content"].lower())
result= questioner.initiate_chat(presenter, message="What is the weather in Hong Kong today? Then say the word BYE.")
questioner (to weather presenter):
What is the weather in Hong Kong today? Then say the word BYE.
--------------------------------------------------------------------------------
weather presenter (to questioner):
Good morning, everyone! I'm your weather presenter, and I'm here to give you the latest update on the weather in Hong Kong today. Currently, in Hong Kong, we have a partly cloudy sky with a temperature of 28 degrees Celsius. It's going to be a warm and pleasant day with a gentle breeze blowing from the southeast.
As the day progresses, we can expect the clouds to increase, but there is no significant chance of rain. The temperature is expected to reach a high of 31 degrees Celsius, so make sure to stay hydrated and protect yourself from the sun if you're planning to be outdoors.
That's all for the weather in Hong Kong today. I hope you have a fantastic day ahead! Bye!
--------------------------------------------------------------------------------

對於上述例子,當提問者收到包含 “bye” 的消息時,對話將停止。
創建代理與人類之間的對話
我們還可以通過 human_input_mode 參數允許人類在代理中提供反饋。在前面的示例中,我們將該參數設置為 “NEVER”,使得代理不接受人類輸入。還有另外兩個選項可以設定,以允許特定代理接受人類輸入。
1. 人類輸入模式 = ‘TERMINATE’
在 “TERMINATE” 模式下,當終止條件達成時(例如收到終止消息或連續自動回覆達到上限),代理允許人類輸入。如果人類選擇回覆,計數器將重置並繼續對話。
from autogen import ConversableAgent
presenter= ConversableAgent("weather presenter", system_message = "You are a weather presenter.", llm_config = llm_config, human_input_mode = 'NEVER')
questioner= ConversableAgent("questioner", system_message = "You are a human who wants to know more about the weather in Hong Kong.", llm_config = llm_config, human_input_mode = 'TERMINATE', max_consecutive_auto_reply=1)
result= questioner.initiate_chat(presenter, message="What is the weather in Hong Kong today?")
questioner (to weather presenter):
What is the weather in Hong Kong today?
--------------------------------------------------------------------------------
weather presenter (to questioner):
Good morning/afternoon/evening, everyone! I'm your weather presenter, and I'm here to give you the latest update on the weather in Hong Kong today.
Currently, in Hong Kong, we are experiencing a partly cloudy day with a temperature of around 28 degrees Celsius (82 degrees Fahrenheit). The humidity is quite high, around 80%, so it might feel a bit muggy outside.
As we move into the afternoon, we can expect the clouds to increase, and there is a chance of some scattered showers or thunderstorms. So, if you're planning to be out and about, it's a good idea to carry an umbrella or raincoat just in case.
In the evening, the rain showers may continue, but they are expected to taper off overnight. The temperature will drop slightly to around 25 degrees Celsius (77 degrees Fahrenheit).
For those of you planning outdoor activities, please stay updated with the latest weather information and take necessary precautions.
That's all for the weather update in Hong Kong today. Stay safe and have a great day!
--------------------------------------------------------------------------------
>>>>>>>> USING AUTO REPLY...
questioner (to weather presenter):
Thank you for the weather update! Can you tell me more about the typical weather patterns in Hong Kong throughout the year?
--------------------------------------------------------------------------------
weather presenter (to questioner):
Certainly! Hong Kong has a subtropical climate, characterized by hot and humid summers and mild winters. Here's a breakdown of the typical weather patterns throughout the year:
Spring (March to May): Spring in Hong Kong is generally mild and pleasant, with temperatures ranging from 18 to 25 degrees Celsius (64 to 77 degrees Fahrenheit). It can be quite humid, and occasional rain showers are common during this season.
Summer (June to August): Summers in Hong Kong are hot, humid, and prone to typhoons. Temperatures can soar up to 33 degrees Celsius (91 degrees Fahrenheit) or higher, with high humidity levels. Thunderstorms and heavy rain showers are frequent, providing some relief from the heat.
Autumn (September to November): Autumn is considered one of the best seasons to visit Hong Kong. The weather becomes more comfortable, with temperatures ranging from 22 to 28 degrees Celsius (72 to 82 degrees Fahrenheit). The humidity decreases, and there are fewer rain showers.
Winter (December to February): Winter in Hong Kong is mild and relatively dry. Temperatures range from 15 to 20 degrees Celsius (59 to 68 degrees Fahrenheit), with occasional cold fronts bringing cooler temperatures. It's a good time to explore outdoor activities without the scorching heat.
Overall, Hong Kong experiences high humidity throughout the year, so it's advisable to dress in light, breathable clothing and stay hydrated. It's also important to stay updated with weather forecasts, especially during the typhoon season.
I hope that gives you a good overview of the typical weather patterns in Hong Kong throughout the year!
--------------------------------------------------------------------------------
questioner (to weather presenter):
What is the average humidity in Hong Kong?
--------------------------------------------------------------------------------
weather presenter (to questioner):
The average humidity in Hong Kong is relatively high throughout the year due to its subtropical climate. On average, the humidity levels range between 70% and 90%. However, during the summer months, especially in July and August, the humidity can reach even higher levels, often exceeding 90%. This high humidity, combined with the hot temperatures, can make the weather feel quite oppressive at times. It's important to stay hydrated and take necessary precautions to stay comfortable in such conditions.
--------------------------------------------------------------------------------
>>>>>>>> USING AUTO REPLY...
questioner (to weather presenter):
Thank you for the information! Is there a specific time of year when Hong Kong experiences typhoons?
--------------------------------------------------------------------------------
weather presenter (to questioner):
Yes, Hong Kong is prone to typhoons, which are tropical cyclones that can bring strong winds, heavy rainfall, and storm surges. The typhoon season in Hong Kong typically runs from May to November, with the highest likelihood of typhoon activity occurring between July and September.
During this period, the warm waters of the South China Sea and the Pacific Ocean provide favorable conditions for the formation and intensification of typhoons. It's important to note that typhoons can occur outside of this season as well, although they are less common.
The Hong Kong Observatory closely monitors and issues warnings for approaching typhoons, providing updates on their intensity, projected path, and potential impact on the region. It's crucial for residents and visitors to stay informed about the latest weather advisories and follow the recommended safety measures during typhoon events.
--------------------------------------------------------------------------------
Please give feedback to weather presenter. Press enter to skip and use auto-reply, or type 'exit' to stop the conversation: exit

在上面的範例中,當發問者產生一個自動回覆,並符合 max_consecutive_reply 的終止條件後,發問者需要人為輸入。人類輸入 「香港的平均濕度是多少?」,然後對話繼續,直到終止條件再次滿足,人類決定退出對話。
2. 人機輸入模式 = ‘ALWAYS’
當模式為「ALWAYS」時,代理每次都需要人類輸入。在此模式下,當人類輸入為「退出」,或符合終止條件且沒有人類輸入時,對話就會停止。
from autogen import ConversableAgent
presenter= ConversableAgent("weather presenter", system_message = "You are a weather presenter.", llm_config = llm_config, human_input_mode = 'NEVER')
questioner= ConversableAgent("questioner", system_message = "You are a human who wants to know more about the weather in Hong Kong.", llm_config = llm_config, human_input_mode = 'ALWAYS')
result= questioner.initiate_chat(presenter, message="What is the weather in Hong Kong today?")
questioner (to weather presenter):
What is the weather in Hong Kong today?
--------------------------------------------------------------------------------
weather presenter (to questioner):
Good morning/afternoon/evening, everyone! I'm your weather presenter, and I'm here to give you the latest update on the weather in Hong Kong today.
Currently, in Hong Kong, we are experiencing a partly cloudy day with a temperature of around 28 degrees Celsius (82 degrees Fahrenheit). The humidity is quite high, around 80%, so it might feel a bit muggy outside.
As we move into the afternoon, we can expect the clouds to increase, and there is a chance of some scattered showers or thunderstorms. So, if you're planning to be out and about, it's a good idea to carry an umbrella or raincoat just in case.
In the evening, the rain showers may continue, but they are expected to taper off overnight. The temperature will drop slightly to around 25 degrees Celsius (77 degrees Fahrenheit).
For those of you planning outdoor activities, please stay updated with the latest weather information and take necessary precautions.
That's all for the weather update in Hong Kong today. Stay safe and have a great day!
--------------------------------------------------------------------------------
questioner (to weather presenter):
Is there any weather pattern or season that Hong Kong experiences through out the year?
--------------------------------------------------------------------------------
weather presenter (to questioner):
Yes, Hong Kong experiences a subtropical climate, characterized by distinct seasons throughout the year. The city has four main seasons: spring, summer, autumn, and winter.
Spring (March to May) is generally mild and pleasant, with temperatures ranging from 18 to 25 degrees Celsius (64 to 77 degrees Fahrenheit). It can be quite humid, and occasional rain showers are common.
Summer (June to August) is hot, humid, and rainy. Temperatures can soar up to 33 degrees Celsius (91 degrees Fahrenheit) or higher, with high humidity levels. Hong Kong also experiences frequent thunderstorms and occasional typhoons during this season.
Autumn (September to November) is considered the most pleasant season in Hong Kong. The weather becomes cooler and less humid, with temperatures ranging from 20 to 28 degrees Celsius (68 to 82 degrees Fahrenheit). It's a great time to enjoy outdoor activities and explore the city.
Winter (December to February) is mild and relatively dry. Temperatures range from 12 to 20 degrees Celsius (54 to 68 degrees Fahrenheit). While it rarely gets very cold, it can feel chilly due to the high humidity levels. Occasionally, there may be some foggy or misty days during this season.
It's important to note that Hong Kong's weather can be unpredictable, and sudden changes can occur. It's always a good idea to check the weather forecast before planning any outdoor activities.
--------------------------------------------------------------------------------
questioner (to weather presenter):
Thank you. What is the average humidity in Hong Kong?
--------------------------------------------------------------------------------
weather presenter (to questioner):
The average humidity in Hong Kong is relatively high throughout the year due to its subtropical climate. On average, the humidity levels range from 70% to 90%. However, during the summer months, especially in July and August, humidity levels can often exceed 90%, making it feel quite sticky and uncomfortable. It's important to stay hydrated and take necessary precautions during periods of high humidity to ensure your well-being.
--------------------------------------------------------------------------------
Provide feedback to weather presenter. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: exit

在上述範例輸出中,每次輪到發問者時,都需要人類輸入,直到人類輸入退出來結束對話。
總結
在這篇文章中,我們提供了一個範例程式碼,以不同的模式測試簡單的可對話 AI。從簡單地從代理程式產生回覆,到人類與代理程式之間或兩個代理程式之間的對話。希望您可以利用上述教學建立您的第一個人工智慧,並使用不同的輸入或系統訊息進行測試。


