Skip to content

Commit 60df17d

Browse files
authored
Python: Improve agent getting started samples (#10667)
### Motivation and Context <!-- Thank you for your contribution to the semantic-kernel repo! Please help reviewers and future users, providing the following information: 1. Why is this change required? 2. What problem does it solve? 3. What scenario does it contribute to? 4. If it fixes an open issue, please link to the issue here. --> We are improving developer experience by updating the agent getting started samples. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Simplify the agent getting started samples by removing unnecessary code and add excessive comments to make sure we are only doing what we need to get started. ### Contribution Checklist <!-- Before submitting this PR, please make sure: --> - [x] The code builds clean without any errors or warnings - [x] The PR follows the [SK Contribution Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md) and the [pre-submission formatting script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts) raises no violations - [x] All unit tests pass, and I have added new tests where possible - [x] I didn't break anyone 😄
1 parent 9e979f8 commit 60df17d

22 files changed

+1391
-1278
lines changed

python/samples/getting_started_with_agents/README.md

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,11 @@ The getting started with agents examples include:
2020

2121
Example|Description
2222
---|---
23-
[step1_agent](../getting_started_with_agents/chat_completion/step1_agent.py)|How to create and use an agent.
24-
[step2_plugins](../getting_started_with_agents/chat_completion/step2_plugins.py)|How to associate plugins with an agent.
25-
[step3_chat](../getting_started_with_agents/chat_completion/step3_chat.py)|How to create a conversation between agents.
26-
[step4_kernel_function_strategies](../getting_started_with_agents/chat_completion/step4_kernel_function_strategies.py)|How to utilize a `KernelFunction` as a chat strategy.
27-
[step5_json_result](../getting_started_with_agents/chat_completion/step5_json_result.py)|How to have an agent produce JSON.
28-
[step6_logging](../getting_started_with_agents/chat_completion/step6_logging.py)|How to enable logging for agents.
23+
[step1_chat_completion_agent](../getting_started_with_agents/chat_completion/step1_chat_completion_agent.py)|How to create and use an agent.
24+
[step2_chat_completion_agent_chat](../getting_started_with_agents/chat_completion/step2_chat_completion_agent_chat.py)|How to create a conversation between agents.
25+
[step3_kernel_function_strategies](../getting_started_with_agents/chat_completion/step3_kernel_function_strategies.py)|How to utilize a `KernelFunction` as a chat strategy.
26+
[step4_chat_completion_agent_json_result](../getting_started_with_agents/chat_completion/step4_chat_completion_agent_json_result.py)|How to have an agent produce JSON.
27+
[step5_chat_completion_agent_logging](../getting_started_with_agents/chat_completion/step5_chat_completion_agent_logging.py)|How to enable logging for agents.
2928

3029
## OpenAI Assistant Agent
3130

python/samples/getting_started_with_agents/azure_ai_agent/step1_azure_ai_agent.py

Lines changed: 36 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,13 @@
66
from azure.identity.aio import DefaultAzureCredential
77

88
from semantic_kernel.agents.azure_ai import AzureAIAgent, AzureAIAgentSettings
9-
from semantic_kernel.contents.chat_message_content import ChatMessageContent
10-
from semantic_kernel.contents.utils.author_role import AuthorRole
11-
from semantic_kernel.functions.kernel_function_decorator import kernel_function
9+
from semantic_kernel.contents import AuthorRole
10+
from semantic_kernel.functions import kernel_function
1211

13-
###################################################################
14-
# The following sample demonstrates how to create a simple, #
15-
# Azure AI agent that answers questions about a sample menu #
16-
# using a Semantic Kernel Plugin. #
17-
###################################################################
12+
"""
13+
The following sample demonstrates how to create an Azure AI agent that answers
14+
questions about a sample menu using a Semantic Kernel Plugin.
15+
"""
1816

1917

2018
# Define a sample plugin for the sample
@@ -36,65 +34,68 @@ def get_item_price(
3634
return "$9.99"
3735

3836

37+
# Simulate a conversation with the agent
38+
USER_INPUTS = [
39+
"Hello",
40+
"What is the special soup?",
41+
"How much does that cost?",
42+
"Thank you",
43+
]
44+
45+
3946
async def main() -> None:
4047
ai_agent_settings = AzureAIAgentSettings.create()
4148

4249
async with (
4350
DefaultAzureCredential() as creds,
44-
AzureAIAgent.create_client(
45-
credential=creds,
46-
conn_str=ai_agent_settings.project_connection_string.get_secret_value(),
47-
) as client,
51+
AzureAIAgent.create_client(credential=creds) as client,
4852
):
49-
AGENT_NAME = "Host"
50-
AGENT_INSTRUCTIONS = "Answer questions about the menu."
51-
52-
# Create agent definition
53+
# 1. Create an agent on the Azure AI agent service
5354
agent_definition = await client.agents.create_agent(
5455
model=ai_agent_settings.model_deployment_name,
55-
name=AGENT_NAME,
56-
instructions=AGENT_INSTRUCTIONS,
56+
name="Host",
57+
instructions="Answer questions about the menu.",
5758
)
5859

59-
# Create the AzureAI Agent
60+
# 2. Create a Semantic Kernel agent for the Azure AI agent
6061
agent = AzureAIAgent(
6162
client=client,
6263
definition=agent_definition,
6364
# Optionally configure polling options
6465
# polling_options=RunPollingOptions(run_polling_interval=timedelta(seconds=1)),
6566
)
6667

67-
# Add the sample plugin to the kernel
68+
# 3. Add a plugin to the agent via the kernel
6869
agent.kernel.add_plugin(MenuPlugin(), plugin_name="menu")
6970

70-
# Create a new thread
71+
# 4. Create a new thread on the Azure AI agent service
7172
thread = await client.agents.create_thread()
7273

73-
user_inputs = [
74-
"Hello",
75-
"What is the special soup?",
76-
"How much does that cost?",
77-
"Thank you",
78-
]
79-
8074
try:
81-
for user_input in user_inputs:
82-
# Add the user input as a chat message
83-
await agent.add_chat_message(
84-
thread_id=thread.id, message=ChatMessageContent(role=AuthorRole.USER, content=user_input)
85-
)
86-
print(f"# User: '{user_input}'")
87-
# Invoke the agent for the specified thread
75+
for user_input in USER_INPUTS:
76+
# 5. Add the user input as a chat message
77+
await agent.add_chat_message(thread_id=thread.id, message=user_input)
78+
print(f"# User: {user_input}")
79+
# 6. Invoke the agent for the specified thread for response
8880
async for content in agent.invoke(
8981
thread_id=thread.id,
9082
temperature=0.2, # override the agent-level temperature setting with a run-time value
9183
):
9284
if content.role != AuthorRole.TOOL:
9385
print(f"# Agent: {content.content}")
9486
finally:
87+
# 7. Cleanup: Delete the thread and agent
9588
await client.agents.delete_thread(thread.id)
9689
await client.agents.delete_agent(agent.id)
9790

91+
"""
92+
Sample Output:
93+
# User: Hello
94+
# Agent: Hello! How can I assist you today?
95+
# User: What is the special soup?
96+
# ...
97+
"""
98+
9899

99100
if __name__ == "__main__":
100101
asyncio.run(main())

python/samples/getting_started_with_agents/azure_ai_agent/step2_azure_ai_agent_chat.py

Lines changed: 31 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,14 @@
66

77
from semantic_kernel.agents import AgentGroupChat
88
from semantic_kernel.agents.azure_ai import AzureAIAgent, AzureAIAgentSettings
9-
from semantic_kernel.agents.strategies.termination.termination_strategy import TerminationStrategy
10-
from semantic_kernel.contents.chat_message_content import ChatMessageContent
11-
from semantic_kernel.contents.utils.author_role import AuthorRole
9+
from semantic_kernel.agents.strategies import TerminationStrategy
10+
from semantic_kernel.contents import AuthorRole
1211

13-
#####################################################################
14-
# The following sample demonstrates how to create an OpenAI #
15-
# assistant using either Azure OpenAI or OpenAI, a chat completion #
16-
# agent and have them participate in a group chat to work towards #
17-
# the user's requirement. #
18-
#####################################################################
12+
"""
13+
The following sample demonstrates how to create an OpenAI assistant using either
14+
Azure OpenAI or OpenAI, a chat completion agent and have them participate in a
15+
group chat to work towards the user's requirement.
16+
"""
1917

2018

2119
class ApprovalTerminationStrategy(TerminationStrategy):
@@ -44,66 +42,70 @@ async def should_agent_terminate(self, agent, history):
4442
Consider suggestions when refining an idea.
4543
"""
4644

45+
TASK = "a slogan for a new line of electric cars."
46+
4747

4848
async def main():
4949
ai_agent_settings = AzureAIAgentSettings.create()
5050

5151
async with (
5252
DefaultAzureCredential() as creds,
53-
AzureAIAgent.create_client(
54-
credential=creds,
55-
conn_str=ai_agent_settings.project_connection_string.get_secret_value(),
56-
) as client,
53+
AzureAIAgent.create_client(credential=creds) as client,
5754
):
58-
# Create the reviewer agent definition
55+
# 1. Create the reviewer agent on the Azure AI agent service
5956
reviewer_agent_definition = await client.agents.create_agent(
6057
model=ai_agent_settings.model_deployment_name,
6158
name=REVIEWER_NAME,
6259
instructions=REVIEWER_INSTRUCTIONS,
6360
)
64-
# Create the reviewer Azure AI Agent
61+
62+
# 2. Create a Semantic Kernel agent for the reviewer Azure AI agent
6563
agent_reviewer = AzureAIAgent(
6664
client=client,
6765
definition=reviewer_agent_definition,
6866
)
6967

70-
# Create the copy writer agent definition
68+
# 3. Create the copy writer agent on the Azure AI agent service
7169
copy_writer_agent_definition = await client.agents.create_agent(
7270
model=ai_agent_settings.model_deployment_name,
7371
name=COPYWRITER_NAME,
7472
instructions=COPYWRITER_INSTRUCTIONS,
7573
)
76-
# Create the copy writer Azure AI Agent
74+
75+
# 4. Create a Semantic Kernel agent for the copy writer Azure AI agent
7776
agent_writer = AzureAIAgent(
7877
client=client,
7978
definition=copy_writer_agent_definition,
8079
)
8180

81+
# 5. Place the agents in a group chat with a custom termination strategy
8282
chat = AgentGroupChat(
8383
agents=[agent_writer, agent_reviewer],
8484
termination_strategy=ApprovalTerminationStrategy(agents=[agent_reviewer], maximum_iterations=10),
8585
)
8686

87-
input = "a slogan for a new line of electric cars."
88-
8987
try:
90-
await chat.add_chat_message(ChatMessageContent(role=AuthorRole.USER, content=input))
91-
print(f"# {AuthorRole.USER}: '{input}'")
92-
88+
# 6. Add the task as a message to the group chat
89+
await chat.add_chat_message(message=TASK)
90+
print(f"# {AuthorRole.USER}: '{TASK}'")
91+
# 7. Invoke the chat
9392
async for content in chat.invoke():
9493
print(f"# {content.role} - {content.name or '*'}: '{content.content}'")
95-
96-
print(f"# IS COMPLETE: {chat.is_complete}")
97-
98-
print("*" * 60)
99-
print("Chat History (In Descending Order):\n")
100-
async for message in chat.get_chat_messages(agent=agent_reviewer):
101-
print(f"# {message.role} - {message.name or '*'}: '{message.content}'")
10294
finally:
95+
# 8. Cleanup: Delete the agents
10396
await chat.reset()
10497
await client.agents.delete_agent(agent_reviewer.id)
10598
await client.agents.delete_agent(agent_writer.id)
10699

100+
"""
101+
Sample Output:
102+
# AuthorRole.USER: 'a slogan for a new line of electric cars.'
103+
# AuthorRole.ASSISTANT - CopyWriter: '"Charge Ahead: Drive the Future."'
104+
# AuthorRole.ASSISTANT - ArtDirector: 'This slogan has a nice ring to it and captures the ...'
105+
# AuthorRole.ASSISTANT - CopyWriter: '"Plug In. Drive Green."'
106+
...
107+
"""
108+
107109

108110
if __name__ == "__main__":
109111
asyncio.run(main())

python/samples/getting_started_with_agents/azure_ai_agent/step3_azure_ai_agent_code_interpreter.py

Lines changed: 49 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -6,63 +6,83 @@
66
from azure.identity.aio import DefaultAzureCredential
77

88
from semantic_kernel.agents.azure_ai import AzureAIAgent, AzureAIAgentSettings
9-
from semantic_kernel.contents.chat_message_content import ChatMessageContent
10-
from semantic_kernel.contents.utils.author_role import AuthorRole
9+
from semantic_kernel.contents import AuthorRole
1110

12-
###################################################################
13-
# The following sample demonstrates how to create a simple, #
14-
# Azure AI agent that uses the code interpreter tool to answer #
15-
# a coding question. #
16-
###################################################################
11+
"""
12+
The following sample demonstrates how to create a simple, Azure AI agent that
13+
uses the code interpreter tool to answer a coding question.
14+
"""
15+
16+
TASK = "Use code to determine the values in the Fibonacci sequence that that are less then the value of 101."
1717

1818

1919
async def main() -> None:
2020
ai_agent_settings = AzureAIAgentSettings.create()
2121

2222
async with (
2323
DefaultAzureCredential() as creds,
24-
AzureAIAgent.create_client(
25-
credential=creds,
26-
conn_str=ai_agent_settings.project_connection_string.get_secret_value(),
27-
) as client,
24+
AzureAIAgent.create_client(credential=creds) as client,
2825
):
26+
# 1. Create an agent with a code interpreter on the Azure AI agent service
2927
code_interpreter = CodeInterpreterTool()
30-
31-
# Create agent definition
3228
agent_definition = await client.agents.create_agent(
3329
model=ai_agent_settings.model_deployment_name,
3430
tools=code_interpreter.definitions,
3531
tool_resources=code_interpreter.resources,
3632
)
3733

38-
# Create the AzureAI Agent
34+
# 2. Create a Semantic Kernel agent for the Azure AI agent
3935
agent = AzureAIAgent(
4036
client=client,
4137
definition=agent_definition,
4238
)
4339

44-
# Create a new thread
40+
# 3. Create a new thread on the Azure AI agent service
4541
thread = await client.agents.create_thread()
4642

47-
user_inputs = [
48-
"Use code to determine the values in the Fibonacci sequence that that are less then the value of 101."
49-
]
50-
5143
try:
52-
for user_input in user_inputs:
53-
# Add the user input as a chat message
54-
await agent.add_chat_message(
55-
thread_id=thread.id, message=ChatMessageContent(role=AuthorRole.USER, content=user_input)
56-
)
57-
print(f"# User: '{user_input}'")
58-
# Invoke the agent for the specified thread
59-
async for content in agent.invoke(thread_id=thread.id):
60-
if content.role != AuthorRole.TOOL:
61-
print(f"# Agent: {content.content}")
44+
# 4. Add the task as a chat message
45+
await agent.add_chat_message(thread_id=thread.id, message=TASK)
46+
print(f"# User: '{TASK}'")
47+
# 5. Invoke the agent for the specified thread for response
48+
async for content in agent.invoke(thread_id=thread.id):
49+
if content.role != AuthorRole.TOOL:
50+
print(f"# Agent: {content.content}")
6251
finally:
52+
# 6. Cleanup: Delete the thread and agent
6353
await client.agents.delete_thread(thread.id)
6454
await client.agents.delete_agent(agent.id)
6555

56+
"""
57+
Sample Output:
58+
# User: 'Use code to determine the values in the Fibonacci sequence that that are less then the value of 101.'
59+
# Agent: # Function to generate Fibonacci sequence values less than a given limit
60+
def fibonacci_less_than(limit):
61+
fib_sequence = []
62+
a, b = 0, 1
63+
while a < limit:
64+
fib_sequence.append(a)
65+
a, b = b, a + b
66+
a, b = 0, 1
67+
while a < limit:
68+
fib_sequence.append(a)
69+
a, b = 0, 1
70+
while a < limit:
71+
a, b = 0, 1
72+
a, b = 0, 1
73+
while a < limit:
74+
fib_sequence.append(a)
75+
a, b = b, a + b
76+
return fib_sequence
77+
78+
Generate Fibonacci sequence values less than 101
79+
fibonacci_values = fibonacci_less_than(101)
80+
fibonacci_values
81+
# Agent: The values in the Fibonacci sequence that are less than 101 are:
82+
83+
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
84+
"""
85+
6686

6787
if __name__ == "__main__":
6888
asyncio.run(main())

0 commit comments

Comments
 (0)