Skip to content

Commit 8eb2762

Browse files
authored
Merge pull request #4709 from aahill/release-build-agents-2
Python updates
2 parents eab50cd + 10c0f94 commit 8eb2762

File tree

12 files changed

+775
-319
lines changed

12 files changed

+775
-319
lines changed

articles/ai-services/agents/concepts/tracing.md

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,12 @@ Tracing solves this by allowing you to clearly see the inputs and outputs of eac
2626
The Agents playground in the Azure AI Foundry portal lets you trace threads and runs that your agents produce. To open a trace, select **Thread info** in an active thread. You can also optionally select **Metrics** to enable automatic evaluations of the model's performance across several dimensions of **AI quality** and **Risk and safety**.
2727

2828
> [!NOTE]
29-
> Evaluations are not available in the following regions.
30-
> * australiaeast
31-
> * japaneast
32-
> * southindia
33-
> * uksouth
29+
> * Evaluations are available for 24 hours after they're generated.
30+
> * Evaluations are not available in the following regions.
31+
> * australiaeast
32+
> * japaneast
33+
> * southindia
34+
> * uksouth
3435
3536
:::image type="content" source="../media/ai-foundry-tracing.png" alt-text="A screenshot of the agent playground in the Azure AI Foundry portal." lightbox="../media/ai-foundry-tracing.png":::
3637

articles/ai-services/agents/how-to/tools/azure-ai-search-samples.md

