AllTools

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
using var api = GetAuthenticatedClient();

OpenAIFile favoriteNumberFile = await api.Files.CreateFileAsync(
    file: """
          This file contains the favorite numbers for individuals.

          John Doe: 14
          Bob Doe: 32
          Jane Doe: 44
          """u8.ToArray(),
    filename: "favorite_numbers.txt",
    purpose: CreateFileRequestPurpose.Assistants);

var service = new AllToolsService();
IList<ChatCompletionTool> tools = service.AsTools().AsOpenAiTools();

AssistantObject assistant = await api.Assistants.CreateAssistantAsync(
    model: CreateAssistantRequestModel.Gpt4o,
    instructions: "Use functions to resolve family relations into the names of people. Use file search to "
                  + " look up the favorite numbers of people. Use code interpreter to create graphs of lines.",
    tools: tools
        .Select(x => new ToolsItem2(new AssistantToolsFunction
        {
            Function = x.Function,
        }))
        .Concat([
            new AssistantToolsFileSearch(),
            new AssistantToolsCode()
        ])
        .ToArray(),
    toolResources: new CreateAssistantRequestToolResources
    {
        FileSearch = new CreateAssistantRequestToolResourcesFileSearch
        {
            VectorStores = new List<CreateAssistantRequestToolResourcesFileSearchVectorStore>
            {
                new()
                {
                    FileIds = [favoriteNumberFile.Id],
                },
            },
        },
    });

RunObject run = await api.Assistants.CreateThreadAndRunAsync(
    assistantId: assistant.Id,
    new CreateThreadRequest
    {
        Messages = [
            "Create a graph of a line with a slope that's my father's favorite number "
            + "and an offset that's my mother's favorite number.",
            "Include people's names in your response and cite where you found them."
        ],
    });

// Poll the run until it is no longer queued or in progress.
while (run.Status is RunObjectStatus.Queued or RunObjectStatus.InProgress or RunObjectStatus.RequiresAction)
{
    await Task.Delay(TimeSpan.FromSeconds(1));
    run = await api.Assistants.GetRunAsync(run.ThreadId, run.Id);

    // If the run requires action, resolve them.
    if (run.Status == RunObjectStatus.RequiresAction)
    {
        List<SubmitToolOutputsRunRequestToolOutput> toolOutputs = [];

        foreach (RunToolCallObject toolCall in run.RequiredAction?.SubmitToolOutputs.ToolCalls ?? [])
        {
            var json = await service.CallAsync(
                functionName: toolCall.Function.Name,
                argumentsAsJson: toolCall.Function.Arguments);
            toolOutputs.Add(new SubmitToolOutputsRunRequestToolOutput
            {
                ToolCallId = toolCall.Id,
                Output = json,
            });
        }

        // Submit the tool outputs to the assistant, which returns the run to the queued state.
        run = await api.Assistants.SubmitToolOuputsToRunAsync(
            threadId: run.ThreadId,
            runId: run.Id,
            toolOutputs: toolOutputs);
    }
}

// With the run complete, list the messages and display their content
if (run.Status == RunObjectStatus.Completed)
{
    ListMessagesResponse messages
        = await api.Assistants.ListMessagesAsync(run.ThreadId, order: ListMessagesOrder.Asc);

    foreach (MessageObject message in messages.Data)
    {
        Console.WriteLine($"[{message.Role.ToString().ToUpper()}]: ");
        foreach (ContentItem2 contentItem in message.Content)
        {
            if (contentItem.ImageFile is {} imageFile)
            {
                OpenAIFile imageInfo = await api.Files.RetrieveFileAsync(imageFile.ImageFile.FileId);
                byte[] imageBytes = await api.Files.DownloadFileAsync(imageFile.ImageFile.FileId);

                FileInfo fileInfo = new($"{imageInfo.Filename}.png");

                await File.WriteAllBytesAsync(fileInfo.FullName, imageBytes);

                Console.WriteLine($"<image: {new Uri(fileInfo.FullName).AbsoluteUri}>");
            }
            if (contentItem.ImageUrl is {} imageUrl)
            {
                Console.WriteLine($" <Image URL> {imageUrl.ImageUrl.Url}");
            }
            if (contentItem.Text is {} text)
            {
                Console.WriteLine($"{text.Text.Value}");

                // Include annotations, if any.
                if (text.Text.Annotations.Count > 0)
                {
                    Console.WriteLine();
                    foreach (AnnotationsItem annotation in text.Text.Annotations)
                    {
                        if (annotation.FileCitation is {} fileCitation)
                        {
                            Console.WriteLine($"* File citation, file ID: {fileCitation.FileCitation.FileId}");
                            Console.WriteLine($"* Text to replace: {fileCitation.Text}");
                            Console.WriteLine($"* Message content index range: {fileCitation.StartIndex}-{fileCitation.EndIndex}");
                        }
                        if (annotation.FilePath is {} filePath)
                        {
                            Console.WriteLine($"* File output, new file ID: {filePath.FilePath.FileId}");
                            Console.WriteLine($"* Text to replace: {filePath.Text}");
                            Console.WriteLine($"* Message content index range: {filePath.StartIndex}-{filePath.EndIndex}");
                        }
                    }
                }
            }
            if (contentItem.Refusal is {} refusal)
            {
                Console.WriteLine($"Refusal: {refusal.Refusal}");
            }
        }
        Console.WriteLine();
    }


    // List run steps for details about tool calls
    ListRunStepsResponse runSteps = await api.Assistants.ListRunStepsAsync(
        threadId: run.ThreadId,
        runId: run.Id,
        order: ListRunStepsOrder.Asc);
    foreach (RunStepObject step in runSteps.Data)
    {
        Console.WriteLine($"Run step: {step.Status}");
        foreach (var toolCall in step.StepDetails.ToolCalls?.ToolCalls ?? [])
        {
            if (toolCall.CodeInterpreter is {} codeInterpreter)
            {
                Console.WriteLine($" --> Tool call: {codeInterpreter.Type}");
                foreach (var output in codeInterpreter.CodeInterpreter.Outputs)
                {
                    if (output.Logs is {} logs)
                    {
                        Console.WriteLine($"    --> Output: {logs.Logs}");
                    }
                    if (output.Image is {} image)
                    {
                        Console.WriteLine($"    --> Output: {image.Image.FileId}");
                    }
                }
            }
            if (toolCall.FileSearch is {} fileSearch)
            {
                Console.WriteLine($" --> Tool call: {fileSearch.Type}");
                foreach (var output in fileSearch.FileSearch.Results ?? [])
                {
                    Console.WriteLine($"    --> Output: {output.FileId}");
                }
            }
            if (toolCall.Function is {} tool)
            {
                Console.WriteLine($" --> Tool call: {tool.Type}");
            }
        }
    }
}
else
{
    throw new NotImplementedException(run.Status.ToString());
}

// Optionally, delete any persistent resources you no longer need.
_ = await api.Assistants.DeleteThreadAsync(run.ThreadId);
_ = await api.Assistants.DeleteAssistantAsync(assistant.Id);
_ = await api.Files.DeleteFileAsync(favoriteNumberFile.Id);