Skip to content

Commit e442c3d

Browse files
Merge pull request #6515 from aahill/agents-java-2
revert code interpreter
2 parents 24bceca + 0ae34f7 commit e442c3d

File tree

1 file changed

+58
-108
lines changed

1 file changed

+58
-108
lines changed

articles/ai-foundry/agents/how-to/tools/code-interpreter-samples.md

Lines changed: 58 additions & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ description: Find code samples to enable code interpreter for Azure AI Agents.
55
author: aahill
66
ms.author: aahi
77
manager: nitinme
8-
ms.date: 06/30/2025
8+
ms.date: 08/11/2025
99
ms.service: azure-ai-agent-service
1010
ms.topic: how-to
1111
ms.custom:
@@ -146,161 +146,112 @@ This ensures proper resource management and prevents unnecessary resource consum
146146

147147
:::zone pivot="csharp"
148148

149-
## Create a project client
149+
## Create a client and agent
150150

151-
Create a client object, which will contain the project endpoint for connecting to your AI project and other resources.
151+
First, set up the configuration using `appsettings.json`, create a `PersistentAgentsClient`, and then create a `PersistentAgent` with the Code Interpreter tool enabled.
152152

153153
```csharp
154154
using Azure;
155155
using Azure.AI.Agents.Persistent;
156156
using Azure.Identity;
157+
using Microsoft.Extensions.Configuration;
158+
using System.Diagnostics;
157159

158-
var projectEndpoint = System.Environment.GetEnvironmentVariable("ProjectEndpoint");
159-
var projectEndpoint = System.Environment.GetEnvironmentVariable("ModelDeploymentName");
160-
var projectEndpoint = System.Environment.GetEnvironmentVariable("BingConnectionId");
160+
IConfigurationRoot configuration = new ConfigurationBuilder()
161+
.SetBasePath(AppContext.BaseDirectory)
162+
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
163+
.Build();
161164

162-
// Create the Agent Client
163-
PersistentAgentsClient agentClient = new(projectEndpoint, new DefaultAzureCredential());
164-
```
165-
166-
## Create an Agent with the Grounding with Bing search tool enabled
167-
168-
To make the Grounding with Bing search tool available to your agent, use a connection to initialize the tool and attach it to the agent. You can find your connection in the **connected resources** section of your project in the [Azure AI Foundry portal](https://ai.azure.com/?cid=learnDocs).
169-
170-
```csharp
165+
var projectEndpoint = configuration["ProjectEndpoint"];
166+
var modelDeploymentName = configuration["ModelDeploymentName"];
171167

172-
BingGroundingToolDefinition bingGroundingTool = new(
173-
new BingGroundingSearchToolParameters(
174-
[new BingGroundingSearchConfiguration(bingConnectionId)]
175-
)
176-
);
168+
PersistentAgentsClient client = new(projectEndpoint, new DefaultAzureCredential());
177169

178-
// Create the Agent
179-
PersistentAgent agent = agentClient.Administration.CreateAgent(
170+
PersistentAgent agent = client.Administration.CreateAgent(
180171
model: modelDeploymentName,
181-
name: "my-agent",
182-
instructions: "Use the bing grounding tool to answer questions.",
183-
tools: [bingGroundingTool]
172+
name: "My Friendly Test Agent",
173+
instructions: "You politely help with math questions. Use the code interpreter tool when asked to visualize numbers.",
174+
tools: [new CodeInterpreterToolDefinition()]
184175
);
185176
```
186177

187-
## Create a thread and run
178+
## Create a thread and add a message
179+
180+
Next, create a `PersistentAgentThread` for the conversation and add the initial user message.
188181

189182
```csharp
190-
PersistentAgentThread thread = agentClient.Threads.CreateThread();
183+
PersistentAgentThread thread = client.Threads.CreateThread();
191184

192-
// Create message and run the agent
193-
PersistentThreadMessage message = agentClient.Messages.CreateMessage(
185+
client.Messages.CreateMessage(
194186
thread.Id,
195187
MessageRole.User,
196-
"How does wikipedia explain Euler's Identity?");
197-
ThreadRun run = agentClient.Runs.CreateRun(thread, agent);
198-
188+
"Hi, Agent! Draw a graph for a line with a slope of 4 and y-intercept of 9.");
199189
```
200190

201-
## Wait for the agent to complete and print the output
191+
## Create and monitor a run
202192

203-
First, wait for the agent to complete the run by polling its status. Observe that the model uses the Grounding with Bing Search tool to provide a response to the user's question.
193+
Then, create a `ThreadRun` for the thread and agent. Poll the run's status until it completes or requires action.
204194

205195
```csharp
206-
// Wait for the agent to finish running
196+
ThreadRun run = client.Runs.CreateRun(
197+
thread.Id,
198+
agent.Id,
199+
additionalInstructions: "Please address the user as Jane Doe. The user has a premium account.");
200+
207201
do
208202
{
209203
Thread.Sleep(TimeSpan.FromMilliseconds(500));
210-
run = agentClient.Runs.GetRun(thread.Id, run.Id);
204+
run = client.Runs.GetRun(thread.Id, run.Id);
211205
}
212206
while (run.Status == RunStatus.Queued
213-
|| run.Status == RunStatus.InProgress);
214-
215-
// Confirm that the run completed successfully
216-
if (run.Status != RunStatus.Completed)
217-
{
218-
throw new Exception("Run did not complete successfully, error: " + run.LastError?.Message);
219-
}
207+
|| run.Status == RunStatus.InProgress
208+
|| run.Status == RunStatus.RequiresAction);
220209
```
221210

222-
Then, retrieve and process the messages from the completed run.
211+
## Process the results and handle files
212+
213+
Once the run is finished, retrieve all messages from the thread. Iterate through the messages to display text content and handle any generated image files by saving them locally and opening them.
223214

224215
```csharp
225-
// Retrieve all messages from the agent client
226-
Pageable<PersistentThreadMessage> messages = agentClient.Messages.GetMessages(
216+
Pageable<PersistentThreadMessage> messages = client.Messages.GetMessages(
227217
threadId: thread.Id,
228-
order: ListSortOrder.Ascending
229-
);
218+
order: ListSortOrder.Ascending);
230219

231-
// Process messages in order
232220
foreach (PersistentThreadMessage threadMessage in messages)
233221
{
234-
Console.Write($"{threadMessage.CreatedAt:yyyy-MM-dd HH:mm:ss} - {threadMessage.Role,10}: ");
235-
foreach (MessageContent contentItem in threadMessage.ContentItems)
222+
foreach (MessageContent content in threadMessage.ContentItems)
236223
{
237-
if (contentItem is MessageTextContent textItem)
224+
switch (content)
238225
{
239-
string response = textItem.Text;
240-
241-
// If we have Text URL citation annotations, reformat the response to show title & URL for citations
242-
if (textItem.Annotations != null)
243-
{
244-
foreach (MessageTextAnnotation annotation in textItem.Annotations)
226+
case MessageTextContent textItem:
227+
Console.WriteLine($"[{threadMessage.Role}]: {textItem.Text}");
228+
break;
229+
case MessageImageFileContent imageFileContent:
230+
Console.WriteLine($"[{threadMessage.Role}]: Image content file ID = {imageFileContent.FileId}");
231+
BinaryData imageContent = client.Files.GetFileContent(imageFileContent.FileId);
232+
string tempFilePath = Path.Combine(AppContext.BaseDirectory, $"{Guid.NewGuid()}.png");
233+
File.WriteAllBytes(tempFilePath, imageContent.ToArray());
234+
client.Files.DeleteFile(imageFileContent.FileId);
235+
236+
ProcessStartInfo psi = new()
245237
{
246-
if (annotation is MessageTextUriCitationAnnotation urlAnnotation)
247-
{
248-
response = response.Replace(urlAnnotation.Text, $" [{urlAnnotation.UriCitation.Title}]({urlAnnotation.UriCitation.Uri})");
249-
}
250-
}
251-
}
252-
Console.Write($"Agent response: {response}");
253-
}
254-
else if (contentItem is MessageImageFileContent imageFileItem)
255-
{
256-
Console.Write($"<image from ID: {imageFileItem.FileId}");
238+
FileName = tempFilePath,
239+
UseShellExecute = true
240+
};
241+
Process.Start(psi);
242+
break;
257243
}
258-
Console.WriteLine();
259244
}
260245
}
261-
262-
```
263-
264-
## Optionally output the run steps used by the agent
265-
266-
```csharp
267-
// Retrieve the run steps used by the agent and print those to the console
268-
Console.WriteLine("Run Steps used by Agent:");
269-
Pageable<RunStep> runSteps = agentClient.Runs.GetRunSteps(run);
270-
271-
foreach (var step in runSteps)
272-
{
273-
Console.WriteLine($"Step ID: {step.Id}, Total Tokens: {step.Usage.TotalTokens}, Status: {step.Status}, Type: {step.Type}");
274-
275-
if (step.StepDetails is RunStepMessageCreationDetails messageCreationDetails)
276-
{
277-
Console.WriteLine($" Message Creation Id: {messageCreationDetails.MessageCreation.MessageId}");
278-
}
279-
else if (step.StepDetails is RunStepToolCallDetails toolCallDetails)
280-
{
281-
// We know this agent only has the Bing Grounding tool, so we can cast it directly
282-
foreach (RunStepBingGroundingToolCall toolCall in toolCallDetails.ToolCalls)
283-
{
284-
Console.WriteLine($" Tool Call Details: {toolCall.GetType()}");
285-
286-
foreach (var result in toolCall.BingGrounding)
287-
{
288-
Console.WriteLine($" {result.Key}: {result.Value}");
289-
}
290-
}
291-
}
292-
}
293-
294246
```
295247

296248
## Clean up resources
297249

298-
Clean up the resources from this sample.
250+
Finally, delete the thread and the agent to clean up the resources created in this sample.
299251

300252
```csharp
301-
// Delete thread and agent
302-
agentClient.Threads.DeleteThread(threadId: thread.Id);
303-
agentClient.Administration.DeleteAgent(agentId: agent.Id);
253+
client.Threads.DeleteThread(threadId: thread.Id);
254+
client.Administration.DeleteAgent(agentId: agent.Id);
304255
```
305256

306257
:::zone-end
@@ -566,7 +517,6 @@ curl --request GET \
566517

567518
:::zone-end
568519

569-
570520
:::zone pivot="java"
571521

572522
## Download an example file

0 commit comments

Comments
 (0)