-
Notifications
You must be signed in to change notification settings - Fork 4k
Python: Multi-agent orchestration: Magentic #12104
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
TaoChenOSU
merged 11 commits into
main
from
taochen/python-multi-agent-orchestration-pr-part-4
May 16, 2025
Merged
Changes from 5 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
fd24140
Magentic orchestration
TaoChenOSU ca83971
Refine magentic manager base
TaoChenOSU 7c01aa9
Tune magentic sample
TaoChenOSU b01eb4a
Merge branch 'main' into local-branch-python-multi-agent-orchestratio…
TaoChenOSU b508bb6
Update sample readme
TaoChenOSU f0cdd3b
Tune magentic sample
TaoChenOSU 954e46c
Address comments
TaoChenOSU 1f9ed45
Merge branch 'main' into taochen/python-multi-agent-orchestration-pr-…
moonbox3 b5d52b6
Address comments 2
TaoChenOSU 122f55a
Fix mypy
TaoChenOSU 577101e
Update agent description
TaoChenOSU File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
48 changes: 48 additions & 0 deletions
48
python/samples/getting_started_with_agents/multi_agent_orchestration/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
# Multi-agent orchestration | ||
TaoChenOSU marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
The Semantic Kernel Agent Framework now supports orchestrating multiple agents to work together to complete a task. | ||
|
||
## Background | ||
|
||
The following samples are beneficial if you are just getting started with Semantic Kernel. | ||
|
||
- [Chat Completion](../../concepts/chat_completion/) | ||
- [Auto Function Calling](../../concepts/auto_function_calling/) | ||
- [Structured Output](../../concepts/structured_output/) | ||
- [Getting Started with Agents](../../getting_started_with_agents/) | ||
- [More advanced agent samples](../../concepts/agents/) | ||
|
||
## Prerequisites | ||
|
||
The following environment variables are required to run the samples: | ||
|
||
- OPENAI_API_KEY | ||
- OPENAI_CHAT_MODEL_ID | ||
|
||
However, if you are using other model services, feel free to switch to those in the samples. | ||
Refer to [here](../../concepts/setup/README.md) on how to set up the environment variables for your model service. | ||
|
||
## Orchestrations | ||
|
||
| **Orchestrations** | **Description** | | ||
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| **Concurrent** | Useful for tasks that will benefit from independent analysis from multiple agents. | | ||
| **Sequential** | Useful for tasks that require a well-defined step-by-step approach. | | ||
| **Handoff** | Useful for tasks that are dynamic in nature and don't have a well-defined step-by-step approach. | | ||
| **GroupChat** | Useful for tasks that will benefit from inputs from multiple agents and a highly configurable conversation flow. | | ||
| **Magentic** | GroupChat like with a planner based manager. Inspired by [Magentic One](https://www.microsoft.com/en-us/research/articles/magentic-one-a-generalist-multi-agent-system-for-solving-complex-tasks/). | | ||
|
||
## Samples | ||
|
||
| Sample | Description | | ||
|-----------------------------------------------------------------------------|--------------| | ||
| [step1_concurrent](step1_concurrent.py) | Run agents in parallel on the same task. | | ||
| [step1a_concurrent_structure_output](step1a_concurrent_structure_output.py) | Run agents in parallel on the same task and return structured output. | | ||
| [step2_sequential](step2_sequential.py) | Run agents in sequence to complete a task. | | ||
| [step2a_sequential_cancellation_token](step2a_sequential_cancellation_token.py) | Cancel an invocation while it is in progress. | | ||
| [step3_group_chat](step3_group_chat.py) | Run agents in a group chat to complete a task. | | ||
| [step3a_group_chat_human_in_the_loop](step3a_group_chat_human_in_the_loop.py) | Run agents in a group chat with human in the loop. | | ||
| [step3b_group_chat_with_chat_completion_manager](step3b_group_chat_with_chat_completion_manager.py) | Run agents in a group chat with a more dynamic manager. | | ||
| [step4_handoff](step4_handoff.py) | Run agents in a handoff orchestration to complete a task. | | ||
| [step4a_handoff_structure_input](step4a_handoff_structure_input.py) | Run agents in a handoff orchestration to complete a task with structured input. | | ||
| [step5_magentic](step5_magentic.py) | Run agents in a Magentic orchestration to complete a task. | |
File renamed without changes.
155 changes: 155 additions & 0 deletions
155
python/samples/getting_started_with_agents/multi_agent_orchestration/step5_magentic.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,155 @@ | ||
# Copyright (c) Microsoft. All rights reserved. | ||
|
||
import asyncio | ||
|
||
from semantic_kernel.agents import Agent, ChatCompletionAgent, MagenticOrchestration, OpenAIAssistantAgent | ||
from semantic_kernel.agents.orchestration.magentic import StandardMagenticManager | ||
TaoChenOSU marked this conversation as resolved.
Show resolved
Hide resolved
|
||
from semantic_kernel.agents.runtime import InProcessRuntime | ||
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion, OpenAIPromptExecutionSettings | ||
from semantic_kernel.contents import ChatMessageContent | ||
|
||
""" | ||
The following sample demonstrates how to create a Magentic orchestration with two agents: | ||
- A Research agent that can perform web searches | ||
- A Coder agent that can run code using the code interpreter | ||
|
||
Read more about Magentic here: | ||
https://www.microsoft.com/en-us/research/articles/magentic-one-a-generalist-multi-agent-system-for-solving-complex-tasks/ | ||
|
||
This sample demonstrates the basic steps of creating and starting a runtime, creating | ||
a Magentic orchestration with two agents and a Magentic manager, invoking the | ||
orchestration, and finally waiting for the results. | ||
|
||
The Magentic manager requires a chat completion model that supports structured output. | ||
""" | ||
|
||
|
||
async def agents() -> list[Agent]: | ||
"""Return a list of agents that will participate in the Magentic orchestration. | ||
|
||
Feel free to add or remove agents. | ||
""" | ||
research_agent = ChatCompletionAgent( | ||
name="ResearchAgent", | ||
description="A helpful assistant with access to web search. Ask it to perform web searches.", | ||
instructions=( | ||
"You are a Researcher. You find information without additional computation or quantitative analysis." | ||
), | ||
# This agent requires the gpt-4o-search-preview model to perform web searches. | ||
service=OpenAIChatCompletion(ai_model_id="gpt-4o-search-preview"), | ||
TaoChenOSU marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) | ||
|
||
# Create an OpenAI Assistant agent with code interpreter capability | ||
client, model = OpenAIAssistantAgent.setup_resources() | ||
code_interpreter_tool, code_interpreter_tool_resources = OpenAIAssistantAgent.configure_code_interpreter_tool() | ||
definition = await client.beta.assistants.create( | ||
model=model, | ||
name="CoderAgent", | ||
description="A helpful assistant with code interpreter capability.", | ||
TaoChenOSU marked this conversation as resolved.
Show resolved
Hide resolved
|
||
instructions="You solve questions using code. Please provide detailed analysis and computation process.", | ||
tools=code_interpreter_tool, | ||
tool_resources=code_interpreter_tool_resources, | ||
) | ||
coder_agent = OpenAIAssistantAgent( | ||
client=client, | ||
definition=definition, | ||
) | ||
|
||
return [research_agent, coder_agent] | ||
|
||
|
||
def agent_response_callback(message: ChatMessageContent) -> None: | ||
"""Observer function to print the messages from the agents.""" | ||
print(f"**{message.name}**\n{message.content}") | ||
|
||
|
||
async def main(): | ||
"""Main function to run the agents.""" | ||
# 1. Create a Magentic orchestration with two agents and a Magentic manager | ||
# Note, the Magentic manager accepts custom prompts for advanced users and scenarios. | ||
magentic_orchestration = MagenticOrchestration( | ||
members=await agents(), | ||
manager=StandardMagenticManager( | ||
chat_completion_service=OpenAIChatCompletion(), | ||
prompt_execution_settings=OpenAIPromptExecutionSettings(), | ||
), | ||
agent_response_callback=agent_response_callback, | ||
) | ||
|
||
# 2. Create a runtime and start it | ||
runtime = InProcessRuntime() | ||
runtime.start() | ||
|
||
# 3. Invoke the orchestration with a task and the runtime | ||
orchestration_result = await magentic_orchestration.invoke( | ||
task=( | ||
"The 2025 trade war between the US and other countries has had a significant impact " | ||
TaoChenOSU marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"on the global economy. I am a business owner in the US that import household goods " | ||
"such as bed sheets and holiday decorations from south-east Asia. I want " | ||
"to know the impact of the tariffs on my business given that my current profit " | ||
"margin is 20%. And If I were to increase the price of my products by 10%, " | ||
"how would that affect my customer behavior and profit margin? Base on the analysis, " | ||
"find similar cases in the past to cross-reference the results. Provide a detailed " | ||
"report and recommendations on how to adapt to the changing market conditions at the end." | ||
), | ||
runtime=runtime, | ||
) | ||
|
||
# 4. Wait for the results | ||
value = await orchestration_result.get() | ||
|
||
print(f"\nFinal result:\n{value}") | ||
|
||
# 5. Stop the runtime when idle | ||
await runtime.stop_when_idle() | ||
|
||
""" | ||
Sample output: | ||
**ResearchAgent** | ||
The 2025 trade war has led to significant tariffs imposed by the United States on imports from Southeast Asian | ||
countries, directly affecting industries such as household goods. For instance, Cambodia faces a 49% tariff, | ||
Vietnam 46%, and Thailand 36% on their exports to the U.S. | ||
([thailandinfo.se](https://www.thailandinfo.se/en/usa-tariffs-southeast-asia-2025/?utm_source=openai)) | ||
|
||
... | ||
**CoderAgent** | ||
Here's the analysis based on your scenario: | ||
|
||
1. **Initial Scenario:** | ||
- Initial Selling Price: $125.00 (to achieve a 20% profit margin) | ||
|
||
2. **After Applying Tariffs:** | ||
- New Cost Price: $145.00 (after a 45% tariff on the initial $100 cost) | ||
|
||
3. **With a 10% Price Increase:** | ||
- New Selling Price: $137.50 | ||
|
||
4. **Profit Margin and Volume Impact:** | ||
... | ||
**ResearchAgent** | ||
In response to increased tariffs during trade wars, various companies have implemented strategic measures to | ||
mitigate financial impacts and maintain competitiveness. Notable examples include: | ||
|
||
**1. Supply Chain Diversification:** | ||
|
||
- **Steven Madden Ltd.:** Faced with a 10% tariff on handbags imported from China, the company relocated | ||
production to Cambodia to circumvent the tariffs.([money.usnews.com](https://money.usnews.com/money/blogs/... | ||
**CoderAgent** | ||
Here's a detailed simulated report on the potential business impact due to tariffs and price adjustments, | ||
along with strategic recommendations: | ||
|
||
### Financial Impact Summary: | ||
|
||
1. **New Cost Price after Tariffs:** $145.00 | ||
2. **New Selling Price after 10% Increase:** $137.50 | ||
3. **New Profit Margin:** -5.45% | ||
4. **Estimated Sales Volume Change:** Decrease to 95.0% of original | ||
5. **New Estimated Profit per Unit:** Negative $7.12 | ||
|
||
### Strategies from Historical Cases: | ||
... | ||
""" | ||
|
||
|
||
if __name__ == "__main__": | ||
asyncio.run(main()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.