Skip to content

Commit

Permalink
Address comments second batch
Browse files Browse the repository at this point in the history
  • Loading branch information
TaoChenOSU committed Jan 30, 2025
1 parent 439dc62 commit 4740657
Show file tree
Hide file tree
Showing 17 changed files with 816 additions and 378 deletions.
4 changes: 2 additions & 2 deletions python/samples/concepts/agents/bedrock_agent/.env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
AGENT_ROLE_AMAZON_RESOURCE_NAME=[YOUR_AGENT_ROLE_AMAZON_RESOURCE_NAME]
FOUNDATION_MODEL=[YOUR_FOUNDATION_MODEL]
BEDROCK_AGENT_AGENT_RESOURCE_ROLE_ARN=[YOUR_AGENT_ROLE_AMAZON_RESOURCE_NAME]
BEDROCK_AGENT_FOUNDATION_MODEL=[YOUR_FOUNDATION_MODEL]
Original file line number Diff line number Diff line change
Expand Up @@ -3,59 +3,53 @@
import asyncio
import uuid

from samples.concepts.agents.bedrock_agent.setup_utils import use_existing_agent, use_new_agent
from semantic_kernel.agents.bedrock.bedrock_agent import BedrockAgent

# This sample shows how to interact with a Bedrock agent in the simplest way.
# This sample uses the following main component(s):
# - a Bedrock agent
# You will learn how to create a new or connect to an existing Bedrock agent and talk to it.
# You will learn how to create a new Bedrock agent and talk to it.

# By default, this sample will create a new agent that will be deleted after the session ends.
# If you want to use an existing agent, set this to False and fill in required parameters.
CREATE_NEW_AGENT = True

# If you want to enable streaming, set this to True.
# In order to perform streaming, you need to have the permission on action: bedrock:InvokeModelWithResponseStream
STREAMING = False

# Common parameters whether creating a new agent or using an existing agent
AGENT_NAME = "semantic-kernel-bedrock-agent-simple-chat-sample"

# If creating a new agent, you need to specify the following:
AGENT_NAME = "semantic-kernel-bedrock-agent"
INSTRUCTION = "You are a friendly assistant. You help people find information."

# If using an existing agent, you need to specify the following:
AGENT_ID = ""


async def main():
if CREATE_NEW_AGENT:
bedrock_agent = await use_new_agent(AGENT_NAME, INSTRUCTION)
else:
bedrock_agent = await use_existing_agent(AGENT_ID, AGENT_NAME)
bedrock_agent = await BedrockAgent.create(AGENT_NAME, instructions=INSTRUCTION)

# Use a uiud as the session id
new_session_id = str(uuid.uuid4())

# Invoke the agent
if STREAMING:
print("Response: ")
async for response in bedrock_agent.invoke_stream(
session_id=new_session_id,
input_text="Hi, how are you?",
):
print(response, end="")
else:
async for response in bedrock_agent.invoke(
session_id=new_session_id,
input_text="Hi, how are you?",
):
print(f"Response:\n{response}")

if CREATE_NEW_AGENT:
# Delete the agent if it was created in this session
try:
while True:
user_input = input("User:> ")
if user_input == "exit":
print("\n\nExiting chat...")
break

# Invoke the agent
# The chat history is maintained in the session
async for response in bedrock_agent.invoke(
session_id=new_session_id,
input_text=user_input,
):
print(f"Bedrock agent: {response}")
except KeyboardInterrupt:
print("\n\nExiting chat...")
return False
except EOFError:
print("\n\nExiting chat...")
return False
finally:
# Delete the agent
await bedrock_agent.delete_agent()

# Sample output (using anthropic.claude-3-haiku-20240307-v1:0):
# User:> Hi, my name is John.
# Bedrock agent: Hello John. How can I help you?
# User:> What is my name?
# Bedrock agent: Your name is John.


if __name__ == "__main__":
asyncio.run(main())
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Copyright (c) Microsoft. All rights reserved.

import asyncio
import uuid

from semantic_kernel.agents.bedrock.bedrock_agent import BedrockAgent

# This sample shows how to interact with a Bedrock agent via streaming in the simplest way.
# This sample uses the following main component(s):
# - a Bedrock agent
# You will learn how to create a new Bedrock agent and talk to it.

AGENT_NAME = "semantic-kernel-bedrock-agent"
INSTRUCTION = "You are a friendly assistant. You help people find information."


async def main():
bedrock_agent = await BedrockAgent.create(AGENT_NAME, instructions=INSTRUCTION)

# Use a uiud as the session id
new_session_id = str(uuid.uuid4())

try:
while True:
user_input = input("User:> ")
if user_input == "exit":
print("\n\nExiting chat...")
break

# Invoke the agent
# The chat history is maintained in the session
print("Bedrock agent: ", end="")
async for response in bedrock_agent.invoke_stream(
session_id=new_session_id,
input_text=user_input,
):
print(response, end="")
print()
except KeyboardInterrupt:
print("\n\nExiting chat...")
return False
except EOFError:
print("\n\nExiting chat...")
return False
finally:
# Delete the agent
await bedrock_agent.delete_agent()

# Sample output (using anthropic.claude-3-haiku-20240307-v1:0):
# User:> Hi, my name is John.
# Bedrock agent: Hello John. How can I help you?
# User:> What is my name?
# Bedrock agent: Your name is John.


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

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Copyright (c) Microsoft. All rights reserved.

import asyncio
import os
import uuid

from semantic_kernel.agents.bedrock.bedrock_agent import BedrockAgent
from semantic_kernel.contents.binary_content import BinaryContent
from semantic_kernel.contents.chat_message_content import ChatMessageContent

# This sample shows how to interact with a Bedrock agent that is capable of writing and executing code.
# This sample uses the following main component(s):
# - a Bedrock agent
# You will learn how to create a new Bedrock agent and ask it a question that requires coding to answer.
# After running this sample, a bar chart will be generated and saved to a file in the same directory
# as this script.

AGENT_NAME = "semantic-kernel-bedrock-agent"
INSTRUCTION = "You are a friendly assistant. You help people find information."


ASK = """
Create a bar chart for the following data:
Panda 5
Tiger 8
Lion 3
Monkey 6
Dolpin 2
"""


async def main():
bedrock_agent = await BedrockAgent.create(
AGENT_NAME,
instructions=INSTRUCTION,
enable_code_interpreter=True,
)

# Use a uiud as the session id
new_session_id = str(uuid.uuid4())

# Placeholder for the file generated by the code interpreter
binary_item: BinaryContent | None = None

try:
# Invoke the agent
async for response in bedrock_agent.invoke(
session_id=new_session_id,
input_text=ASK,
):
print(f"Response:\n{response}")
assert isinstance(response, ChatMessageContent) # nosec
binary_item = next(item for item in response.items if isinstance(item, BinaryContent))
finally:
# Delete the agent
await bedrock_agent.delete_agent()

# Save the chart to a file
if not binary_item:
raise RuntimeError("No chart generated")

file_path = os.path.join(os.path.dirname(__file__), binary_item.metadata["name"])
binary_item.write_to_file(os.path.join(os.path.dirname(__file__), binary_item.metadata["name"]))
print(f"Chart saved to {file_path}")

# Sample output (using anthropic.claude-3-haiku-20240307-v1:0):
# Response:
# Here is the bar chart for the given data:
# [A bar chart showing the following data:
# Panda 5
# Tiger 8
# Lion 3
# Monkey 6
# Dolpin 2]
# Chart saved to ...


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

0 comments on commit 4740657

Please sign in to comment.