Lines changed: 62 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -35,110 +35,101 @@ Complete the [Azure AI Search tool setup](../../how-to/tools/azure-ai-search.md?
3535
:::zone pivot="python"
3636

3737
## Step 1: Create an Azure AI Client
38-
First, create an Azure AI Client using the connection string of your project.
38+
First, create an Azure AI Client using the endpoint of your project.
3939

4040
```python
4141
import os
4242
from azure.ai.projects import AIProjectClient
4343
from azure.identity import DefaultAzureCredential
44-
from azure.ai.projects.models import AzureAISearchTool
45-
46-
# Create an Azure AI Client from a connection string, copied from your Azure AI Foundry project.
47-
# At the moment, it should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<ProjectName>"
48-
# HostName can be found by navigating to your discovery_url and removing the leading "https://" and trailing "/discovery"
49-
# To find your discovery_url, run the CLI command: az ml workspace show -n {project_name} --resource-group {resource_group_name} --query discovery_url
50-
# Project Connection example: eastus.api.azureml.ms;my-subscription-id;my-resource-group;my-hub-name
5144

52-
connection_string = os.environ["PROJECT_CONNECTION_STRING"]
45+
# Retrieve the endpoint from environment variables
46+
project_endpoint = os.environ["PROJECT_ENDPOINT"]
5347

54-
project_client = AIProjectClient.from_connection_string(
55-
credential=DefaultAzureCredential(),
56-
conn_str=connection_string,
48+
# Initialize the AIProjectClient
49+
project_client = AIProjectClient(
50+
endpoint=project_endpoint,
51+
credential=DefaultAzureCredential(exclude_interactive_browser_credential=False),
52+
api_version="latest",
5753
)
5854
```
5955

60-
## Step 2: Get the connection ID for the Azure AI Search resource
61-
Get the connection ID of the Azure AI Search connection in the project. You can use the code snippet to print the connection ID of all the Azure AI Search connections in the project.
56+
## Step 2: Configure the Azure AI Search tool
57+
Using the connection ID of your Azure AI Search resource, configure the Azure AI Search tool to use your Azure AI Search index.
6258

6359
```python
64-
# AI Search resource connection ID
65-
# This code looks for the AI Search Connection ID and saves it as variable conn_id
66-
67-
# If you have more than one AI search connection, try to establish the value in your .env file.
68-
# Extract the connection list.
69-
conn_list = project_client.connections._list_connections()["value"]
70-
conn_id = ""
71-
72-
# Search in the metadata field of each connection in the list for the azure_ai_search type and get the id value to establish the variable
73-
for conn in conn_list:
74-
metadata = conn["properties"].get("metadata", {})
75-
if metadata.get("type", "").upper() == "AZURE_AI_SEARCH":
76-
conn_id = conn["id"]
77-
break
60+
from azure.ai.agents.models import AzureAISearchTool, AzureAISearchQueryType
61+
62+
# Define the Azure AI Search connection ID and index name
63+
azure_ai_conn_id = os.environ["AZURE_AI_CONNECTION_ID"]
64+
index_name = "sample_index"
65+
66+
# Initialize the Azure AI Search tool
67+
ai_search = AzureAISearchTool(
68+
index_connection_id=azure_ai_conn_id,
69+
index_name=index_name,
70+
query_type=AzureAISearchQueryType.SIMPLE, # Use SIMPLE query type
71+
top_k=3, # Retrieve the top 3 results
72+
filter="", # Optional filter for search results
73+
)
7874
```
7975

80-
## Step 3: Configure the Azure AI Search tool
81-
Using the connection ID you got in the previous step, you can now configure the Azure AI Search tool to use your Azure AI Search index.
76+
## Step 3: Create an agent with the Azure AI Search tool enabled
77+
Create an agent with the Azure AI Search tool attached. Change the model to the one deployed in your project.
8278

8379
```python
84-
# TO DO: replace this value with the connection ID of the search index
85-
conn_id = "/subscriptions/<your-subscription-id>/resourceGroups/<your-resource-group>/providers/Microsoft.MachineLearningServices/workspaces/<your-project-name>/connections/<your-azure-ai-search-connection-name>"
86-
87-
# Initialize agent AI search tool and add the search index connection ID and index name
88-
# TO DO: replace <your-index-name> with the name of the index you want to use
89-
ai_search = AzureAISearchTool(index_connection_id=conn_id, index_name="<your-index-name>",
90-
query_type="<select-search-type>")
91-
```
92-
93-
## Step 4: Create an agent with the Azure AI Search tool enabled
94-
Change the model to the one deployed in your project. You can find the model name in the Azure AI Foundry under the **Models** tab. You can also change the name and instructions of the agent to suit your needs.
80+
# Define the model deployment name
81+
model_deployment_name = os.environ["MODEL_DEPLOYMENT_NAME"]
9582

96-
```python
83+
# Create an agent with the Azure AI Search tool
9784
agent = project_client.agents.create_agent(
98-
model="gpt-4o-mini",
99-
name="my-assistant",
100-
instructions="You are a helpful assistant",
85+
model=model_deployment_name,
86+
name="my-agent",
87+
instructions="You are a helpful agent",
10188
tools=ai_search.definitions,
102-
tool_resources = ai_search.resources,
89+
tool_resources=ai_search.resources,
10390
)
10491
print(f"Created agent, ID: {agent.id}")
10592
```
10693

107-
## Step 5: Ask the agent questions about data in the index
108-
Now that the agent is created, ask it questions about the data in your Azure AI Search index. The example assumes your Azure AI Search index contains information about health care plans.
94+
## Step 4: Ask the agent questions about data in the index
95+
Now that the agent is created, ask it questions about the data in your Azure AI Search index.
10996

11097
```python
111-
# Create a thread
112-
thread = project_client.agents.create_thread()
113-
print(f"Created thread, thread ID: {thread.id}")
114-
115-
# Create a message
116-
message = project_client.agents.create_message(
98+
from azure.ai.agents.models import MessageRole, ListSortOrder
99+
100+
# Create a thread for communication
101+
thread = project_client.agents.threads.create()
102+
print(f"Created thread, ID: {thread.id}")
103+
104+
# Send a message to the thread
105+
message = project_client.agents.messages.create(
117106
thread_id=thread.id,
118-
role="user",
119-
content="what are my health insurance plan coverage types?",
107+
role=MessageRole.USER,
108+
content="What is the temperature rating of the cozynights sleeping bag?",
120109
)
121-
print(f"Created message, message ID: {message.id}")
122-
123-
# Run the agent
124-
run = project_client.agents.create_and_process_run(thread_id=thread.id, agent_id=agent.id)
110+
print(f"Created message, ID: {message['id']}")
111+
112+
# Create and process a run with the specified thread and agent
113+
run = project_client.agents.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)
125114
print(f"Run finished with status: {run.status}")
126-
115+
116+
# Check if the run failed
127117
if run.status == "failed":
128-
# Check if you got "Rate limit is exceeded.", then you want to get more quota
129118
print(f"Run failed: {run.last_error}")
130119

131-
# Get messages from the thread
132-
messages = project_client.agents.list_messages(thread_id=thread.id)
133-
print(f"Messages: {messages}")
134-
135-
assistant_message = ""
120+
# Fetch and log all messages in the thread
121+
messages = project_client.agents.messages.list(thread_id=thread.id, order=ListSortOrder.ASCENDING)
136122
for message in messages.data:
137-
if message["role"] == "assistant":
138-
assistant_message = message["content"][0]["text"]["value"]
123+
print(f"Role: {message.role}, Content: {message.content}")
124+
```
139125

140-
# Get the last message from the sender
141-
print(f"Assistant response: {assistant_message}")
126+
## Step 5: Clean up resources
127+
After completing the operations, delete the agent to clean up resources.
128+
129+
```python
130+
# Delete the agent
131+
project_client.agents.delete_agent(agent.id)
132+
print("Deleted agent")
142133
```
143134

144135
:::zone-end

articles/ai-services/agents/how-to/tools/azure-functions-samples.md

Lines changed: 59 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -67,97 +67,96 @@ def process_queue_message(msg: func.QueueMessage) -> None:
6767
In the sample below we create a client and an agent that has the tools definition for the Azure Function
6868

6969
```python
70-
# Initialize the client and create agent for the tools Azure Functions that the agent can use
70+
import os
71+
from azure.ai.projects import AIProjectClient
72+
from azure.identity import DefaultAzureCredential
73+
from azure.ai.agents.models import AzureFunctionStorageQueue, AzureFunctionTool
7174

7275
# Create a project client
7376
project_client = AIProjectClient.from_connection_string(
7477
credential=DefaultAzureCredential(),
7578
conn_str=os.environ["PROJECT_CONNECTION_STRING"]
7679
)
7780

78-
# Get the connection string for the storage account to send and receive the function calls to the queues
79-
storage_connection_string = os.environ["STORAGE_CONNECTION__queueServiceUri"]
81+
# Retrieve the storage service endpoint from environment variables
82+
storage_service_endpoint = os.environ["STORAGE_SERVICE_ENDPONT"]
83+
84+
# Define the Azure Function tool
85+
azure_function_tool = AzureFunctionTool(
86+
name="foo", # Name of the tool
87+
description="Get answers from the foo bot.", # Description of the tool's purpose
88+
parameters={ # Define the parameters required by the tool
89+
"type": "object",
90+
"properties": {
91+
"query": {"type": "string", "description": "The question to ask."},
92+
"outputqueueuri": {"type": "string", "description": "The full output queue URI."},
93+
},
94+
},
95+
input_queue=AzureFunctionStorageQueue( # Input queue configuration
96+
queue_name="azure-function-foo-input",
97+
storage_service_endpoint=storage_service_endpoint,
98+
),
99+
output_queue=AzureFunctionStorageQueue( # Output queue configuration
100+
queue_name="azure-function-tool-output",
101+
storage_service_endpoint=storage_service_endpoint,
102+
),
103+
)
80104

81-
# Create an agent with the Azure Function tool to get the weather
105+
# Initialize the AIProjectClient
106+
project_client = AIProjectClient(
107+
endpoint=os.environ["PROJECT_ENDPOINT"],
108+
credential=DefaultAzureCredential(),
109+
api_version="latest",
110+
)# Create an agent with the Azure Function tool
82111
agent = project_client.agents.create_agent(
83-
model="gpt-4o-mini",
84-
name="azure-function-agent-get-weather",
85-
instructions="You are a helpful support agent. Answer the user's questions to the best of your ability.",
86-
headers={"x-ms-enable-preview": "true"},
87-
tools=[
88-
{
89-
"type": "azure_function",
90-
"azure_function": {
91-
"function": {
92-
"name": "GetWeather",
93-
"description": "Get the weather in a location.",
94-
"parameters": {
95-
"type": "object",
96-
"properties": {
97-
"location": {"type": "string", "description": "The location to look up."}
98-
},
99-
"required": ["location"]
100-
}
101-
},
102-
"input_binding": {
103-
"type": "storage_queue",
104-
"storage_queue": {
105-
"queue_service_uri": storage_connection_string,
106-
"queue_name": "input"
107-
}
108-
},
109-
"output_binding": {
110-
"type": "storage_queue",
111-
"storage_queue": {
112-
"queue_service_uri": storage_connection_string,
113-
"queue_name": "output"
114-
}
115-
}
116-
}
117-
}
118-
],
112+
model=os.environ["MODEL_DEPLOYMENT_NAME"], # Model deployment name
113+
name="azure-function-agent-foo", # Name of the agent
114+
instructions=(
115+
"You are a helpful support agent. Use the provided function any time the prompt contains the string "
116+
"'What would foo say?'. When you invoke the function, ALWAYS specify the output queue URI parameter as "
117+
f"'{storage_service_endpoint}/azure-function-tool-output'. Always respond with \"Foo says\" and then the response from the tool."
118+
),
119+
tools=azure_function_tool.definitions, # Attach the tool definitions to the agent
119120
)
121+
print(f"Created agent, agent ID: {agent.id}")
120122
```
121123

122124
## Create a thread for the agent
123125

124126
```python
125-
# Create a thread
126-
thread = project_client.agents.create_thread()
127+
# Create a thread for communication
128+
thread = project_client.agents.threads.create()
127129
print(f"Created thread, thread ID: {thread.id}")
128130
```
129131

130132
## Create a run and check the output
131133

132134
```python
133-
# Send the prompt to the agent
134-
message = project_client.agents.create_message(
135+
# Create a message in the thread
136+
message = project_client.agents.messages.create(
135137
thread_id=thread.id,
136138
role="user",
137-
content="What is the weather in Seattle, WA?",
139+
content="What is the most prevalent element in the universe? What would foo say?", # Message content
138140
)
139-
print(f"Created message, message ID: {message.id}")
140-
141-
# Run the agent
142-
run = project_client.agents.create_run(thread_id=thread.id, agent_id=agent.id)
143-
# Monitor and process the run status. The function call should be placed on the input queue by the Agent Service for the Azure Function to pick up when requires_action is returned
144-
while run.status in ["queued", "in_progress", "requires_action"]:
145-
time.sleep(1)
146-
run = project_client.agents.get_run(thread_id=thread.id, run_id=run.id)
147-
148-
if run.status not in ["queued", "in_progress", "requires_action"]:
149-
break
141+
print(f"Created message, message ID: {message['id']}")
150142

143+
# Create and process a run for the agent to handle the message
144+
run = project_client.agents.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)
151145
print(f"Run finished with status: {run.status}")
146+
147+
# Check if the run failed
148+
if run.status == "failed":
149+
print(f"Run failed: {run.last_error}")
152150
```
153151

154152

155153
## Get the result of the run
156154

157155
```python
158-
# Get messages from the assistant thread
159-
messages = project_client.agents.get_messages(thread_id=thread.id)
160-
print(f"Messages: {messages}")
156+
# Retrieve and print all messages from the thread
157+
messages = project_client.agents.messages.list(thread_id=thread.id)
158+
for msg in messages:
159+
print(f"Role: {msg['role']}, Content: {msg['content']}")# Get messages from the assistant thread
161160

162161
# Get the last message from the assistant
163162
last_msg = messages.get_last_text_message_by_sender("assistant")
@@ -166,7 +165,7 @@ if last_msg:
166165

167166
# Delete the agent once done
168167
project_client.agents.delete_agent(agent.id)
169-
print("Deleted agent")
168+
print(f"Deleted agent")
170169
```
171170

172171
For any issues with the Python code, create an issue on the [sample code repository](https://github.com/Azure-Samples/azure-functions-ai-services-agent-python/issues)

0 commit comments

Comments
 (0)