|
| 1 | +# Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +import asyncio |
| 4 | + |
| 5 | +import boto3 |
| 6 | + |
| 7 | +from semantic_kernel.agents.bedrock.bedrock_agent import BedrockAgent |
| 8 | + |
| 9 | +""" |
| 10 | +The following sample demonstrates how to use an already existing |
| 11 | +Bedrock Agent within Semantic Kernel. This sample requires that you |
| 12 | +have an existing agent created either previously in code or via the |
| 13 | +AWS Console. |
| 14 | +This sample uses the following main component(s): |
| 15 | +- a Bedrock agent |
| 16 | +You will learn how to retrieve a Bedrock agent and talk to it. |
| 17 | +""" |
| 18 | + |
| 19 | +# Replace "your-agent-id" with the ID of the agent you want to use |
| 20 | +AGENT_ID = "your-agent-id" |
| 21 | + |
| 22 | + |
| 23 | +async def main(): |
| 24 | + client = boto3.client("bedrock-agent") |
| 25 | + agent_model = client.get_agent(agentId=AGENT_ID)["agent"] |
| 26 | + bedrock_agent = BedrockAgent(agent_model) |
| 27 | + session_id = BedrockAgent.create_session_id() |
| 28 | + |
| 29 | + try: |
| 30 | + while True: |
| 31 | + user_input = input("User:> ") |
| 32 | + if user_input == "exit": |
| 33 | + print("\n\nExiting chat...") |
| 34 | + break |
| 35 | + |
| 36 | + # Invoke the agent |
| 37 | + # The chat history is maintained in the session |
| 38 | + async for response in bedrock_agent.invoke( |
| 39 | + session_id=session_id, |
| 40 | + input_text=user_input, |
| 41 | + ): |
| 42 | + print(f"Bedrock agent: {response}") |
| 43 | + except KeyboardInterrupt: |
| 44 | + print("\n\nExiting chat...") |
| 45 | + return False |
| 46 | + except EOFError: |
| 47 | + print("\n\nExiting chat...") |
| 48 | + return False |
| 49 | + |
| 50 | + # Sample output (using anthropic.claude-3-haiku-20240307-v1:0): |
| 51 | + # User:> Hi, my name is John. |
| 52 | + # Bedrock agent: Hello John. How can I help you? |
| 53 | + # User:> What is my name? |
| 54 | + # Bedrock agent: Your name is John. |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + asyncio.run(main()) |
0 commit comments