1# pylint: disable=line-too-long,useless-suppression
2# ------------------------------------
3# Copyright (c) Microsoft Corporation.
4# Licensed under the MIT License.
5# ------------------------------------
6
7"""
8FILE: sample_agents_openapi_connection_auth.py
9
10DESCRIPTION:
11 This sample demonstrates how to use agent operations with the
12 OpenAPI tool from the Azure Agents service using a synchronous client, using
13 custom key authentication against the TripAdvisor API.
14 To learn more about OpenAPI specs, visit https://learn.microsoft.com/openapi
15
16USAGE:
17 python sample_agents_openapi_connection_auth.py
18
19 Before running the sample:
20
21 Set up an account at https://www.tripadvisor.com/developers and get an API key.
22
23 Set up a custom key connection and save the connection name following the steps at
24 https://aka.ms/azsdk/azure-ai-agents/custom-key-setup
25
26 Save that connection name as the PROJECT_OPENAPI_CONNECTION_NAME environment variable
27
28 pip install azure-ai-projects azure-ai-agents azure-identity jsonref
29
30 Set this environment variables with your own values:
31 PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the Overview
32 page of your Azure AI Foundry portal.
33 PROJECT_OPENAPI_CONNECTION_NAME - the connection name for the OpenAPI connection, taken from Azure AI Foundry.
34 MODEL_DEPLOYMENT_NAME - name of the model deployment in the project to use Agents against
35"""
36
37import os
38import jsonref
39from azure.ai.projects import AIProjectClient
40from azure.identity import DefaultAzureCredential
41from azure.ai.agents.models import OpenApiTool, OpenApiConnectionAuthDetails, OpenApiConnectionSecurityScheme
42
43asset_file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../assets/tripadvisor_openapi.json"))
44
45project_client = AIProjectClient(
46 endpoint=os.environ["PROJECT_ENDPOINT"],
47 credential=DefaultAzureCredential(),
48)
49
50model_name = os.environ["MODEL_DEPLOYMENT_NAME"]
51connection_id = project_client.connections.get(os.environ["PROJECT_OPENAPI_CONNECTION_NAME"]).id
52
53print(connection_id)
54
55with open(asset_file_path, "r") as f:
56 openapi_spec = jsonref.loads(f.read())
57
58# Create Auth object for the OpenApiTool (note that connection or managed identity auth setup requires additional setup in Azure)
59auth = OpenApiConnectionAuthDetails(security_scheme=OpenApiConnectionSecurityScheme(connection_id=connection_id))
60
61# Initialize an Agent OpenApi tool using the read in OpenAPI spec
62openapi = OpenApiTool(
63 name="get_weather", spec=openapi_spec, description="Retrieve weather information for a location", auth=auth
64)
65
66# Create an Agent with OpenApi tool and process Agent run
67with project_client:
68 agents_client = project_client.agents
69
70 agent = agents_client.create_agent(
71 model=model_name, name="my-agent", instructions="You are a helpful agent", tools=openapi.definitions
72 )
73 print(f"Created agent, ID: {agent.id}")
74
75 # Create thread for communication
76 thread = agents_client.threads.create()
77 print(f"Created thread, ID: {thread.id}")
78
79 # Create message to thread
80 message = agents_client.messages.create(
81 thread_id=thread.id,
82 role="user",
83 content="Summarize the reviews for the top rated hotel in Paris",
84 )
85 print(f"Created message: {message['id']}")
86
87 # Create and process an Agent run in thread with tools
88 run = agents_client.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)
89 print(f"Run finished with status: {run.status}")
90
91 if run.status == "failed":
92 print(f"Run failed: {run.last_error}")
93
94 # Delete the Agent when done
95 agents_client.delete_agent(agent.id)
96 print("Deleted agent")
97
98 # Fetch and log all messages
99 messages = agents_client.messages.list(thread_id=thread.id)
100 for msg in messages:
101 if msg.text_messages:
102 last_text = msg.text_messages[-1]
103 print(f"{msg.role}: {last_text.text.value}")