|
| 1 | +# Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from typing import Annotated |
| 5 | + |
| 6 | +from azure.identity.aio import DefaultAzureCredential |
| 7 | + |
| 8 | +from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread |
| 9 | +from semantic_kernel.contents import ChatHistory, FunctionCallContent, FunctionResultContent |
| 10 | +from semantic_kernel.functions import kernel_function |
| 11 | + |
| 12 | +""" |
| 13 | +The following sample demonstrates how to create an Azure AI Agent |
| 14 | +and use it with streaming responses. Additionally, the invoke_stream |
| 15 | +configures a chat history callback to receive the conversation history |
| 16 | +once the streaming invocation is complete. The agent is configured to use |
| 17 | +a plugin that provides a list of specials from the menu and the price |
| 18 | +of the requested menu item. |
| 19 | +""" |
| 20 | + |
| 21 | + |
| 22 | +# Define a sample plugin for the sample |
| 23 | +class MenuPlugin: |
| 24 | + """A sample Menu Plugin used for the concept sample.""" |
| 25 | + |
| 26 | + @kernel_function(description="Provides a list of specials from the menu.") |
| 27 | + def get_specials(self) -> Annotated[str, "Returns the specials from the menu."]: |
| 28 | + return """ |
| 29 | + Special Soup: Clam Chowder |
| 30 | + Special Salad: Cobb Salad |
| 31 | + Special Drink: Chai Tea |
| 32 | + """ |
| 33 | + |
| 34 | + @kernel_function(description="Provides the price of the requested menu item.") |
| 35 | + def get_item_price( |
| 36 | + self, menu_item: Annotated[str, "The name of the menu item."] |
| 37 | + ) -> Annotated[str, "Returns the price of the menu item."]: |
| 38 | + return "$9.99" |
| 39 | + |
| 40 | + |
| 41 | +final_chat_history = ChatHistory() |
| 42 | + |
| 43 | + |
| 44 | +def handle_stream_completion(history: ChatHistory) -> None: |
| 45 | + final_chat_history.messages.extend(history.messages) |
| 46 | + |
| 47 | + |
| 48 | +async def main() -> None: |
| 49 | + ai_agent_settings = AzureAIAgentSettings.create() |
| 50 | + |
| 51 | + async with ( |
| 52 | + 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, |
| 57 | + ): |
| 58 | + AGENT_NAME = "Host" |
| 59 | + AGENT_INSTRUCTIONS = "Answer questions about the menu." |
| 60 | + |
| 61 | + # Create agent definition |
| 62 | + agent_definition = await client.agents.create_agent( |
| 63 | + model=ai_agent_settings.model_deployment_name, |
| 64 | + name=AGENT_NAME, |
| 65 | + instructions=AGENT_INSTRUCTIONS, |
| 66 | + ) |
| 67 | + |
| 68 | + # Create the AzureAI Agent |
| 69 | + agent = AzureAIAgent( |
| 70 | + client=client, |
| 71 | + definition=agent_definition, |
| 72 | + plugins=[MenuPlugin()], # add the sample plugin to the agent |
| 73 | + ) |
| 74 | + |
| 75 | + # Create a thread for the agent |
| 76 | + # If no thread is provided, a new thread will be |
| 77 | + # created and returned with the initial response |
| 78 | + thread: AzureAIAgentThread = None |
| 79 | + |
| 80 | + user_inputs = [ |
| 81 | + "Hello", |
| 82 | + "What is the special soup?", |
| 83 | + "How much does that cost?", |
| 84 | + "Thank you", |
| 85 | + ] |
| 86 | + |
| 87 | + try: |
| 88 | + for user_input in user_inputs: |
| 89 | + print(f"# User: '{user_input}'") |
| 90 | + first_chunk = True |
| 91 | + async for response in agent.invoke_stream( |
| 92 | + messages=user_input, |
| 93 | + thread=thread, |
| 94 | + on_complete=handle_stream_completion, |
| 95 | + ): |
| 96 | + if first_chunk: |
| 97 | + print(f"# {response.role}: ", end="", flush=True) |
| 98 | + first_chunk = False |
| 99 | + print(response.content, end="", flush=True) |
| 100 | + thread = response.thread |
| 101 | + print() |
| 102 | + finally: |
| 103 | + # Cleanup: Delete the thread and agent |
| 104 | + await thread.delete() if thread else None |
| 105 | + await client.agents.delete_agent(agent.id) |
| 106 | + |
| 107 | + # Print the final chat history |
| 108 | + print("\nFinal chat history:") |
| 109 | + for msg in final_chat_history.messages: |
| 110 | + if any(isinstance(item, FunctionResultContent) for item in msg.items): |
| 111 | + for fr in msg.items: |
| 112 | + if isinstance(fr, FunctionResultContent): |
| 113 | + print(f"Function Result:> {fr.result} for function: {fr.name}") |
| 114 | + elif any(isinstance(item, FunctionCallContent) for item in msg.items): |
| 115 | + for fcc in msg.items: |
| 116 | + if isinstance(fcc, FunctionCallContent): |
| 117 | + print(f"Function Call:> {fcc.name} with arguments: {fcc.arguments}") |
| 118 | + else: |
| 119 | + print(f"{msg.role}: {msg.content}") |
| 120 | + |
| 121 | + |
| 122 | +if __name__ == "__main__": |
| 123 | + asyncio.run(main()) |
0 commit comments