autogen 中的 Termination 使用
·
MaxMessageTermination
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
model_client = OpenAIChatCompletionClient(
model="GLM-4-Flash",
api_key = "your api key",
base_url="https://open.bigmodel.cn/api/paas/v4/",
model_capabilities={
"vision": False,
"function_calling": True,
"json_output": True,
}
)
model_client_air = OpenAIChatCompletionClient(
model="GLM-4-Air-0111",
api_key = "your api key",
base_url="https://open.bigmodel.cn/api/paas/v4/",
model_capabilities={
"vision": False,
"function_calling": True,
"json_output": True,
}
)
# Create the primary agent.
primary_agent = AssistantAgent(
"primary",
model_client=model_client,
system_message="You are a helpful AI assistant.",
)
# Create the critic agent.
critic_agent = AssistantAgent(
"critic",
model_client=model_client_air,
system_message="Provide constructive feedback for every message. Respond with 'APPROVE' to when your feedbacks are addressed.",
)
max_msg_termination = MaxMessageTermination(max_messages=3)
round_robin_team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=max_msg_termination)
# Use asyncio.run(...) if you are running this script as a standalone script.
await Console(round_robin_team.run_stream(task="Write a unique, Haiku about the weather in Paris"))
---------- user ----------
Write a unique, Haiku about the weather in Paris
---------- primary ----------
Paris rain whispers,
Eiffel's silhouette shimmers,
Clouds dance in the breeze.
---------- critic ----------
This is a good start to a Haiku about the weather in Paris! Here are some points of feedback to make it even stronger:
* **Line 1:** "Paris rain whispers" is evocative, but "whispers" typically suggests a very soft sound. Rain in Paris is often more noticeable than a whisper. Consider a word that reflects the rhythmic or persistent nature of Parisian rain.
* **Line 2:** "Eiffel's silhouette shimmers" is a beautiful image. However, "shimmers" usually implies a sparkling light, which might not be the most fitting verb for a silhouette against a potentially overcast sky. Think about how the Eiffel Tower might appear in the specific weather conditions you're describing.
* **Line 3:** "Clouds dance in the breeze" is a nice image, but it might be too general. Try to connect the clouds more directly to the Parisian atmosphere or the specific weather you're depicting.
Here's a revised version incorporating these suggestions:
Gray sky weeps softly,
Eiffel stands stark against it,
Clouds hug the city.
Let me know what you think!
TaskResult(messages=[TextMessage(source='user', models_usage=None, content='Write a unique, Haiku about the weather in Paris', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=25, completion_tokens=22), content="Paris rain whispers,\nEiffel's silhouette shimmers, \nClouds dance in the breeze.", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=62, completion_tokens=239), content='This is a good start to a Haiku about the weather in Paris! Here are some points of feedback to make it even stronger:\n\n* **Line 1:** "Paris rain whispers" is evocative, but "whispers" typically suggests a very soft sound. Rain in Paris is often more noticeable than a whisper. Consider a word that reflects the rhythmic or persistent nature of Parisian rain. \n* **Line 2:** "Eiffel\'s silhouette shimmers" is a beautiful image. However, "shimmers" usually implies a sparkling light, which might not be the most fitting verb for a silhouette against a potentially overcast sky. Think about how the Eiffel Tower might appear in the specific weather conditions you\'re describing.\n* **Line 3:** "Clouds dance in the breeze" is a nice image, but it might be too general. Try to connect the clouds more directly to the Parisian atmosphere or the specific weather you\'re depicting.\n\nHere\'s a revised version incorporating these suggestions:\n\nGray sky weeps softly,\nEiffel stands stark against it,\nClouds hug the city.\n\nLet me know what you think!\n', type='TextMessage')], stop_reason='Maximum number of messages 3 reached, current message count: 3')
可以继续
# Use asyncio.run(...) if you are running this script as a standalone script.
await Console(round_robin_team.run_stream())
---------- primary ----------
Your revised Haiku captures the essence of Parisian weather with a more vivid image. Here's a slight tweak to enhance the imagery further:
Gray sky weeps gently,
Eiffel's silhouette gleams,
Paris shrouded in mist.
---------- critic ----------
This is an excellent revision! The changes you've made create a more cohesive and evocative Haiku. Here's my feedback:
* **Line 1:** "Gray sky weeps gently" is perfect. The word "gently" accurately portrays a soft, consistent rain that is characteristic of Paris. It's a more fitting description than "softly."
* **Line 2:** "Eiffel's silhouette gleams" is a great improvement. "Gleams" suggests a subtle reflection or a faint light, which is a more accurate depiction of how the Eiffel Tower might appear against a gray, rainy sky. It hints at the tower standing out despite the overcast weather.
* **Line 3:** "Paris shrouded in mist" is a very strong closing line. It effectively captures the atmospheric quality of Paris, especially during wet weather. The word "shrouded" adds a sense of mystery and depth, making the poem more captivating.
**APPROVE**
---------- primary ----------
I'm glad you approved! Your positive feedback is much appreciated. The Haiku now effectively conveys the mood and atmosphere of Paris under a rainy sky. If you have any more requests or need further assistance with poetry or any other topic, feel free to ask!
TaskResult(messages=[TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=286, completion_tokens=51), content="Your revised Haiku captures the essence of Parisian weather with a more vivid image. Here's a slight tweak to enhance the imagery further:\n\nGray sky weeps gently,\nEiffel's silhouette gleams,\nParis shrouded in mist.", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=352, completion_tokens=208), content='This is an excellent revision! The changes you\'ve made create a more cohesive and evocative Haiku. Here\'s my feedback:\n\n* **Line 1:** "Gray sky weeps gently" is perfect. The word "gently" accurately portrays a soft, consistent rain that is characteristic of Paris. It\'s a more fitting description than "softly."\n* **Line 2:** "Eiffel\'s silhouette gleams" is a great improvement. "Gleams" suggests a subtle reflection or a faint light, which is a more accurate depiction of how the Eiffel Tower might appear against a gray, rainy sky. It hints at the tower standing out despite the overcast weather.\n* **Line 3:** "Paris shrouded in mist" is a very strong closing line. It effectively captures the atmospheric quality of Paris, especially during wet weather. The word "shrouded" adds a sense of mystery and depth, making the poem more captivating.\n\n**APPROVE**\n', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=545, completion_tokens=55), content="I'm glad you approved! Your positive feedback is much appreciated. The Haiku now effectively conveys the mood and atmosphere of Paris under a rainy sky. If you have any more requests or need further assistance with poetry or any other topic, feel free to ask!", type='TextMessage')], stop_reason='Maximum number of messages 3 reached, current message count: 3')
MaxMessageTermination | TextMentionTermination Or操作
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
model_client = OpenAIChatCompletionClient(
model="GLM-4-Air-0111",
api_key = "your api key",
base_url="https://open.bigmodel.cn/api/paas/v4/",
model_capabilities={
"vision": False,
"function_calling": True,
"json_output": True,
}
)
model_client_air = OpenAIChatCompletionClient(
model="GLM-4-plus",
api_key = "your api key",
base_url="https://open.bigmodel.cn/api/paas/v4/",
model_capabilities={
"vision": False,
"function_calling": True,
"json_output": True,
}
)
# Create the primary agent.
primary_agent = AssistantAgent(
"primary",
model_client=model_client,
system_message="You are a helpful AI assistant.",
)
# Create the critic agent.
critic_agent = AssistantAgent(
"critic",
model_client=model_client_air,
system_message="Provide constructive feedback for every message. Respond with 'APPROVE' to when your feedbacks are addressed.",
)
max_msg_termination = MaxMessageTermination(max_messages=10)
text_termination = TextMentionTermination("APPROVE")
combined_termination = max_msg_termination | text_termination
round_robin_team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=combined_termination)
# Use asyncio.run(...) if you are running this script as a standalone script.
await Console(round_robin_team.run_stream(task="Write a unique, Haiku about the weather in Paris"))
---------- user ----------
Write a unique, Haiku about the weather in Paris
---------- primary ----------
Soft sun, cool stone breeze,
Rain's gentle, misty touch,
City gray, then bright.
---------- critic ----------
**Feedback:**
- The Haiku captures the essence of Parisian weather with a nice balance of elements.
- The imagery is vivid, especially with "soft sun" and "cool stone breeze."
- Consider slightly tweaking the third line to enhance the contrast or add a touch of surprise. For example, "City gray, blooms light" could add a hint of color and life.
Overall, a well-crafted Haiku!
---------- primary ----------
Thank you for the feedback! I appreciate the kind words and the suggestion. I'll consider your idea for the third line. Here's the revised haiku with your suggestion incorporated:
Soft sun, cool stone breeze,
Rain's gentle, misty touch,
City gray, blooms light.
I think this version adds a nice touch of contrast and visual interest. The idea of blooms emerging even on a gray day in Paris really paints a vivid picture. Thank you for helping me improve it!
---------- critic ----------
**Feedback:**
- The revised Haiku successfully incorporates the suggested change, enhancing the contrast and visual interest.
- The addition of "blooms light" beautifully captures the resilience and beauty of Paris, even on a gray day.
- The flow and rhythm of the Haiku remain intact, maintaining the traditional structure.
- The imagery is now even more vivid and evocative, creating a strong mental picture for the reader.
Well done on refining the Haiku! It's a delightful improvement.
**APPROVE**
TaskResult(messages=[TextMessage(source='user', models_usage=None, content='Write a unique, Haiku about the weather in Paris', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=25, completion_tokens=23), content="Soft sun, cool stone breeze,\nRain's gentle, misty touch,\nCity gray, then bright.\n", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=63, completion_tokens=88), content='**Feedback:**\n\n- The Haiku captures the essence of Parisian weather with a nice balance of elements.\n- The imagery is vivid, especially with "soft sun" and "cool stone breeze."\n- Consider slightly tweaking the third line to enhance the contrast or add a touch of surprise. For example, "City gray, blooms light" could add a hint of color and life.\n\nOverall, a well-crafted Haiku!', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=136, completion_tokens=99), content="Thank you for the feedback! I appreciate the kind words and the suggestion. I'll consider your idea for the third line. Here's the revised haiku with your suggestion incorporated:\n\nSoft sun, cool stone breeze,\nRain's gentle, misty touch,\nCity gray, blooms light.\n\nI think this version adds a nice touch of contrast and visual interest. The idea of blooms emerging even on a gray day in Paris really paints a vivid picture. Thank you for helping me improve it!\n", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=250, completion_tokens=106), content='**Feedback:**\n\n- The revised Haiku successfully incorporates the suggested change, enhancing the contrast and visual interest.\n- The addition of "blooms light" beautifully captures the resilience and beauty of Paris, even on a gray day.\n- The flow and rhythm of the Haiku remain intact, maintaining the traditional structure.\n- The imagery is now even more vivid and evocative, creating a strong mental picture for the reader.\n\nWell done on refining the Haiku! It\'s a delightful improvement.\n\n**APPROVE**', type='TextMessage')], stop_reason="Text 'APPROVE' mentioned")
& 操作
combined_termination = max_msg_termination & text_termination
完整的Termination
- MaxMessageTermination: 在生成指定数量的消息后停止,包括代理和任务消息。
- TextMentionTermination: 当消息中提到特定文本或字符串时停止(例如,“TERMINATE”)。
- TokenUsageTermination: 当使用一定数量的提示或完成令牌时停止。这要求代理在其消息中报告令牌使用情况。
- TimeoutTermination: 在指定的持续时间(以秒为单位)后停止。
- HandoffTermination: 当请求切换到特定目标时停止。切换消息可用于构建诸如Swarm之类的模式。这在您希望暂停运行并允许应用程序或用户在代理切换到他们时提供输入时非常有用。
- SourceMatchTermination: 在特定代理响应后停止。
- ExternalTermination: 允许从运行外部以编程方式控制终止。这对于UI集成非常有用(例如,聊天界面中的“停止”按钮)。
- StopMessageTermination: 当代理生成StopMessage时停止。
更多推荐
所有评论(0)