Skip to content

Commit 74015b9

Browse files
authored
Merge branch 'main' into Update-readme-final-samples
2 parents e553728 + f073202 commit 74015b9

File tree

17 files changed

+849
-365
lines changed

17 files changed

+849
-365
lines changed
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
using Azure.AI.Agents.Persistent;
2+
using Azure.Identity;
3+
using System;
4+
using Microsoft.Extensions.Configuration;
5+
using Azure;
6+
using System.Threading.Tasks;
7+
8+
// Get Connection information from App Configuration
9+
IConfigurationRoot configuration = new ConfigurationBuilder()
10+
.SetBasePath(AppContext.BaseDirectory)
11+
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
12+
.Build();
13+
14+
var projectEndpoint = configuration["ProjectEndpoint"];
15+
var modelDeploymentName = configuration["ModelDeploymentName"];
16+
var fabricConnectionId = configuration["FabricConnectionId"];
17+
18+
// Create the Agent Client
19+
PersistentAgentsClient agentClient = new(
20+
projectEndpoint,
21+
new DefaultAzureCredential(),
22+
new PersistentAgentsAdministrationClientOptions(
23+
PersistentAgentsAdministrationClientOptions.ServiceVersion.V2025_05_01
24+
));
25+
26+
// Create the MicrosoftFabricToolDefinition object needed when creating the agent
27+
ToolConnectionList connectionList = new()
28+
{
29+
ConnectionList = { new ToolConnection(fabricConnectionId) }
30+
};
31+
MicrosoftFabricToolDefinition fabricTool = new(connectionList);
32+
33+
// Create the Agent
34+
PersistentAgent agent = await agentClient.Administration.CreateAgentAsync(
35+
model: modelDeploymentName,
36+
name: "my-assistant",
37+
instructions: "You are a helpful assistant.",
38+
tools: [fabricTool]);
39+
40+
PersistentAgentThread thread = await agentClient.Threads.CreateThreadAsync();
41+
42+
// Create message and run the agent
43+
ThreadMessage message = await agentClient.Messages.CreateMessageAsync(
44+
thread.Id,
45+
MessageRole.User,
46+
"What are the top 3 weather events with highest property damage?");
47+
ThreadRun run = agentClient.Runs.CreateRun(thread, agent);
48+
49+
// Wait for the agent to finish running
50+
do
51+
{
52+
await Task.Delay(TimeSpan.FromMilliseconds(500));
53+
run = await agentClient.Runs.GetRunAsync(thread.Id, run.Id);
54+
}
55+
while (run.Status == RunStatus.Queued
56+
|| run.Status == RunStatus.InProgress);
57+
58+
// Confirm that the run completed successfully
59+
if (run.Status != RunStatus.Completed)
60+
{
61+
throw new Exception("Run did not complete successfully, error: " + run.LastError?.Message);
62+
}
63+
64+
// Retrieve all messages from the agent client
65+
AsyncPageable<ThreadMessage> messages = agentClient.Messages.GetMessagesAsync(
66+
threadId: thread.Id,
67+
order: ListSortOrder.Ascending
68+
);
69+
70+
// Process messages in order
71+
await foreach (ThreadMessage threadMessage in messages)
72+
{
73+
Console.Write($"{threadMessage.CreatedAt:yyyy-MM-dd HH:mm:ss} - {threadMessage.Role,10}: ");
74+
foreach (MessageContent contentItem in threadMessage.ContentItems)
75+
{
76+
if (contentItem is MessageTextContent textItem)
77+
{
78+
string response = textItem.Text;
79+
80+
// If we have Text URL citation annotations, reformat the response to show title & URL for citations
81+
if (textItem.Annotations != null)
82+
{
83+
foreach (MessageTextAnnotation annotation in textItem.Annotations)
84+
{
85+
if (annotation is MessageTextUrlCitationAnnotation urlAnnotation)
86+
{
87+
response = response.Replace(urlAnnotation.Text, $" [{urlAnnotation.UrlCitation.Title}]({urlAnnotation.UrlCitation.Url})");
88+
}
89+
}
90+
}
91+
Console.Write($"Agent response: {response}");
92+
}
93+
else if (contentItem is MessageImageFileContent imageFileItem)
94+
{
95+
Console.Write($"<image from ID: {imageFileItem.FileId}");
96+
}
97+
Console.WriteLine();
98+
}
99+
}
100+
101+
// Delete thread and agent
102+
await agentClient.Threads.DeleteThreadAsync(threadId: thread.Id);
103+
await agentClient.Administration.DeleteAgentAsync(agentId: agent.Id);
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
using Azure.AI.Agents.Persistent;
2+
using Azure.Identity;
3+
using System;
4+
using Microsoft.Extensions.Configuration;
5+
using System.Threading;
6+
using Azure;
7+
8+
// Get Connection information from App Configuration
9+
IConfigurationRoot configuration = new ConfigurationBuilder()
10+
.SetBasePath(AppContext.BaseDirectory)
11+
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
12+
.Build();
13+
14+
var projectEndpoint = configuration["ProjectEndpoint"];
15+
var modelDeploymentName = configuration["ModelDeploymentName"];
16+
var fabricConnectionId = configuration["FabricConnectionId"];
17+
18+
// Create the Agent Client
19+
PersistentAgentsClient agentClient = new(
20+
projectEndpoint,
21+
new DefaultAzureCredential(),
22+
new PersistentAgentsAdministrationClientOptions(
23+
PersistentAgentsAdministrationClientOptions.ServiceVersion.V2025_05_01
24+
));
25+
26+
// Create the MicrosoftFabricToolDefinition object needed when creating the agent
27+
ToolConnectionList connectionList = new()
28+
{
29+
ConnectionList = { new ToolConnection(fabricConnectionId) }
30+
};
31+
MicrosoftFabricToolDefinition fabricTool = new(connectionList);
32+
33+
// Create the Agent
34+
PersistentAgent agent = agentClient.Administration.CreateAgent(
35+
model: modelDeploymentName,
36+
name: "my-assistant",
37+
instructions: "You are a helpful assistant.",
38+
tools: [fabricTool]);
39+
40+
PersistentAgentThread thread = agentClient.Threads.CreateThread();
41+
42+
// Create message and run the agent
43+
ThreadMessage message = agentClient.Messages.CreateMessage(
44+
thread.Id,
45+
MessageRole.User,
46+
"What are the top 3 weather events with highest property damage?");
47+
ThreadRun run = agentClient.Runs.CreateRun(thread, agent);
48+
49+
// Wait for the agent to finish running
50+
do
51+
{
52+
Thread.Sleep(TimeSpan.FromMilliseconds(500));
53+
run = agentClient.Runs.GetRun(thread.Id, run.Id);
54+
}
55+
while (run.Status == RunStatus.Queued
56+
|| run.Status == RunStatus.InProgress);
57+
58+
// Confirm that the run completed successfully
59+
if (run.Status != RunStatus.Completed)
60+
{
61+
throw new Exception("Run did not complete successfully, error: " + run.LastError?.Message);
62+
}
63+
64+
// Retrieve all messages from the agent client
65+
Pageable<ThreadMessage> messages = agentClient.Messages.GetMessages(
66+
threadId: thread.Id,
67+
order: ListSortOrder.Ascending
68+
);
69+
70+
// Process messages in order
71+
foreach (ThreadMessage threadMessage in messages)
72+
{
73+
Console.Write($"{threadMessage.CreatedAt:yyyy-MM-dd HH:mm:ss} - {threadMessage.Role,10}: ");
74+
foreach (MessageContent contentItem in threadMessage.ContentItems)
75+
{
76+
if (contentItem is MessageTextContent textItem)
77+
{
78+
string response = textItem.Text;
79+
80+
// If we have Text URL citation annotations, reformat the response to show title & URL for citations
81+
if (textItem.Annotations != null)
82+
{
83+
foreach (MessageTextAnnotation annotation in textItem.Annotations)
84+
{
85+
if (annotation is MessageTextUrlCitationAnnotation urlAnnotation)
86+
{
87+
response = response.Replace(urlAnnotation.Text, $" [{urlAnnotation.UrlCitation.Title}]({urlAnnotation.UrlCitation.Url})");
88+
}
89+
}
90+
}
91+
Console.Write($"Agent response: {response}");
92+
}
93+
else if (contentItem is MessageImageFileContent imageFileItem)
94+
{
95+
Console.Write($"<image from ID: {imageFileItem.FileId}");
96+
}
97+
Console.WriteLine();
98+
}
99+
}
100+
101+
// Delete thread and agent
102+
agentClient.Threads.DeleteThread(threadId: thread.Id);
103+
agentClient.Administration.DeleteAgent(agentId: agent.Id);

samples/microsoft/csharp/getting-started-agents/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ This table tracks the current status of code samples for each supported tool in
2121
| | Using blob storage (project data assets)| ⚠️ Exists| Sample not yet tested - but compiles properly and follows updated coding patterns |
2222
| | Managing files | ❌ Doesn't exist| |
2323
| **Azure AI Search**| Using a knowledge store | ⚠️ Exists | Sample not yet tested - but compiles properly and follows updated coding patterns |
24-
| **Fabric** | Grounding with Fabric data | ❌ Doesn't exist| |
24+
| **Fabric** | Grounding with Fabric data | ⚠️ Exists| Sample not yet tested - but compiles properly and follows updated coding patterns |
2525
| **SharePoint** | Grounding with SharePoint files | ❌ Doesn't exist in docs or repo| |
2626
| **TripAdvisor** | Using licensed TripAdvisor data | ❌ Doesn't exist in docs or repo| |
2727
| **Function Calling**| Calling local functions | ✅ Fully functional and validated| |

samples/microsoft/python/getting-started-agents/README.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,15 @@ This table tracks the current status of code samples for each supported tool in
1414
| | Managing files | ❌ Doesn't exist | |
1515
| **Azure AI Search**| Using a knowledge store | ✅ Exists and works | |
1616
| **Fabric** | Grounding with Fabric data | ✅ Exists and works | |
17-
| **SharePoint** | Grounding with SharePoint files | ⚠️ Exists and yet to work | |
18-
| **TripAdvisor** | Using licensed TripAdvisor data | ⚠️ Exists and doesn't work | |
19-
| **Function Calling**| Calling local functions | ❌ Doesn't exist | |
20-
| **Azure Functions**| Calling durable Azure Functions | ❌ Doesn't exist | |
21-
| **Logic Apps** | Calling Logic Apps workflows | ❌ Doesn't exist | |
17+
| **SharePoint** | Grounding with SharePoint files | Exists and works | |
18+
| **TripAdvisor** | Using licensed TripAdvisor data | Exists | |
19+
| **Function Calling**| Calling local functions | ✅ Exists and works | |
20+
| **Azure Functions**| Calling durable Azure Functions | ⚠️ Exists | To be tested |
21+
| **Logic Apps** | Calling Logic Apps workflows | ⚠️ Exists | To be tested |
2222
| **Code Interpreter**| Using Code Interpreter | ❌ Doesn't exist | |
2323
| **OpenAPI** | Calling external APIs with OpenAPI | ❌ Doesn't exist | |
24-
| **Basic Agent** | Using agent with no tools | ❌ Doesn't exist | |
25-
| **Quickstart** | Basic setup and usage example | ❌ Doesn't exist | |
24+
| **Basic Agent** | Using agent with no tools | ✅ Exists and works | |
25+
| **Quickstart** | Basic setup and usage example | ✅ Exists and works | |
2626

2727
---
2828

samples/microsoft/python/getting-started-agents/agent_sharepoint.py

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -25,19 +25,20 @@
2525
import os
2626
from azure.identity import DefaultAzureCredential
2727
from azure.ai.projects import AIProjectClient
28-
from azure.ai.projects import AIProjectClient
29-
from azure.ai.agents.models import SharepointTool
30-
from azure.identity import DefaultAzureCredential
28+
from azure.ai.agents.models import MessageRole, SharepointTool
3129

3230
# Retrieve endpoint and model deployment name from environment variables
33-
endpoint = os.environ["PROJECT_ENDPOINT"], # Ensure the PROJECT_ENDPOINT environment variable is set
31+
project_endpoint = os.environ["PROJECT_ENDPOINT"] # Ensure the PROJECT_ENDPOINT environment variable is set
3432
model_deployment_name = os.environ["MODEL_DEPLOYMENT_NAME"] # Ensure the MODEL_DEPLOYMENT_NAME environment variable is set
3533

3634
# Initialize the AIProjectClient with the endpoint and credentials
37-
with AIProjectClient(
38-
endpoint=endpoint,
35+
project_client = AIProjectClient(
36+
endpoint=project_endpoint,
3937
credential=DefaultAzureCredential(exclude_interactive_browser_credential=False), # Use Azure Default Credential for authentication
40-
) as project_client:
38+
api_version="latest",
39+
)
40+
41+
with project_client:
4142
# Initialize SharePoint tool with connection ID
4243
sharepoint_connection = project_client.connections.get(
4344
name="CONNECTION_NAME", # Replace with your actual connection name
@@ -46,11 +47,8 @@
4647
print(conn_id)
4748
sharepoint = SharepointTool(connection_id=conn_id) # Initialize the SharePoint tool with the connection ID
4849

49-
# Access the agents client from the project client
50-
agents_client = project_client.agents
51-
5250
# Create an agent with the specified model, name, instructions, and tools
53-
agent = agents_client.create_agent(
51+
agent = project_client.agents.create_agent(
5452
model=model_deployment_name, # Model deployment name
5553
name="my-agent", # Name of the agent
5654
instructions="You are a helpful agent", # Instructions for the agent
@@ -59,33 +57,31 @@
5957
print(f"Created agent, ID: {agent.id}")
6058

6159
# Create a thread for communication with the agent
62-
thread = agents_client.create_thread()
60+
thread = project_client.agents.threads.create()
6361
print(f"Created thread, ID: {thread.id}")
6462

6563
# Send a message to the thread
66-
message = agents_client.create_message(
64+
message = project_client.agents.messages.create(
6765
thread_id=thread.id, # ID of the thread
68-
role="user", # Role of the message sender (e.g., user)
66+
role=MessageRole.USER, # Role of the message sender (e.g., user)
6967
content="Hello, summarize the key points of the <sharepoint_resource_document>", # Message content
7068
)
71-
print(f"Created message, ID: {message.id}")
69+
print(f"Created message, ID: {message['id']}")
7270

7371
# Create and process an agent run in the thread using the tools
74-
run = agents_client.create_and_process_run(thread_id=thread.id, agent_id=agent.id)
72+
run = project_client.agents.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)
7573
print(f"Run finished with status: {run.status}")
7674

7775
if run.status == "failed":
7876
# Log the error if the run fails
7977
print(f"Run failed: {run.last_error}")
8078

8179
# Delete the agent when done to clean up resources
82-
agents_client.delete_agent(agent.id)
80+
project_client.agents.delete_agent(agent.id)
8381
print("Deleted agent")
8482

8583
# Fetch and log all messages from the thread
86-
messages = agents_client.list_message(thread_id=thread.id)
87-
for msg in messages:
88-
if msg.text_messages: # Check if there are text messages
89-
last_text = msg.text_messages[-1] # Get the last text message
90-
print(f"{msg.role}: {last_text.text.value}") # Print the role and message content
84+
messages = project_client.agents.messages.list(thread_id=thread.id)
85+
for message in messages:
86+
print(f"Role: {message['role']}, Content: {message['content']}")
9187

0 commit comments

Comments
 (0)