|
| 1 | +# pylint: disable=line-too-long,useless-suppression |
| 2 | +# ------------------------------------ |
| 3 | +# Copyright (c) Microsoft Corporation. |
| 4 | +# Licensed under the MIT License. |
| 5 | +# ------------------------------------ |
| 6 | + |
| 7 | +""" |
| 8 | +DESCRIPTION: |
| 9 | + This sample demonstrates how to use agent operations with the |
| 10 | + OpenAPI tool from the Azure Agents service using a synchronous client. |
| 11 | + To learn more about OpenAPI specs, visit https://learn.microsoft.com/openapi |
| 12 | +
|
| 13 | +USAGE: |
| 14 | + python legalfly.py |
| 15 | +
|
| 16 | + Before running the sample: |
| 17 | +
|
| 18 | + pip install azure-ai-projects azure-ai-agents azure-identity python-dotenv jsonref |
| 19 | +
|
| 20 | + Set these environment variables with your own values: |
| 21 | + 1) PROJECT_ENDPOINT - the Azure AI Agents endpoint. |
| 22 | + 2) MODEL - The deployment name of the AI model, as found under the "Name" column in |
| 23 | + the "Models + endpoints" tab in your Azure AI Foundry project. |
| 24 | + 3) LEGALFLY_API_CONNECTION_NAME - The name of the connection for the LegalFly API. |
| 25 | +""" |
| 26 | +# <initialization> |
| 27 | +# Import necessary libraries |
| 28 | +import os |
| 29 | +import jsonref |
| 30 | +from azure.ai.projects import AIProjectClient |
| 31 | +from azure.identity import DefaultAzureCredential |
| 32 | +from azure.ai.agents.models import OpenApiTool, OpenApiConnectionAuthDetails, OpenApiConnectionSecurityScheme |
| 33 | +from dotenv import load_dotenv |
| 34 | + |
| 35 | +load_dotenv() |
| 36 | + |
| 37 | +# endpoint should be in the format "https://<your-ai-services-resource-name>.services.ai.azure.com/api/projects/<your-project-name>" |
| 38 | +endpoint = os.environ["PROJECT_ENDPOINT"] |
| 39 | +model = os.environ.get("MODEL", "gpt-4o") |
| 40 | +connection_name = os.environ["LEGALFLY_API_CONNECTION_NAME"] |
| 41 | + |
| 42 | + |
| 43 | +# Initialize the project client using the endpoint and default credentials |
| 44 | +with AIProjectClient.from_connection_string( |
| 45 | + conn_str=endpoint, |
| 46 | + credential=DefaultAzureCredential(exclude_interactive_browser_credential=False), |
| 47 | +) as project_client: |
| 48 | + # </initialization> |
| 49 | + |
| 50 | + # Load the OpenAPI specification for the service from a local JSON file using jsonref to handle references |
| 51 | + with open("./legalfly.json", "r") as f: |
| 52 | + openapi_spec = jsonref.loads(f.read()) |
| 53 | + |
| 54 | + conn_id = project_client.connections.get(connection_name=connection_name).id |
| 55 | + # Create Auth object for the OpenApiTool (note that connection or managed identity auth setup requires additional setup in Azure) |
| 56 | + auth = OpenApiConnectionAuthDetails(security_scheme=OpenApiConnectionSecurityScheme(connection_id=conn_id)) |
| 57 | + |
| 58 | + |
| 59 | + # Initialize the main OpenAPI tool definition for weather |
| 60 | + openapi_tool = OpenApiTool( |
| 61 | + name="getLegalCounsel", |
| 62 | + spec=openapi_spec, |
| 63 | + description="LegalFly legal counsel API", |
| 64 | + auth=auth |
| 65 | + ) |
| 66 | + |
| 67 | + # <agent_creation> |
| 68 | + # --- Agent Creation --- |
| 69 | + # Create an agent configured with the combined OpenAPI tool definitions |
| 70 | + agent = project_client.agents.create_agent( |
| 71 | + model=model, # Specify the model deployment |
| 72 | + name="my-agent", # Give the agent a name |
| 73 | + instructions="You are a helpful AI legal assistant. Act like a friendly person who possesses a lot of legal knowledge.", |
| 74 | + tools=openapi_tool.definitions, # Provide the list of tool definitions |
| 75 | + ) |
| 76 | + print(f"Created agent, ID: {agent.id}") |
| 77 | + # </agent_creation> |
| 78 | + |
| 79 | + # <thread_management> |
| 80 | + # --- Thread Management --- |
| 81 | + # Create a new conversation thread for the interaction |
| 82 | + thread = project_client.agents.create_thread() |
| 83 | + print(f"Created thread, ID: {thread.id}") |
| 84 | + |
| 85 | + # Create the initial user message in the thread |
| 86 | + message = project_client.agents.create_message( |
| 87 | + thread_id=thread.id, |
| 88 | + role="user", |
| 89 | + # give an example of a user message that the agent can respond to |
| 90 | + content="What do I need to start a company in California?", |
| 91 | + ) |
| 92 | + print(f"Created message, ID: {message.id}") |
| 93 | + # </thread_management> |
| 94 | + |
| 95 | + # <message_processing> |
| 96 | + # --- Message Processing (Run Creation and Auto-processing) --- |
| 97 | + # Create and automatically process the run, handling tool calls internally |
| 98 | + # Note: This differs from the function_tool example where tool calls are handled manually |
| 99 | + run = project_client.agents.create_and_process_run(thread_id=thread.id, agent_id=agent.id) |
| 100 | + print(f"Run finished with status: {run.status}") |
| 101 | + # </message_processing> |
| 102 | + |
| 103 | + # <tool_execution_loop> # Note: This section now processes completed steps, as create_and_process_run handles execution |
| 104 | + # --- Post-Run Step Analysis --- |
| 105 | + if run.status == "failed": |
| 106 | + print(f"Run failed: {run.last_error}") |
| 107 | + |
| 108 | + # Retrieve the steps taken during the run for analysis |
| 109 | + run_steps = project_client.agents.list_run_steps(thread_id=thread.id, run_id=run.id) |
| 110 | + |
| 111 | + # Loop through each step to display information |
| 112 | + for step in run_steps.data: |
| 113 | + print(f"Step {step['id']} status: {step['status']}") |
| 114 | + |
| 115 | + # Check if there are tool calls recorded in the step details |
| 116 | + step_details = step.get("step_details", {}) |
| 117 | + tool_calls = step_details.get("tool_calls", []) |
| 118 | + |
| 119 | + if tool_calls: |
| 120 | + print(" Tool calls:") |
| 121 | + for call in tool_calls: |
| 122 | + print(f" Tool Call ID: {call.get('id')}") |
| 123 | + print(f" Type: {call.get('type')}") |
| 124 | + |
| 125 | + function_details = call.get("function", {}) |
| 126 | + if function_details: |
| 127 | + print(f" Function name: {function_details.get('name')}") |
| 128 | + print() # Add an extra newline between steps for readability |
| 129 | + # </tool_execution_loop> |
| 130 | + |
| 131 | + # <cleanup> |
| 132 | + # --- Cleanup --- |
| 133 | + # Delete the agent resource to clean up |
| 134 | + project_client.agents.delete_agent(agent.id) |
| 135 | + print("Deleted agent") |
| 136 | + |
| 137 | + # Fetch and log all messages exchanged during the conversation thread |
| 138 | + messages = project_client.agents.list_messages(thread_id=thread.id) |
| 139 | + print(f"Messages: {messages}") |
| 140 | + messages_array = messages.data |
| 141 | + for m in messages_array: |
| 142 | + content = m.get("content", []) |
| 143 | + if content and content[0].get("type") == "text": |
| 144 | + text_value = content[0].get("text", {}).get("value", "") |
| 145 | + print(f"Text: {text_value}") |
| 146 | + # </cleanup> |
0 commit comments