|
| 1 | +# Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +import asyncio |
| 4 | + |
| 5 | +from azure.identity.aio import DefaultAzureCredential |
| 6 | + |
| 7 | +from semantic_kernel.agents.azure_ai import AzureAIAgent |
| 8 | + |
| 9 | +""" |
| 10 | +The following sample demonstrates how to use an already existing |
| 11 | +Azure AI Agent within Semantic Kernel. This sample requires that you |
| 12 | +have an existing agent created either previously in code or via the |
| 13 | +Azure Portal (or CLI). |
| 14 | +""" |
| 15 | + |
| 16 | + |
| 17 | +# Simulate a conversation with the agent |
| 18 | +USER_INPUTS = [ |
| 19 | + "Why is the sky blue?", |
| 20 | +] |
| 21 | + |
| 22 | + |
| 23 | +async def main() -> None: |
| 24 | + async with ( |
| 25 | + DefaultAzureCredential() as creds, |
| 26 | + AzureAIAgent.create_client(credential=creds) as client, |
| 27 | + ): |
| 28 | + # 1. Retrieve the agent definition based on the `assistant_id` |
| 29 | + # Replace the "your-assistant-id" with the actual assistant ID |
| 30 | + # you want to use. |
| 31 | + agent_definition = await client.agents.get_agent( |
| 32 | + assistant_id="your-assistant-id", |
| 33 | + ) |
| 34 | + |
| 35 | + # 2. Create a Semantic Kernel agent for the Azure AI agent |
| 36 | + agent = AzureAIAgent( |
| 37 | + client=client, |
| 38 | + definition=agent_definition, |
| 39 | + ) |
| 40 | + |
| 41 | + # 3. Create a new thread on the Azure AI agent service |
| 42 | + thread = await client.agents.create_thread() |
| 43 | + |
| 44 | + try: |
| 45 | + for user_input in USER_INPUTS: |
| 46 | + # 4. Add the user input as a chat message |
| 47 | + await agent.add_chat_message(thread_id=thread.id, message=user_input) |
| 48 | + print(f"# User: '{user_input}'") |
| 49 | + # 5. Invoke the agent for the specified thread for response |
| 50 | + response = await agent.get_response(thread_id=thread.id) |
| 51 | + print(f"# {response.name}: {response}") |
| 52 | + finally: |
| 53 | + # 6. Cleanup: Delete the thread and agent |
| 54 | + await client.agents.delete_thread(thread.id) |
| 55 | + # Do not clean up the assistant so it can be used again |
| 56 | + |
| 57 | + """ |
| 58 | + Sample Output: |
| 59 | + # User: 'Why is the sky blue?' |
| 60 | + # Agent: The sky appears blue because molecules in the Earth's atmosphere scatter sunlight, |
| 61 | + and blue light is scattered more than other colors due to its shorter wavelength. |
| 62 | + """ |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + asyncio.run(main()) |
0 commit comments