Skip to content

Commit 9d0cdc4

Browse files
committed
fixing files
1 parent d881754 commit 9d0cdc4

File tree

2 files changed

+119
-765
lines changed

2 files changed

+119
-765
lines changed

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

Lines changed: 58 additions & 254 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
165+
var projectEndpoint = configuration["ProjectEndpoint"];
166+
var modelDeploymentName = configuration["ModelDeploymentName"];
167167

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
168+
PersistentAgentsClient client = new(projectEndpoint, new DefaultAzureCredential());
171169

172-
BingGroundingToolDefinition bingGroundingTool = new(
173-
new BingGroundingSearchToolParameters(
174-
[new BingGroundingSearchConfiguration(bingConnectionId)]
175-
)
176-
);
177-
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}");
257-
}
258-
Console.WriteLine();
259-
}
260-
}
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-
}
238+
FileName = tempFilePath,
239+
UseShellExecute = true
240+
};
241+
Process.Start(psi);
242+
break;
290243
}
291244
}
292245
}
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
@@ -564,151 +515,4 @@ curl --request GET \
564515
-H "Authorization: Bearer $AGENT_TOKEN"
565516
```
566517

567-
:::zone-end
568-
569-
570-
:::zone pivot="java"
571-
572-
## Download an example file
573-
574-
Files can be uploaded and then referenced by agents or messages. Once it's uploaded it can be added to the tool utility for referencing. You can find a downloadable example file on [GitHub](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/ai/ai-agents/data/syntheticCompanyQuarterlyResults.csv).
575-
576-
## Code example
577-
578-
```java
579-
package com.example.agents;
580-
581-
import com.azure.ai.agents.persistent.FilesClient;
582-
import com.azure.ai.agents.persistent.MessagesClient;
583-
import com.azure.ai.agents.persistent.PersistentAgentsAdministrationClient;
584-
import com.azure.ai.agents.persistent.PersistentAgentsClient;
585-
import com.azure.ai.agents.persistent.PersistentAgentsClientBuilder;
586-
import com.azure.ai.agents.persistent.RunsClient;
587-
import com.azure.ai.agents.persistent.ThreadsClient;
588-
import com.azure.ai.agents.persistent.models.CodeInterpreterToolDefinition;
589-
import com.azure.ai.agents.persistent.models.CreateAgentOptions;
590-
import com.azure.ai.agents.persistent.models.CreateRunOptions;
591-
import com.azure.ai.agents.persistent.models.FileDetails;
592-
import com.azure.ai.agents.persistent.models.FileInfo;
593-
import com.azure.ai.agents.persistent.models.FilePurpose;
594-
import com.azure.ai.agents.persistent.models.MessageAttachment;
595-
import com.azure.ai.agents.persistent.models.MessageImageFileContent;
596-
import com.azure.ai.agents.persistent.models.MessageRole;
597-
import com.azure.ai.agents.persistent.models.MessageTextContent;
598-
import com.azure.ai.agents.persistent.models.PersistentAgent;
599-
import com.azure.ai.agents.persistent.models.PersistentAgentThread;
600-
import com.azure.ai.agents.persistent.models.RunStatus;
601-
import com.azure.ai.agents.persistent.models.ThreadMessage;
602-
import com.azure.ai.agents.persistent.models.ThreadRun;
603-
import com.azure.ai.agents.persistent.models.UploadFileRequest;
604-
import com.azure.ai.agents.persistent.models.MessageContent;
605-
import com.azure.core.http.rest.PagedIterable;
606-
import com.azure.core.util.BinaryData;
607-
import com.azure.identity.DefaultAzureCredentialBuilder;
608-
609-
import java.net.URL;
610-
import java.io.File;
611-
import java.io.FileNotFoundException;
612-
import java.net.URISyntaxException;
613-
import java.nio.file.Path;
614-
import java.util.Arrays;
615-
616-
public class AgentExample {
617-
618-
public static void main(String[] args) throws FileNotFoundException, URISyntaxException {
619-
620-
// variables for authenticating requests to the agent service
621-
String projectEndpoint = System.getenv("PROJECT_ENDPOINT");
622-
String modelName = System.getenv("MODEL_DEPLOYMENT_NAME");
623-
624-
PersistentAgentsClientBuilder clientBuilder = new PersistentAgentsClientBuilder().endpoint(projectEndpoint)
625-
.credential(new DefaultAzureCredentialBuilder().build());
626-
PersistentAgentsClient agentsClient = clientBuilder.buildClient();
627-
PersistentAgentsAdministrationClient administrationClient = agentsClient.getPersistentAgentsAdministrationClient();
628-
ThreadsClient threadsClient = agentsClient.getThreadsClient();
629-
MessagesClient messagesClient = agentsClient.getMessagesClient();
630-
RunsClient runsClient = agentsClient.getRunsClient();
631-
FilesClient filesClient = agentsClient.getFilesClient();
632-
633-
Path myFile = getFile("syntheticCompanyQuarterlyResults.csv");
634-
635-
String agentName = "code_interpreter_file_attachment_example";
636-
CodeInterpreterToolDefinition ciTool = new CodeInterpreterToolDefinition();
637-
CreateAgentOptions createAgentOptions = new CreateAgentOptions(modelName).setName(agentName).setInstructions("You are a helpful agent").setTools(Arrays.asList(ciTool));
638-
PersistentAgent agent = administrationClient.createAgent(createAgentOptions);
639-
640-
FileInfo uploadedFile = filesClient.uploadFile(new UploadFileRequest(
641-
new FileDetails(BinaryData.fromFile(myFile))
642-
.setFilename("sample.csv"), FilePurpose.AGENTS));
643-
644-
MessageAttachment messageAttachment = new MessageAttachment(Arrays.asList(BinaryData.fromObject(ciTool))).setFileId(uploadedFile.getId());
645-
646-
PersistentAgentThread thread = threadsClient.createThread();
647-
ThreadMessage createdMessage = messagesClient.createMessage(
648-
thread.getId(),
649-
MessageRole.USER,
650-
"Could you analyze the uploaded CSV file for me?",
651-
Arrays.asList(messageAttachment),
652-
null);
653-
654-
try {
655-
//run agent
656-
CreateRunOptions createRunOptions = new CreateRunOptions(thread.getId(), agent.getId()).setAdditionalInstructions("");
657-
ThreadRun threadRun = runsClient.createRun(createRunOptions);
658-
659-
waitForRunCompletion(thread.getId(), threadRun, runsClient);
660-
printRunMessages(messagesClient, thread.getId());
661-
} catch (InterruptedException e) {
662-
throw new RuntimeException(e);
663-
} finally {
664-
//cleanup
665-
threadsClient.deleteThread(thread.getId());
666-
administrationClient.deleteAgent(agent.getId());
667-
}
668-
}
669-
// A helper function to print messages from the agent
670-
public static void printRunMessages(MessagesClient messagesClient, String threadId) {
671-
672-
PagedIterable<ThreadMessage> runMessages = messagesClient.listMessages(threadId);
673-
for (ThreadMessage message : runMessages) {
674-
System.out.print(String.format("%1$s - %2$s : ", message.getCreatedAt(), message.getRole()));
675-
for (MessageContent contentItem : message.getContent()) {
676-
if (contentItem instanceof MessageTextContent) {
677-
System.out.print((((MessageTextContent) contentItem).getText().getValue()));
678-
} else if (contentItem instanceof MessageImageFileContent) {
679-
String imageFileId = (((MessageImageFileContent) contentItem).getImageFile().getFileId());
680-
System.out.print("Image from ID: " + imageFileId);
681-
}
682-
System.out.println();
683-
}
684-
}
685-
}
686-
687-
// a helper function to wait until a run has completed running
688-
public static void waitForRunCompletion(String threadId, ThreadRun threadRun, RunsClient runsClient)
689-
throws InterruptedException {
690-
691-
do {
692-
Thread.sleep(500);
693-
threadRun = runsClient.getRun(threadId, threadRun.getId());
694-
}
695-
while (
696-
threadRun.getStatus() == RunStatus.QUEUED
697-
|| threadRun.getStatus() == RunStatus.IN_PROGRESS
698-
|| threadRun.getStatus() == RunStatus.REQUIRES_ACTION);
699-
700-
if (threadRun.getStatus() == RunStatus.FAILED) {
701-
System.out.println(threadRun.getLastError().getMessage());
702-
}
703-
}
704-
private static Path getFile(String fileName) throws FileNotFoundException, URISyntaxException {
705-
URL resource = AgentExample.class.getClassLoader().getResource(fileName);
706-
if (resource == null) {
707-
throw new FileNotFoundException("File not found");
708-
}
709-
File file = new File(resource.toURI());
710-
return file.toPath();
711-
}
712-
}
713-
```
714518
:::zone-end

0 commit comments

Comments
 (0)