Skip to content

Quickstart code fails with "Sorry, something went wrong." #299

@boclifton-MSFT

Description

@boclifton-MSFT

Hi team, I'm getting started with agents in Foundry and have created the code found in Basics.md, which is very similar to the code found here; I've tried both approaches. I created it and ran it, but the run fails with "Sorry, something went wrong" as the run.LastError.Message. I tried adding more extensive error handling, but it appears this is the only error message I can get. Threads and Agents appear as expected in Foundry, and the Threads have only the initial user message with no response from the Agent. Full code is below. I have confirmed that RBAC roles are as they are supposed to be...I have both AI User and Owner roles for this Foundry project.

(hardcoded endpoint and model names since this is just a personal tinkering project at this point)

using Azure;
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using System.Diagnostics;

var projectEndpoint = System.Environment.GetEnvironmentVariable("ProjectEndpoint")
    ?? "https://<MY_ENDPOINT>.services.ai.azure.com/api/projects/<MY_PROJECT>";
var modelDeploymentName = System.Environment.GetEnvironmentVariable("ModelDeploymentName")
    ?? "gpt-4o";

//Create a PersistentAgentsClient and PersistentAgent.
PersistentAgentsClient client = new(projectEndpoint, new DefaultAzureCredential());

//Give PersistentAgent a tool to execute code using CodeInterpreterToolDefinition.
// PersistentAgent agent = client.Administration.CreateAgent(
//     model: modelDeploymentName,
//     name: "My Test Agent",
//     instructions: "You politely help with math questions. Use the code interpreter tool when asked to visualize numbers.",
//     tools: [new CodeInterpreterToolDefinition()]
// );

PersistentAgent agent = client.Administration.GetAgent("asst_<MY_AGENT_ID>");

//Create a thread to establish a session between Agent and a User.
PersistentAgentThread thread = client.Threads.CreateThread();

//Ask a question of the Agent.
client.Messages.CreateMessage(
    thread.Id,
    MessageRole.User,
    "Hi, Agent! Draw a graph for a line with a slope of 4 and y-intercept of 9.");

//Have Agent begin processing user's question with some additional instructions associated with the ThreadRun.
ThreadRun run = client.Runs.CreateRun(
    thread.Id,
    agent.Id,
    additionalInstructions: "Please address the user as Jane Doe. The user has a premium account.");

//Poll for completion.
do
{
    Thread.Sleep(TimeSpan.FromMilliseconds(500));
    run = client.Runs.GetRun(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued
    || run.Status == RunStatus.InProgress
    || run.Status == RunStatus.RequiresAction);

// Check for errors after polling completes
if (run.Status != RunStatus.Completed)
{
    Console.WriteLine($"Run failed with status: {run.Status}");
    Console.WriteLine($"Failed at: {run.FailedAt}");
    Console.WriteLine($"Error message: {run.LastError?.Message}");  // Key addition!
    Console.WriteLine($"Error code: {run.LastError?.Code}");
    
    throw new Exception($"Run did not complete successfully. Status: {run.Status}, " +
                       $"Failed at: {run.FailedAt}, Error: {run.LastError?.Message}");
}

//Get the messages in the PersistentAgentThread. Includes Agent (Assistant Role) and User (User Role) messages.
Pageable<PersistentThreadMessage> messages = client.Messages.GetMessages(
    threadId: thread.Id,
    order: ListSortOrder.Ascending);

//Display each message and open the image generated using CodeInterpreterToolDefinition.
foreach (PersistentThreadMessage threadMessage in messages)
{
    foreach (MessageContent content in threadMessage.ContentItems)
    {
        switch (content)
        {
            case MessageTextContent textItem:
                Console.WriteLine($"[{threadMessage.Role}]: {textItem.Text}");
                break;
            case MessageImageFileContent imageFileContent:
                Console.WriteLine($"[{threadMessage.Role}]: Image content file ID = {imageFileContent.FileId}");
                BinaryData imageContent = client.Files.GetFileContent(imageFileContent.FileId);
                string tempFilePath = Path.Combine(AppContext.BaseDirectory, $"{Guid.NewGuid()}.png");
                File.WriteAllBytes(tempFilePath, imageContent.ToArray());
                client.Files.DeleteFile(imageFileContent.FileId);

                ProcessStartInfo psi = new()
                {
                    FileName = tempFilePath,
                    UseShellExecute = true
                };
                Process.Start(psi);
                break;
        }
    }
}

//If you want to delete your agent, uncomment the following lines:
//client.Threads.DeleteThread(threadId: thread.Id);
//client.Administration.DeleteAgent(agentId: agent.Id);

Fails with this error after dotnet run:

Run failed with status: failed
Failed at: 9/5/2025 8:03:35 PM +00:00
Error message: Sorry, something went wrong.
Error code: server_error
Unhandled exception. System.Exception: Run did not complete successfully. Status: failed, Failed at: 9/5/2025 8:03:35 PM +00:00, Error: Sorry, something went wrong.
   at Program.<Main>$(String[] args) in C:\Users\<PATH>\Program.cs:line 57

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions