@@ -22,7 +22,6 @@ ms.date: 03/28/2025
22
22
| Thread | A conversation session between an agent and a user. Threads store Messages and automatically handle truncation to fit content into a model’s context. |
23
23
| Message | A message created by an agent or a user. Messages can include text, images, and other files. Messages are stored as a list on the Thread. |
24
24
| Run | Activation of an agent to begin running based on the contents of Thread. The agent uses its configuration and Thread’s Messages to perform tasks by calling models and tools. As part of a Run, the agent appends Messages to the Thread. |
25
- | Run Step | A detailed list of steps the agent took as part of a Run. An agent can call tools or create Messages during its run. Examining Run Steps allows you to understand how the agent is getting to its results. |
26
25
27
26
Create a .NET Console project.
28
27
@@ -33,10 +32,10 @@ dotnet new console
33
32
Install the .NET package to your project. For example if you're using the .NET CLI, run the following command.
34
33
35
34
> [ !Note]
36
- > Azure.AI.Projects is only available as a prelease version. Please use the "-prerelease" flag to add the package until a release version becomes available.
35
+ > Azure.AI.Agents.Persistent is only available as a prelease version. Please use the "-prerelease" flag to add the package until a release version becomes available.
37
36
38
37
``` console
39
- dotnet add package Azure.AI.Projects --prerelease
38
+ dotnet add package Azure.AI.Agents.Persistent --prerelease
40
39
dotnet add package Azure.Identity
41
40
```
42
41
@@ -56,92 +55,94 @@ For example, your connection string may look something like:
56
55
57
56
` https://myresource.services.ai.azure.com/api/projects/myproject `
58
57
59
- Set this connection string as an environment variable named ` PROJECT_ENDPOINT ` .
58
+ Set this connection string in an appsetting variable named ` ProjectEndpoint ` .
60
59
61
60
62
61
``` csharp
63
- // Copyright (c) Microsoft Corporation. All rights reserved.
64
- // Licensed under the MIT License.
65
-
66
- #nullable disable
67
-
62
+ using Azure ;
63
+ using Azure .AI .Agents .Persistent ;
68
64
using Azure .Identity ;
65
+ using Microsoft .Extensions .Configuration ;
66
+ using System .Diagnostics ;
67
+
68
+ IConfigurationRoot configuration = new ConfigurationBuilder ()
69
+ .SetBasePath (AppContext .BaseDirectory )
70
+ .AddJsonFile (" appsettings.json" , optional : false , reloadOnChange : true )
71
+ .Build ();
72
+
73
+ var projectEndpoint = configuration [" ProjectEndpoint" ];
74
+ var modelDeploymentName = configuration [" ModelDeploymentName" ];
75
+
76
+ // Create a PersistentAgentsClient and PersistentAgent.
77
+ PersistentAgentsClient client = new (projectEndpoint , new DefaultAzureCredential ());
78
+
79
+ // Give PersistentAgent a tool to execute code using CodeInterpreterToolDefinition.
80
+ PersistentAgent agent = client .Administration .CreateAgent (
81
+ model : modelDeploymentName ,
82
+ name : " My Test Agent" ,
83
+ instructions : " You politely help with math questions. Use the code interpreter tool when asked to visualize numbers." ,
84
+ tools : [new CodeInterpreterToolDefinition ()]
85
+ );
86
+
87
+ // Create a thread to establish a session between Agent and a User.
88
+ PersistentAgentThread thread = client .Threads .CreateThread ();
89
+
90
+ // Ask a question of the Agent.
91
+ client .Messages .CreateMessage (
92
+ thread .Id ,
93
+ MessageRole .User ,
94
+ " Hi, Agent! Draw a graph for a line with a slope of 4 and y-intercept of 9." );
95
+
96
+ // Have Agent beging processing user's question with some additional instructions associated with the ThreadRun.
97
+ ThreadRun run = client .Runs .CreateRun (
98
+ thread .Id ,
99
+ agent .Id ,
100
+ additionalInstructions : " Please address the user as Jane Doe. The user has a premium account." );
101
+
102
+ // Poll for completion.
103
+ do
104
+ {
105
+ Thread .Sleep (TimeSpan .FromMilliseconds (500 ));
106
+ run = client .Runs .GetRun (thread .Id , run .Id );
107
+ }
108
+ while (run .Status == RunStatus .Queued
109
+ || run .Status == RunStatus .InProgress
110
+ || run .Status == RunStatus .RequiresAction );
69
111
70
- namespace Azure .AI .Projects .Tests ;
112
+ // Get the messages in the PersistentAgentThread. Includes Agent (Assistant Role) and User (User Role) messages.
113
+ Pageable < ThreadMessage > messages = client .Messages .GetMessages (
114
+ threadId : thread .Id ,
115
+ order : ListSortOrder .Ascending );
71
116
72
- public class Sample_Agent
117
+ // Display each message and open the image generated using CodeInterpreterToolDefinition.
118
+ foreach (ThreadMessage threadMessage in messages )
73
119
{
74
- static async Task Main ( )
120
+ foreach ( MessageContent content in threadMessage . ContentItems )
75
121
{
76
- var connectionString = Environment .GetEnvironmentVariable (" PROJECT_ENDPOINT" );
77
-
78
- AgentsClient client = new AgentsClient (connectionString , new DefaultAzureCredential ());
79
-
80
- // Step 1: Create an agent
81
- Response < Agent > agentResponse = await client .CreateAgentAsync (
82
- model : " gpt-4o-mini" ,
83
- name : " My Agent" ,
84
- instructions : " You are a helpful agent." ,
85
- tools : new List <ToolDefinition > { new CodeInterpreterToolDefinition () });
86
- Agent agent = agentResponse .Value ;
87
-
88
- // Intermission: agent should now be listed
89
-
90
- Response < PageableList < Agent >> agentListResponse = await client .GetAgentsAsync ();
91
-
92
- // // Step 2: Create a thread
93
- Response < AgentThread > threadResponse = await client .CreateThreadAsync ();
94
- AgentThread thread = threadResponse .Value ;
95
-
96
- // Step 3: Add a message to a thread
97
- Response < ThreadMessage > messageResponse = await client .CreateMessageAsync (
98
- thread .Id ,
99
- MessageRole .User ,
100
- " I need to solve the equation `3x + 11 = 14`. Can you help me?" );
101
- ThreadMessage message = messageResponse .Value ;
102
-
103
- // Intermission: message is now correlated with thread
104
- // Intermission: listing messages will retrieve the message just added
105
-
106
- Response < PageableList < ThreadMessage >> messagesListResponse = await client .GetMessagesAsync (thread .Id );
107
- // Assert.That(messagesListResponse.Value.Data[0].Id == message.Id);
108
-
109
- // Step 4: Run the agent
110
- Response < ThreadRun > runResponse = await client .CreateRunAsync (
111
- thread .Id ,
112
- agent .Id ,
113
- additionalInstructions : " " );
114
- ThreadRun run = runResponse .Value ;
115
-
116
- do
117
- {
118
- await Task .Delay (TimeSpan .FromMilliseconds (500 ));
119
- runResponse = await client .GetRunAsync (thread .Id , runResponse .Value .Id );
120
- }
121
- while (runResponse .Value .Status == RunStatus .Queued
122
- || runResponse .Value .Status == RunStatus .InProgress );
123
-
124
- Response < PageableList < ThreadMessage >> afterRunMessagesResponse
125
- = await client .GetMessagesAsync (thread .Id );
126
- IReadOnlyList < ThreadMessage > messages = afterRunMessagesResponse .Value .Data ;
127
-
128
- // Note: messages iterate from newest to oldest, with the messages[0] being the most recent
129
- foreach (ThreadMessage threadMessage in messages )
122
+ switch (content )
130
123
{
131
- Console .Write ($" {threadMessage .CreatedAt : yyyy - MM - dd HH : mm : ss } - {threadMessage .Role ,10 }: " );
132
- foreach (MessageContent contentItem in threadMessage .ContentItems )
133
- {
134
- if (contentItem is MessageTextContent textItem )
124
+ case MessageTextContent textItem :
125
+ Console .WriteLine ($" [{threadMessage .Role }]: {textItem .Text }" );
126
+ break ;
127
+ case MessageImageFileContent imageFileContent :
128
+ Console .WriteLine ($" [{threadMessage .Role }]: Image content file ID = {imageFileContent .FileId }" );
129
+ BinaryData imageContent = client .Files .GetFileContent (imageFileContent .FileId );
130
+ string tempFilePath = Path .Combine (AppContext .BaseDirectory , $" {Guid .NewGuid ()}.png" );
131
+ File .WriteAllBytes (tempFilePath , imageContent .ToArray ());
132
+ client .Files .DeleteFile (imageFileContent .FileId );
133
+
134
+ ProcessStartInfo psi = new ()
135
135
{
136
- Console .Write (textItem .Text );
137
- }
138
- else if (contentItem is MessageImageFileContent imageFileItem )
139
- {
140
- Console .Write ($" <image from ID: {imageFileItem .FileId }" );
141
- }
142
- Console .WriteLine ();
143
- }
136
+ FileName = tempFilePath ,
137
+ UseShellExecute = true
138
+ };
139
+ Process .Start (psi );
140
+ break ;
144
141
}
145
142
}
146
143
}
144
+
145
+ // Clean up test resources.
146
+ client .Threads .DeleteThread (threadId : thread .Id );
147
+ client .Administration .DeleteAgent (agentId : agent .Id );
147
148
```
0 commit comments