Skip to content

Run status is failed, how do i get the reason on why the run failed #173

@madhugilla

Description

@madhugilla

Developing a simple agent to generate a text from an image, the status of the run is failed, but i cant figure out the reason why it failed, i am using the following sample https://github.com/azure-ai-foundry/foundry-samples/blob/main/samples/microsoft/csharp/getting-started-agents/ImageFileInputs/ImageFileInputs.md

here is my code.

`

[Function("Prompt")]
public static async Task<IActionResult> Prompt([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req, FunctionContext executionContext)
{
    var logger = executionContext.GetLogger("Prompt");
    logger.LogInformation("C# HTTP trigger function processed a request.");

    try
    {
        var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_CONNECTION_STRING");

        // Load the file path from the configuration

        var filePath = "./parking.jpg"; // Replace with the actual file path

        // Get the prompt from the request body
        var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        var data = JsonSerializer.Deserialize<Dictionary<string, string>>(requestBody);
        if (data == null || !data.TryGetValue("Prompt", out var prompt))
        {
            return new BadRequestObjectResult("The 'Prompt' field is missing in the request body.");
        }

        PersistentAgentsClient client = new(projectEndpoint, new DefaultAzureCredential());

        PersistentAgentFileInfo uploadedFile = await client.Files.UploadFileAsync(
            filePath: filePath,
            purpose: PersistentAgentFilePurpose.Agents
        );

        PersistentAgent agent = await client.Administration.CreateAgentAsync(
            model: "03-mini",
            name: "File Image Understanding Agent",
            instructions: "extract the text from the image into a valid json, use a flat hierarchy."
        );

        PersistentAgentThread thread = await client.Threads.CreateThreadAsync();

        var contentBlocks = new List<MessageInputContentBlock>

{
new MessageInputTextBlock("Here is an uploaded file, extract the text from the image into a valid json, use a flat hierarchy."),
new MessageInputImageFileBlock(new MessageImageFileParam(uploadedFile.Id))
};

        await client.Messages.CreateMessageAsync(
            thread.Id,
            MessageRole.User,
            contentBlocks: contentBlocks);

        ThreadRun run = await client.Runs.CreateRunAsync(
            threadId: thread.Id,
            assistantId: agent.Id
        );

StringBuilder outPut = new StringBuilder();
do
{
await Task.Delay(TimeSpan.FromMilliseconds(500));
run = await client.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued
|| run.Status == RunStatus.InProgress
|| run.Status == RunStatus.RequiresAction);
outPut.AppendLine($"Run status: {run.Status} - {run.FailedAt}");

        AsyncPageable<PersistentThreadMessage> messages = client.Messages.GetMessagesAsync(
            threadId: thread.Id,
            order: ListSortOrder.Descending);
     
        await foreach (PersistentThreadMessage threadMessage in messages)
        {
            foreach (MessageContent content in threadMessage.ContentItems)
            {
                switch (content)
                {
                    case MessageTextContent textItem:
                        Console.WriteLine($"[{threadMessage.Role}]: {textItem.Text}");
                        outPut.AppendLine($"[{threadMessage.Role}]: {textItem.Text}");
                        break;

                    case MessageImageFileContent fileItem:
                        Console.WriteLine($"[{threadMessage.Role}]: Image File (internal ID): {fileItem.FileId}");
                        outPut.AppendLine($"[{threadMessage.Role}]: Image File (internal ID): {fileItem.FileId}");
                        break;
                }
            }
        }

        await client.Files.DeleteFileAsync(uploadedFile.Id);
        await client.Threads.DeleteThreadAsync(threadId: thread.Id);
        await client.Administration.DeleteAgentAsync(agentId: agent.Id);

        return new OkObjectResult(outPut.ToString());
    }
    catch (Exception ex)
    {
        logger.LogError($"Error processing prompt: {ex.Message}");
        var errorResponse = req.CreateResponse(System.Net.HttpStatusCode.InternalServerError);
        return new BadRequestObjectResult(errorResponse);
    }
}

`

Metadata

Metadata

Assignees

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