diff --git a/.dotnet/CHANGELOG.md b/.dotnet/CHANGELOG.md index 1c3c7b898..4d7218707 100644 --- a/.dotnet/CHANGELOG.md +++ b/.dotnet/CHANGELOG.md @@ -4,6 +4,11 @@ ### Features Added +- Added support for the new [structured outputs](https://platform.openai.com/docs/guides/structured-outputs/introduction) response format feature, which enables chat completions, assistants, and tools on each of those clients to provide a specific JSON Schema that generated content should adhere to. + - To enable top-level structured outputs for response content, use `ChatResponseFormat.CreateJsonSchemaFormat()` and `AssistantResponseFormat.CreateJsonSchemaFormat()` as the `ResponseFormat` in method options like `ChatCompletionOptions` + - To enable structured outputs for function tools, set `StrictParameterSchemaEnabled` to `true` on the tool definition + - For more information, please see [the new section in readme.md](readme.md#how-to-use-structured-outputs) +- Chat completions: the request message types of `AssistantChatMessage`, `SystemChatMessage`, and `ToolChatMessage` now support array-based content part collections in addition to simple string input. - Added the following model factories (static classes that can be used to instantiate OpenAI models for mocking in non-live test scenarios): - `OpenAIAudioModelFactory` in the `OpenAI.Audio` namespace (commit_hash) - `OpenAIEmbeddingsModelFactory` in the `OpenAI.Embeddings` namespace (commit_hash) @@ -22,8 +27,12 @@ ### Bugs Fixed +- The `Assistants` namespace `VectorStoreCreationHelper` type now properly includes a `ChunkingStrategy` property. + ### Other Changes +- `ChatCompletion.ToString()` will no longer throw an exception when no content is present, as is the case for tool calls. Additionally, if a tool call is present with no content, `ToString()` will return the serialized form of the first available tool call. + ## 2.0.0-beta.8 (2024-07-31) ### Breaking Changes diff --git a/.dotnet/README.md b/.dotnet/README.md index 891b11eb8..7185e3464 100644 --- a/.dotnet/README.md +++ b/.dotnet/README.md @@ -17,6 +17,7 @@ It is generated from our [OpenAPI specification](https://github.com/openai/opena - [Using the `OpenAIClient` class](#using-the-openaiclient-class) - [How to use chat completions with streaming](#how-to-use-chat-completions-with-streaming) - [How to use chat completions with tools and function calling](#how-to-use-chat-completions-with-tools-and-function-calling) +- [How to use structured outputs](#how-to-use-structured-outputs) - [How to generate text embeddings](#how-to-generate-text-embeddings) - [How to generate images](#how-to-generate-images) - [How to transcribe audio](#how-to-transcribe-audio) @@ -296,6 +297,60 @@ do } while (requiresAction); ``` +## How to use structured outputs + +Beginning with the `gpt-4o-mini`, `gpt-4o-mini-2024-07-18`, and `gpt-4o-2024-08-06` model snapshots, structured outputs are available for both top-level response content and tool calls in the chat completion and assistants APIs. + +For information about the feature, see [the Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs/introduction). + +To use structured outputs to constrain chat completion content, set an appropriate `ChatResponseFormat` as in the following example: + +```csharp +ChatCompletionOptions options = new() +{ + ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat( + name: "math_reasoning", + jsonSchema: BinaryData.FromString(""" + { + "type": "object", + "properties": { + "steps": { + "type": "array", + "items": { + "type": "object", + "properties": { + "explanation": { "type": "string" }, + "output": { "type": "string" } + }, + "required": ["explanation", "output"], + "additionalProperties": false + } + }, + "final_answer": { "type": "string" } + }, + "required": ["steps", "final_answer"], + "additionalProperties": false + } + """), + strictSchemaEnabled: true) +}; + +ChatCompletion chatCompletion = await client.CompleteChatAsync( + ["How can I solve 8x + 7 = -23?"], + options); + +using JsonDocument structuredJson = JsonDocument.Parse(chatCompletion.ToString()); + +Console.WriteLine($"Final answer: {structuredJson.RootElement.GetProperty("final_answer").GetString()}"); +Console.WriteLine("Reasoning steps:"); + +foreach (JsonElement stepElement in structuredJson.RootElement.GetProperty("steps").EnumerateArray()) +{ + Console.WriteLine($" - Explanation: {stepElement.GetProperty("explanation").GetString()}"); + Console.WriteLine($" Output: {stepElement.GetProperty("output")}"); +} +``` + ## How to generate text embeddings In this example, you want to create a trip-planning website that allows customers to write a prompt describing the kind of hotel that they are looking for and then offers hotel recommendations that closely match this description. To achieve this, it is possible to use text embeddings to measure the relatedness of text strings. In summary, you can get embeddings of the hotel descriptions, store them in a vector database, and use them to build a search index that you can query using the embedding of a given customer's prompt. diff --git a/.dotnet/api/OpenAI.netstandard2.0.cs b/.dotnet/api/OpenAI.netstandard2.0.cs index 2b3b9d35f..a67971fb5 100644 --- a/.dotnet/api/OpenAI.netstandard2.0.cs +++ b/.dotnet/api/OpenAI.netstandard2.0.cs @@ -296,24 +296,33 @@ public class AssistantModificationOptions : IJsonModel.GetFormatFromOptions(ModelReaderWriterOptions options); BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); } - public class AssistantResponseFormat : IJsonModel, IPersistableModel { - protected AssistantResponseFormat(); + public abstract class AssistantResponseFormat : IEquatable, IEquatable, IJsonModel, IPersistableModel { public static AssistantResponseFormat Auto { get; } public static AssistantResponseFormat JsonObject { get; } public static AssistantResponseFormat Text { get; } - public bool Equals(AssistantResponseFormat other); + public static AssistantResponseFormat CreateAutoFormat(); + public static AssistantResponseFormat CreateJsonObjectFormat(); + public static AssistantResponseFormat CreateJsonSchemaFormat(string name, BinaryData jsonSchema, string description = null, bool? strictSchemaEnabled = null); + public static AssistantResponseFormat CreateTextFormat(); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode(); - public static bool operator ==(AssistantResponseFormat left, AssistantResponseFormat right); - public static implicit operator AssistantResponseFormat(string value); - public static bool operator !=(AssistantResponseFormat left, AssistantResponseFormat right); + [EditorBrowsable(EditorBrowsableState.Never)] + public static bool operator ==(AssistantResponseFormat first, AssistantResponseFormat second); + [EditorBrowsable(EditorBrowsableState.Never)] + public static implicit operator AssistantResponseFormat(string plainTextFormat); + [EditorBrowsable(EditorBrowsableState.Never)] + public static bool operator !=(AssistantResponseFormat first, AssistantResponseFormat second); AssistantResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); AssistantResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + [EditorBrowsable(EditorBrowsableState.Never)] + bool IEquatable.Equals(AssistantResponseFormat other); + [EditorBrowsable(EditorBrowsableState.Never)] + bool IEquatable.Equals(string other); public override string ToString(); } public class AssistantThread : IJsonModel, IPersistableModel { @@ -363,10 +372,11 @@ public class FileSearchToolResources : IJsonModel, IPer } public class FunctionToolDefinition : ToolDefinition, IJsonModel, IPersistableModel { public FunctionToolDefinition(); - public FunctionToolDefinition(string name, string description = null, BinaryData parameters = null); + public FunctionToolDefinition(string name); public string Description { get; set; } public required string FunctionName { get; set; } public BinaryData Parameters { get; set; } + public bool? StrictParameterSchemaEnabled { get; set; } FunctionToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); FunctionToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); @@ -384,6 +394,7 @@ public abstract class MessageContent : IJsonModel, IPersistableM public MessageImageDetail? ImageDetail { get; } public string ImageFileId { get; } public Uri ImageUrl { get; } + public string Refusal { get; } public string Text { get; } public IReadOnlyList TextAnnotations { get; } public static MessageContent FromImageFileId(string imageFileId, MessageImageDetail? detail = null); @@ -402,6 +413,7 @@ public class MessageContentUpdate : StreamingUpdate { public string ImageFileId { get; } public string MessageId { get; } public int MessageIndex { get; } + public string RefusalUpdate { get; } public MessageRole? Role { get; } public string Text { get; } public TextAnnotationUpdate TextAnnotation { get; } @@ -937,7 +949,7 @@ public abstract class ToolDefinition : IJsonModel, IPersistableM protected ToolDefinition(string type); public static CodeInterpreterToolDefinition CreateCodeInterpreter(); public static FileSearchToolDefinition CreateFileSearch(int? maxResults = null); - public static FunctionToolDefinition CreateFunction(string name, string description = null, BinaryData parameters = null); + public static FunctionToolDefinition CreateFunction(string name, string description = null, BinaryData parameters = null, bool? strictParameterSchemaEnabled = null); ToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); ToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); @@ -969,6 +981,7 @@ public class VectorStoreCreationHelper : IJsonModel, public VectorStoreCreationHelper(); public VectorStoreCreationHelper(IEnumerable files, IDictionary metadata = null); public VectorStoreCreationHelper(IEnumerable fileIds, IDictionary metadata = null); + public FileChunkingStrategy ChunkingStrategy { get; set; } public IList FileIds { get; } public IDictionary Metadata { get; } VectorStoreCreationHelper IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); @@ -1165,10 +1178,13 @@ namespace OpenAI.Chat { public class AssistantChatMessage : ChatMessage, IJsonModel, IPersistableModel { public AssistantChatMessage(ChatCompletion chatCompletion); public AssistantChatMessage(ChatFunctionCall functionCall, string content = null); + public AssistantChatMessage(params ChatMessageContentPart[] contentParts); + public AssistantChatMessage(IEnumerable contentParts); public AssistantChatMessage(IEnumerable toolCalls, string content = null); public AssistantChatMessage(string content); public ChatFunctionCall FunctionCall { get; set; } public string ParticipantName { get; set; } + public string Refusal { get; set; } public IList ToolCalls { get; } AssistantChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); @@ -1204,6 +1220,8 @@ public class ChatCompletion : IJsonModel, IPersistableModel RefusalTokenLogProbabilities { get; } public ChatMessageRole Role { get; } public string SystemFingerprint { get; } public IReadOnlyList ToolCalls { get; } @@ -1279,13 +1297,22 @@ public class ChatFunctionChoice : IJsonModel, IPersistableMo BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); } public abstract class ChatMessage : IJsonModel, IPersistableModel { - public IList Content { get; protected set; } + protected ChatMessage(); + protected internal ChatMessage(ChatMessageRole role, IEnumerable contentParts); + protected internal ChatMessage(ChatMessageRole role, string content); + public IList Content { get; } public static AssistantChatMessage CreateAssistantMessage(ChatCompletion chatCompletion); public static AssistantChatMessage CreateAssistantMessage(ChatFunctionCall functionCall, string content = null); + public static AssistantChatMessage CreateAssistantMessage(params ChatMessageContentPart[] contentParts); + public static AssistantChatMessage CreateAssistantMessage(IEnumerable contentParts); public static AssistantChatMessage CreateAssistantMessage(IEnumerable toolCalls, string content = null); public static AssistantChatMessage CreateAssistantMessage(string content); public static FunctionChatMessage CreateFunctionMessage(string functionName, string content); + public static SystemChatMessage CreateSystemMessage(params ChatMessageContentPart[] contentParts); + public static SystemChatMessage CreateSystemMessage(IEnumerable contentParts); public static SystemChatMessage CreateSystemMessage(string content); + public static ToolChatMessage CreateToolChatMessage(string toolCallId, params ChatMessageContentPart[] contentParts); + public static ToolChatMessage CreateToolChatMessage(string toolCallId, IEnumerable contentParts); public static ToolChatMessage CreateToolChatMessage(string toolCallId, string content); public static UserChatMessage CreateUserMessage(params ChatMessageContentPart[] contentParts); public static UserChatMessage CreateUserMessage(IEnumerable contentParts); @@ -1304,9 +1331,11 @@ public class ChatMessageContentPart : IJsonModel, IPersi public ImageChatMessageContentPartDetail? ImageDetail { get; } public Uri ImageUri { get; } public ChatMessageContentPartKind Kind { get; } + public string Refusal { get; } public string Text { get; } public static ChatMessageContentPart CreateImageMessageContentPart(BinaryData imageBytes, string imageBytesMediaType, ImageChatMessageContentPartDetail? imageDetail = null); public static ChatMessageContentPart CreateImageMessageContentPart(Uri imageUri, ImageChatMessageContentPartDetail? imageDetail = null); + public static ChatMessageContentPart CreateRefusalMessageContentPart(string refusal); public static ChatMessageContentPart CreateTextMessageContentPart(string text); public static implicit operator ChatMessageContentPart(string content); ChatMessageContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); @@ -1321,6 +1350,7 @@ public class ChatMessageContentPart : IJsonModel, IPersi private readonly int _dummyPrimitive; public ChatMessageContentPartKind(string value); public static ChatMessageContentPartKind Image { get; } + public static ChatMessageContentPartKind Refusal { get; } public static ChatMessageContentPartKind Text { get; } public readonly bool Equals(ChatMessageContentPartKind other); [EditorBrowsable(EditorBrowsableState.Never)] @@ -1339,14 +1369,28 @@ public enum ChatMessageRole { Tool = 3, Function = 4 } - public class ChatResponseFormat : IJsonModel, IPersistableModel { + public abstract class ChatResponseFormat : IEquatable, IJsonModel, IPersistableModel { public static ChatResponseFormat JsonObject { get; } public static ChatResponseFormat Text { get; } + public static ChatResponseFormat CreateJsonObjectFormat(); + public static ChatResponseFormat CreateJsonSchemaFormat(string name, BinaryData jsonSchema, string description = null, bool? strictSchemaEnabled = null); + public static ChatResponseFormat CreateTextFormat(); + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj); + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode(); + [EditorBrowsable(EditorBrowsableState.Never)] + public static bool operator ==(ChatResponseFormat first, ChatResponseFormat second); + [EditorBrowsable(EditorBrowsableState.Never)] + public static bool operator !=(ChatResponseFormat first, ChatResponseFormat second); ChatResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); ChatResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + [EditorBrowsable(EditorBrowsableState.Never)] + bool IEquatable.Equals(ChatResponseFormat other); + public override string ToString(); } public class ChatTokenLogProbabilityInfo : IJsonModel, IPersistableModel { public float LogProbability { get; } @@ -1384,7 +1428,8 @@ public class ChatTool : IJsonModel, IPersistableModel { public string FunctionName { get; } public BinaryData FunctionParameters { get; } public ChatToolKind Kind { get; } - public static ChatTool CreateFunctionTool(string functionName, string functionDescription = null, BinaryData functionParameters = null); + public bool? StrictParameterSchemaEnabled { get; } + public static ChatTool CreateFunctionTool(string functionName, string functionDescription = null, BinaryData functionParameters = null, bool? strictParameterSchemaEnabled = null); ChatTool IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); ChatTool IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); @@ -1480,6 +1525,8 @@ public class StreamingChatCompletionUpdate : IJsonModel RefusalTokenLogProbabilities { get; } + public string RefusalUpdate { get; } public ChatMessageRole? Role { get; } public string SystemFingerprint { get; } public IReadOnlyList ToolCallUpdates { get; } @@ -1512,6 +1559,8 @@ public class StreamingChatToolCallUpdate : IJsonModel.Write(ModelReaderWriterOptions options); } public class SystemChatMessage : ChatMessage, IJsonModel, IPersistableModel { + public SystemChatMessage(params ChatMessageContentPart[] contentParts); + public SystemChatMessage(IEnumerable contentParts); public SystemChatMessage(string content); public string ParticipantName { get; set; } SystemChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); @@ -1522,6 +1571,8 @@ public class SystemChatMessage : ChatMessage, IJsonModel, IPe protected override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); } public class ToolChatMessage : ChatMessage, IJsonModel, IPersistableModel { + public ToolChatMessage(string toolCallId, params ChatMessageContentPart[] contentParts); + public ToolChatMessage(string toolCallId, IEnumerable contentParts); public ToolChatMessage(string toolCallId, string content); public string ToolCallId { get; } ToolChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); @@ -2256,10 +2307,9 @@ public class VectorStoreFileAssociationError : IJsonModel.Create", typeof(Utf8JsonReader), typeof(ModelReaderWriterOptions))] [CodeGenSuppress("global::System.ClientModel.Primitives.IPersistableModel.Write", typeof(ModelReaderWriterOptions))] [CodeGenSuppress("global::System.ClientModel.Primitives.IPersistableModel.Create", typeof(BinaryData), typeof(ModelReaderWriterOptions))] +[CodeGenSuppress("global::System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions", typeof(ModelReaderWriterOptions))] public partial class AssistantResponseFormat : IJsonModel { + internal static void SerializeAssistantResponseFormat(AssistantResponseFormat instance, Utf8JsonWriter writer, ModelReaderWriterOptions options = null) + { + throw new InvalidOperationException(); + } + + internal static AssistantResponseFormat DeserializeAssistantResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + return element.ValueKind switch + { + JsonValueKind.String => InternalAssistantResponseFormatPlainTextNoObject.DeserializeInternalAssistantResponseFormatPlainTextNoObject(element, options), + JsonValueKind.Object when element.TryGetProperty("type", out JsonElement discriminatorElement) + => discriminatorElement.GetString() switch + { + "json_object" => InternalAssistantResponseFormatJsonObject.DeserializeInternalAssistantResponseFormatJsonObject(element, options), + "json_schema" => InternalAssistantResponseFormatJsonSchema.DeserializeInternalAssistantResponseFormatJsonSchema(element, options), + "text" => InternalAssistantResponseFormatText.DeserializeInternalAssistantResponseFormatText(element, options), + _ => null, + }, + _ => null, + }; + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - => CustomSerializationHelpers.SerializeInstance(this, SerializeAssistantResponseFormat, writer, options); + => CustomSerializationHelpers.SerializeInstance(this, SerializeAssistantResponseFormat, writer, options); AssistantResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => CustomSerializationHelpers.DeserializeNewInstance(this, DeserializeAssistantResponseFormat, ref reader, options); @@ -23,53 +46,15 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpt AssistantResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => CustomSerializationHelpers.DeserializeNewInstance(this, DeserializeAssistantResponseFormat, data, options); - internal static void SerializeAssistantResponseFormat(AssistantResponseFormat formatInstance, Utf8JsonWriter writer, ModelReaderWriterOptions options) + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static AssistantResponseFormat FromResponse(PipelineResponse response) { - if (formatInstance._plainTextValue is not null) - { - writer.WriteStringValue(formatInstance._plainTextValue); - } - else - { - writer.WriteStartObject(); - writer.WritePropertyName("type"u8); - writer.WriteStringValue(formatInstance._objectType); - writer.WriteSerializedAdditionalRawData(formatInstance.SerializedAdditionalRawData, options); - writer.WriteEndObject(); - } + throw new InvalidOperationException(); } - internal static AssistantResponseFormat DeserializeAssistantResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + internal virtual BinaryContent ToBinaryContent() { - options ??= ModelSerializationExtensions.WireOptions; - - string plainTextValue = null; - string objectType = null; - IDictionary rawDataDictionary = new ChangeTrackingDictionary(); - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - else if (element.ValueKind == JsonValueKind.String) - { - plainTextValue = element.GetString(); - } - else - { - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - objectType = property.Value.GetString(); - continue; - } - if (true) - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - } - return new AssistantResponseFormat(plainTextValue, objectType, rawDataDictionary); + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); } } diff --git a/.dotnet/src/Custom/Assistants/AssistantResponseFormat.cs b/.dotnet/src/Custom/Assistants/AssistantResponseFormat.cs index 226fa31df..c87b9b076 100644 --- a/.dotnet/src/Custom/Assistants/AssistantResponseFormat.cs +++ b/.dotnet/src/Custom/Assistants/AssistantResponseFormat.cs @@ -1,107 +1,109 @@ +using OpenAI.Internal; using System; -using System.Collections.Generic; +using System.ClientModel.Primitives; using System.ComponentModel; namespace OpenAI.Assistants; -/// -/// Specifies the format that the model must output. Compatible with GPT-4o, GPT-4 Turbo, and all GPT-3.5 Turbo models since gpt-3.5-turbo-1106. -/// -/// -/// -/// Setting to { "type": "json_object" } enables JSON mode, which guarantees the message the model generates is valid JSON. -/// -/// -/// Important: when using JSON mode, you must also instruct the model to produce JSON yourself via a system or user message.Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request.Also note that the message content may be partially cut off if finish_reason= "length", which indicates the generation exceeded max_tokens or the conversation exceeded the max context length. -/// -/// [CodeGenModel("AssistantResponseFormat")] -public partial class AssistantResponseFormat +public partial class AssistantResponseFormat : IEquatable, IEquatable { - private readonly string _plainTextValue; - private readonly string _objectType; - private readonly IDictionary SerializedAdditionalRawData; + public static AssistantResponseFormat Auto { get; } = CreateAutoFormat(); + public static AssistantResponseFormat Text { get; } = CreateTextFormat(); + public static AssistantResponseFormat JsonObject { get; } = CreateJsonObjectFormat(); - private const string AutoValue = "auto"; - private const string TextValue = "text"; - private const string JsonObjectValue = "json_object"; - - /// - /// Default option. Specifies that the model should automatically determine whether it should respond with - /// plain text or another format. - /// - public static AssistantResponseFormat Auto { get; } - = new(plainTextValue: AutoValue, objectType: null, serializedAdditionalRawData: null); + public static AssistantResponseFormat CreateAutoFormat() + => new InternalAssistantResponseFormatPlainTextNoObject("auto"); + public static AssistantResponseFormat CreateTextFormat() + => new InternalAssistantResponseFormatText(); + public static AssistantResponseFormat CreateJsonObjectFormat() + => new InternalAssistantResponseFormatJsonObject(); + public static AssistantResponseFormat CreateJsonSchemaFormat( + string name, + BinaryData jsonSchema, + string description = null, + bool? strictSchemaEnabled = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNull(jsonSchema, nameof(jsonSchema)); - /// - /// Specifies that the model should respond with plain text. - /// - public static AssistantResponseFormat Text { get; } - = new(plainTextValue: null, objectType: TextValue, serializedAdditionalRawData: null); + InternalResponseFormatJsonSchemaJsonSchema internalSchema = new( + description, + name, + jsonSchema, + strictSchemaEnabled, + null); + return new InternalAssistantResponseFormatJsonSchema(internalSchema); + } - /// - /// Specifies that the model should reply with a structured JSON object, enabling JSON mode. - /// - /// - /// **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a - /// system or user message. Without this, the model may generate an unending stream of whitespace until the - /// generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that - /// the message content may be partially cut off if `finish_reason="length"`, which indicates the generation - /// exceeded `max_tokens` or the conversation exceeded the max context length. - /// - public static AssistantResponseFormat JsonObject { get; } - = new(plainTextValue: null, objectType: JsonObjectValue, serializedAdditionalRawData: null); + [EditorBrowsable(EditorBrowsableState.Never)] + public static bool operator ==(AssistantResponseFormat first, AssistantResponseFormat second) + { + if (first is null) + { + return second is null; + } + return first.Equals(second); + } - /// - /// Creates a new instance of for mocking. - /// - protected AssistantResponseFormat() - { } + [EditorBrowsable(EditorBrowsableState.Never)] + public static bool operator !=(AssistantResponseFormat first, AssistantResponseFormat second) + => !(first == second); - internal AssistantResponseFormat(string plainTextValue, string objectType, IDictionary serializedAdditionalRawData) + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) { - _plainTextValue = plainTextValue; - _objectType = objectType; - SerializedAdditionalRawData = serializedAdditionalRawData ?? new ChangeTrackingDictionary(); + return (this as IEquatable).Equals(obj as AssistantResponseFormat) + || ToString().Equals(obj?.ToString()); } - /// - public static bool operator ==(AssistantResponseFormat left, AssistantResponseFormat right) => left.Equals(right); - /// - public static bool operator !=(AssistantResponseFormat left, AssistantResponseFormat right) => !left.Equals(right); + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => ToString().GetHashCode(); - /// - public static implicit operator AssistantResponseFormat(string value) + [EditorBrowsable(EditorBrowsableState.Never)] + public static implicit operator AssistantResponseFormat(string plainTextFormat) + => new InternalAssistantResponseFormatPlainTextNoObject(plainTextFormat); + + [EditorBrowsable(EditorBrowsableState.Never)] + bool IEquatable.Equals(AssistantResponseFormat other) { - if (string.Equals(value, AutoValue, StringComparison.OrdinalIgnoreCase)) + if (other is null) { - return Auto; + return false; } - if (string.Equals(value, TextValue, StringComparison.OrdinalIgnoreCase)) + + if (Object.ReferenceEquals(this, other)) { - return Text; + return true; } - if (string.Equals(value, JsonObjectValue, StringComparison.OrdinalIgnoreCase)) + + return + (this is InternalAssistantResponseFormatPlainTextNoObject thisPlainText + && other is InternalAssistantResponseFormatPlainTextNoObject otherPlainText + && thisPlainText.Value.Equals(otherPlainText.Value)) + || (this is InternalAssistantResponseFormatText && other is InternalAssistantResponseFormatText) + || (this is InternalAssistantResponseFormatJsonObject && other is InternalAssistantResponseFormatJsonObject) + || (this is InternalAssistantResponseFormatJsonSchema thisJsonSchema + && other is InternalAssistantResponseFormatJsonSchema otherJsonSchema + && thisJsonSchema.JsonSchema.Name.Equals(otherJsonSchema.JsonSchema.Name)); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + bool IEquatable.Equals(string other) + { + return this is InternalAssistantResponseFormatPlainTextNoObject thisPlainText + && thisPlainText.Value.Equals(other); + } + + public override string ToString() + { + if (this is InternalAssistantResponseFormatPlainTextNoObject plainTextInstance) { - return JsonObject; + return plainTextInstance.Value; } else { - return new(plainTextValue: null, objectType: value, serializedAdditionalRawData: null); + return ModelReaderWriter.Write(this).ToString(); } } - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is AssistantResponseFormat other && Equals(other); - /// - public bool Equals(AssistantResponseFormat other) - => string.Equals(_plainTextValue, other?._plainTextValue, StringComparison.InvariantCultureIgnoreCase) - && string.Equals(_objectType, other?._objectType, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => $"{_plainTextValue}/{_objectType}".GetHashCode(); - /// - public override string ToString() => _plainTextValue ?? _objectType; -} +} \ No newline at end of file diff --git a/.dotnet/src/Custom/Assistants/FileSearchToolResources.cs b/.dotnet/src/Custom/Assistants/FileSearchToolResources.cs index 66c0a1d43..53e0d6bcf 100644 --- a/.dotnet/src/Custom/Assistants/FileSearchToolResources.cs +++ b/.dotnet/src/Custom/Assistants/FileSearchToolResources.cs @@ -4,7 +4,7 @@ namespace OpenAI.Assistants; -[CodeGenModel("AssistantObjectToolResourcesFileSearch")] +[CodeGenModel("ToolResourcesFileSearch")] [CodeGenSerialization(nameof(NewVectorStores), "vector_stores", SerializationValueHook = nameof(SerializeNewVectorStores))] public partial class FileSearchToolResources { @@ -24,7 +24,7 @@ public IList VectorStoreIds } } - [CodeGenMember("vector_stores")] + [CodeGenMember("VectorStores")] public IList NewVectorStores { get; } = new ChangeTrackingList(); public FileSearchToolResources() diff --git a/.dotnet/src/Custom/Assistants/FunctionToolDefinition.cs b/.dotnet/src/Custom/Assistants/FunctionToolDefinition.cs index 764e93ccf..70e2ba163 100644 --- a/.dotnet/src/Custom/Assistants/FunctionToolDefinition.cs +++ b/.dotnet/src/Custom/Assistants/FunctionToolDefinition.cs @@ -34,15 +34,21 @@ public BinaryData Parameters set => _internalFunction.Parameters = value; } + public bool? StrictParameterSchemaEnabled + { + get => _internalFunction.Strict; + set => _internalFunction.Strict = value; + } + /// /// Creates a new instance of . /// [SetsRequiredMembers] - public FunctionToolDefinition(string name, string description = null, BinaryData parameters = null) + public FunctionToolDefinition(string name) : base("function") { Argument.AssertNotNullOrEmpty(name, nameof(name)); - _internalFunction = new(description, name, parameters, null); + _internalFunction = new(null, name, null, null, null); } /// diff --git a/.dotnet/src/Custom/Assistants/Internal/GeneratorStubs.Internal.cs b/.dotnet/src/Custom/Assistants/Internal/GeneratorStubs.Internal.cs index e8fae6b4f..08f753db0 100644 --- a/.dotnet/src/Custom/Assistants/Internal/GeneratorStubs.Internal.cs +++ b/.dotnet/src/Custom/Assistants/Internal/GeneratorStubs.Internal.cs @@ -120,6 +120,9 @@ internal partial class InternalMessageContentItemFileObjectImageFile [CodeGenModel("MessageContentTextObjectText")] internal partial class InternalMessageContentTextObjectText { } +[CodeGenModel("MessageContentRefusalObjectType")] +internal readonly partial struct InternalMessageContentRefusalObjectType { } + [CodeGenModel("RunStepDetailsMessageCreationObjectMessageCreation")] internal partial class InternalRunStepDetailsMessageCreationObjectMessageCreation { } @@ -189,9 +192,6 @@ internal readonly partial struct InternalAssistantsNamedToolChoiceType { } [CodeGenModel("RunStepDeltaStepDetailsToolCallsCodeObject")] internal partial class InternalRunStepDeltaStepDetailsToolCallsCodeObject { } -[CodeGenModel("RunStepUpdateCodeInterpreterOutput")] -internal abstract partial class InternalRunStepUpdateCodeInterpreterOutput { } - [CodeGenModel("RunStepDeltaStepDetailsToolCallsCodeOutputImageObject")] internal partial class InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject { } @@ -232,12 +232,6 @@ internal partial class InternalRunStepDeltaStepDetails { } [CodeGenModel("RunStepDeltaStepDetailsToolCallsFunctionObjectFunction")] internal partial class InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction { } -[CodeGenModel("AssistantsApiResponseFormat")] -internal partial class InternalAssistantsApiResponseFormat { } - -[CodeGenModel("AssistantsApiResponseFormatType")] -internal readonly partial struct InternalAssistantsApiResponseFormatType { } - [CodeGenModel("AssistantsNamedToolChoiceFunction")] internal partial class InternalAssistantsNamedToolChoiceFunction { } @@ -307,33 +301,15 @@ internal readonly partial struct InternalMessageObjectRole { } [CodeGenModel("CreateRunRequestModel")] internal readonly partial struct InternalCreateRunRequestModel { } -[CodeGenModel("CreateRunRequestToolChoice")] -internal readonly partial struct InternalCreateRunRequestToolChoice { } - -[CodeGenModel("CreateAssistantRequestResponseFormat1")] -internal readonly partial struct InternalCreateAssistantRequestResponseFormat { } - [CodeGenModel("CreateAssistantRequestToolResources")] internal partial class InternalCreateAssistantRequestToolResources { } [CodeGenModel("CreateAssistantRequestToolResourcesCodeInterpreter")] internal partial class InternalCreateAssistantRequestToolResourcesCodeInterpreter { } -[CodeGenModel("CreateAssistantRequestToolResourcesFileSearchBase")] -internal partial class InternalCreateAssistantRequestToolResourcesFileSearchBase { } - -[CodeGenModel("CreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers")] -internal partial class InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers { } - -[CodeGenModel("CreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences")] -internal partial class InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences { } - [CodeGenModel("CreateThreadAndRunRequestModel")] internal readonly partial struct InternalCreateThreadAndRunRequestModel { } -[CodeGenModel("CreateThreadAndRunRequestResponseFormat")] -internal readonly partial struct InternalCreateThreadAndRunRequestResponseFormat { } - [CodeGenModel("CreateThreadAndRunRequestToolChoice")] internal readonly partial struct InternalCreateThreadAndRunRequestToolChoice { } @@ -343,9 +319,6 @@ internal partial class InternalCreateThreadAndRunRequestToolResources { } [CodeGenModel("CreateThreadAndRunRequestToolResourcesCodeInterpreter")] internal partial class InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter { } -[CodeGenModel("CreateThreadAndRunRequestToolResourcesFileSearch")] -internal partial class InternalCreateThreadAndRunRequestToolResourcesFileSearch { } - [CodeGenModel("CreateThreadRequestToolResources")] internal partial class InternalCreateThreadRequestToolResources { } @@ -355,33 +328,18 @@ internal partial class InternalCreateThreadRequestToolResourcesCodeInterpreter { [CodeGenModel("CreateThreadRequestToolResourcesFileSearchBase")] internal partial class InternalCreateThreadRequestToolResourcesFileSearchBase { } -[CodeGenModel("CreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers")] -internal partial class InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers { } - -[CodeGenModel("CreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore")] -internal partial class InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore { } - -[CodeGenModel("CreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences")] -internal partial class InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences { } - [CodeGenModel("ModifyAssistantRequestToolResources")] internal partial class InternalModifyAssistantRequestToolResources { } [CodeGenModel("ModifyAssistantRequestToolResourcesCodeInterpreter")] internal partial class InternalModifyAssistantRequestToolResourcesCodeInterpreter { } -[CodeGenModel("ModifyAssistantRequestToolResourcesFileSearch")] -internal partial class InternalModifyAssistantRequestToolResourcesFileSearch { } - [CodeGenModel("ModifyThreadRequestToolResources")] internal partial class InternalModifyThreadRequestToolResources { } [CodeGenModel("ModifyThreadRequestToolResourcesCodeInterpreter")] internal partial class InternalModifyThreadRequestToolResourcesCodeInterpreter { } -[CodeGenModel("ModifyThreadRequestToolResourcesFileSearch")] -internal partial class InternalModifyThreadRequestToolResourcesFileSearch { } - [CodeGenModel("ThreadObjectToolResources")] internal partial class InternalThreadObjectToolResources { } @@ -396,3 +354,10 @@ internal partial class InternalAssistantToolsFileSearchTypeOnly { } [CodeGenModel("AssistantToolsFileSearchTypeOnlyType")] internal readonly partial struct InternalAssistantToolsFileSearchTypeOnlyType { } + +[CodeGenModel("AssistantResponseFormatText")] internal partial class InternalAssistantResponseFormatText { } +[CodeGenModel("AssistantResponseFormatJsonObject")] internal partial class InternalAssistantResponseFormatJsonObject { } +[CodeGenModel("AssistantResponseFormatJsonSchema")] internal partial class InternalAssistantResponseFormatJsonSchema { } +[CodeGenModel("UnknownAssistantResponseFormat")] internal partial class InternalUnknownAssistantResponseFormat { } +[CodeGenModel("MessageDeltaContentRefusalObject")] internal partial class InternalMessageDeltaContentRefusalObject { } +[CodeGenModel("ToolResourcesFileSearchIdsOnly")] internal partial class InternalToolResourcesFileSearchIdsOnly { } diff --git a/.dotnet/src/Custom/Assistants/Internal/InternalAssistantResponseFormatPlainTextNoObject.Serialization.cs b/.dotnet/src/Custom/Assistants/Internal/InternalAssistantResponseFormatPlainTextNoObject.Serialization.cs new file mode 100644 index 000000000..1d962611c --- /dev/null +++ b/.dotnet/src/Custom/Assistants/Internal/InternalAssistantResponseFormatPlainTextNoObject.Serialization.cs @@ -0,0 +1,36 @@ +using System; +using System.ClientModel.Primitives; +using System.Text.Json; + +namespace OpenAI.Assistants; + +internal partial class InternalAssistantResponseFormatPlainTextNoObject : IJsonModel +{ + internal static void SerializeInternalAssistantResponseFormatPlainTextNoObject(InternalAssistantResponseFormatPlainTextNoObject instance, Utf8JsonWriter writer, ModelReaderWriterOptions options = null) + { + writer.WriteStringValue(instance.Value); + } + + internal static InternalAssistantResponseFormatPlainTextNoObject DeserializeInternalAssistantResponseFormatPlainTextNoObject(JsonElement element, ModelReaderWriterOptions options = null) + { + if (element.ValueKind == JsonValueKind.String) + { + return new(element.GetString()); + } + return null; + } + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + => CustomSerializationHelpers.SerializeInstance(this, SerializeInternalAssistantResponseFormatPlainTextNoObject, writer, options); + + InternalAssistantResponseFormatPlainTextNoObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + => CustomSerializationHelpers.DeserializeNewInstance(this, DeserializeInternalAssistantResponseFormatPlainTextNoObject, ref reader, options); + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + => CustomSerializationHelpers.SerializeInstance(this, options); + + InternalAssistantResponseFormatPlainTextNoObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + => CustomSerializationHelpers.DeserializeNewInstance(this, DeserializeInternalAssistantResponseFormatPlainTextNoObject, data, options); + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; +} diff --git a/.dotnet/src/Custom/Assistants/Internal/InternalAssistantResponseFormatPlainTextNoObject.cs b/.dotnet/src/Custom/Assistants/Internal/InternalAssistantResponseFormatPlainTextNoObject.cs new file mode 100644 index 000000000..6c3e2ee7c --- /dev/null +++ b/.dotnet/src/Custom/Assistants/Internal/InternalAssistantResponseFormatPlainTextNoObject.cs @@ -0,0 +1,11 @@ +namespace OpenAI.Assistants; + +internal partial class InternalAssistantResponseFormatPlainTextNoObject : AssistantResponseFormat +{ + public string Value { get; set; } + + public InternalAssistantResponseFormatPlainTextNoObject(string value) + { + Value = value; + } +} \ No newline at end of file diff --git a/.dotnet/src/Custom/Assistants/Internal/InternalMessageRefusalContent.Serialization.cs b/.dotnet/src/Custom/Assistants/Internal/InternalMessageRefusalContent.Serialization.cs new file mode 100644 index 000000000..b14bf17a6 --- /dev/null +++ b/.dotnet/src/Custom/Assistants/Internal/InternalMessageRefusalContent.Serialization.cs @@ -0,0 +1,27 @@ +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Assistants; + +[CodeGenSuppress("global::System.ClientModel.Primitives.IJsonModel.Write", typeof(Utf8JsonWriter), typeof(ModelReaderWriterOptions))] +internal partial class InternalMessageRefusalContent : IJsonModel +{ + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + => CustomSerializationHelpers.SerializeInstance(this, SerializeInternalMessageRefusalContent, writer, options); + + internal static void SerializeInternalMessageRefusalContent(InternalMessageRefusalContent instance, Utf8JsonWriter writer, ModelReaderWriterOptions options) + => instance.WriteCore(writer, options); + + protected override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(_type); + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(Refusal); + writer.WriteEndObject(); + } +} \ No newline at end of file diff --git a/.dotnet/src/Custom/Assistants/Internal/InternalMessageRefusalContent.cs b/.dotnet/src/Custom/Assistants/Internal/InternalMessageRefusalContent.cs new file mode 100644 index 000000000..ed0188314 --- /dev/null +++ b/.dotnet/src/Custom/Assistants/Internal/InternalMessageRefusalContent.cs @@ -0,0 +1,20 @@ +using System; + +namespace OpenAI.Assistants; + +/// +/// Represents an item of image URL content within an Assistants API message. +/// +/// +/// Use the method to +/// create an instance of this type. +/// +[CodeGenModel("MessageContentRefusalObject")] +internal partial class InternalMessageRefusalContent +{ + [CodeGenMember("Type")] + private string _type = "refusal"; + + [CodeGenMember("Refusal")] + public string InternalRefusal { get; set; } +} diff --git a/.dotnet/src/Custom/Assistants/MessageContent.cs b/.dotnet/src/Custom/Assistants/MessageContent.cs index a32b8e982..8043d79cb 100644 --- a/.dotnet/src/Custom/Assistants/MessageContent.cs +++ b/.dotnet/src/Custom/Assistants/MessageContent.cs @@ -45,11 +45,13 @@ public static MessageContent FromText(string text) public string Text => AsInternalRequestText?.InternalText ?? AsInternalResponseText?.InternalText; /// public IReadOnlyList TextAnnotations => AsInternalResponseText?.InternalAnnotations ?? []; + public string Refusal => AsRefusal?.InternalRefusal; private InternalMessageImageFileContent AsInternalImageFile => this as InternalMessageImageFileContent; private InternalMessageImageUrlContent AsInternalImageUrl => this as InternalMessageImageUrlContent; private InternalResponseMessageTextContent AsInternalResponseText => this as InternalResponseMessageTextContent; private InternalRequestMessageTextContent AsInternalRequestText => this as InternalRequestMessageTextContent; + private InternalMessageRefusalContent AsRefusal => this as InternalMessageRefusalContent; /// /// The implicit conversion operator that infers an equivalent diff --git a/.dotnet/src/Custom/Assistants/Streaming/MessageContentUpdate.cs b/.dotnet/src/Custom/Assistants/Streaming/MessageContentUpdate.cs index 468e27082..ad6944617 100644 --- a/.dotnet/src/Custom/Assistants/Streaming/MessageContentUpdate.cs +++ b/.dotnet/src/Custom/Assistants/Streaming/MessageContentUpdate.cs @@ -21,6 +21,7 @@ public partial class MessageContentUpdate : StreamingUpdate public int MessageIndex => _textContent?.Index ?? _imageFileContent?.Index ?? _imageUrlContent?.Index + ?? _refusalContent?.Index ?? TextAnnotation?.ContentIndex ?? 0; @@ -42,9 +43,12 @@ public partial class MessageContentUpdate : StreamingUpdate /// public TextAnnotationUpdate TextAnnotation { get; } + public string RefusalUpdate => _refusalContent?.Refusal; + private readonly InternalMessageDeltaContentImageFileObject _imageFileContent; private readonly InternalMessageDeltaContentTextObject _textContent; private readonly InternalMessageDeltaContentImageUrlObject _imageUrlContent; + private readonly InternalMessageDeltaContentRefusalObject _refusalContent; private readonly InternalMessageDeltaObject _delta; internal MessageContentUpdate(InternalMessageDeltaObject delta, InternalMessageDeltaContent content) @@ -54,6 +58,7 @@ internal MessageContentUpdate(InternalMessageDeltaObject delta, InternalMessageD _textContent = content as InternalMessageDeltaContentTextObject; _imageFileContent = content as InternalMessageDeltaContentImageFileObject; _imageUrlContent = content as InternalMessageDeltaContentImageUrlObject; + _refusalContent = content as InternalMessageDeltaContentRefusalObject; } internal MessageContentUpdate(InternalMessageDeltaObject delta, TextAnnotationUpdate annotation) diff --git a/.dotnet/src/Custom/Assistants/ToolDefinition.cs b/.dotnet/src/Custom/Assistants/ToolDefinition.cs index 92528d30b..0b876e1c1 100644 --- a/.dotnet/src/Custom/Assistants/ToolDefinition.cs +++ b/.dotnet/src/Custom/Assistants/ToolDefinition.cs @@ -14,8 +14,13 @@ public static FileSearchToolDefinition CreateFileSearch(int? maxResults = null) MaxResults = maxResults }; } - public static FunctionToolDefinition CreateFunction(string name, string description = null, BinaryData parameters = null) - => new FunctionToolDefinition(name, description, parameters); + public static FunctionToolDefinition CreateFunction(string name, string description = null, BinaryData parameters = null, bool? strictParameterSchemaEnabled = null) + => new FunctionToolDefinition(name) + { + Description = description, + Parameters = parameters, + StrictParameterSchemaEnabled = strictParameterSchemaEnabled, + }; protected ToolDefinition(string type) { diff --git a/.dotnet/src/Custom/Assistants/VectorStoreCreationHelper.cs b/.dotnet/src/Custom/Assistants/VectorStoreCreationHelper.cs index 91c231ef4..cba26fb8e 100644 --- a/.dotnet/src/Custom/Assistants/VectorStoreCreationHelper.cs +++ b/.dotnet/src/Custom/Assistants/VectorStoreCreationHelper.cs @@ -1,20 +1,23 @@ using OpenAI.Files; +using OpenAI.VectorStores; using System.Collections.Generic; using System.Linq; -namespace OpenAI.Assistants +namespace OpenAI.Assistants; + +[CodeGenModel("ToolResourcesFileSearchVectorStore")] +public partial class VectorStoreCreationHelper { - [CodeGenModel("CreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore")] - public partial class VectorStoreCreationHelper - { - public VectorStoreCreationHelper(IEnumerable fileIds, IDictionary metadata = null) - { - FileIds = fileIds.ToList(); - Metadata = metadata ?? new ChangeTrackingDictionary(); - } + [CodeGenMember("ChunkingStrategy")] + public FileChunkingStrategy ChunkingStrategy { get; set; } - public VectorStoreCreationHelper(IEnumerable files, IDictionary metadata = null) - : this(files?.Select(file => file.Id) ?? [], metadata) - {} + public VectorStoreCreationHelper(IEnumerable fileIds, IDictionary metadata = null) + { + FileIds = fileIds.ToList(); + Metadata = metadata ?? new ChangeTrackingDictionary(); } + + public VectorStoreCreationHelper(IEnumerable files, IDictionary metadata = null) + : this(files?.Select(file => file.Id) ?? [], metadata) + {} } diff --git a/.dotnet/src/Custom/Chat/AssistantChatMessage.Serialization.cs b/.dotnet/src/Custom/Chat/AssistantChatMessage.Serialization.cs index 38d9b4e4c..44749c211 100644 --- a/.dotnet/src/Custom/Chat/AssistantChatMessage.Serialization.cs +++ b/.dotnet/src/Custom/Chat/AssistantChatMessage.Serialization.cs @@ -1,5 +1,5 @@ -using System; using System.ClientModel.Primitives; +using System.Collections; using System.Collections.Generic; using System.Text.Json; @@ -17,47 +17,13 @@ internal static void SerializeAssistantChatMessage(AssistantChatMessage instance protected override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); - if (Optional.IsDefined(ParticipantName)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(ParticipantName); - } - if (Optional.IsCollectionDefined(ToolCalls)) - { - writer.WritePropertyName("tool_calls"u8); - writer.WriteStartArray(); - foreach (var item in ToolCalls) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(FunctionCall)) - { - if (FunctionCall != null) - { - writer.WritePropertyName("function_call"u8); - writer.WriteObjectValue(FunctionCall, options); - } - else - { - writer.WriteNull("function_call"); - } - } writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role); - if (Optional.IsCollectionDefined(Content)) - { - if (Content[0] != null) - { - writer.WritePropertyName("content"u8); - writer.WriteStringValue(Content[0].Text); - } - else - { - writer.WriteNull("content"); - } - } + writer.WriteStringValue(Role.ToSerialString()); + ChatMessageContentPart.WriteCoreContentPartList(Content, writer, options); + writer.WriteOptionalProperty("refusal"u8, Refusal, options); + writer.WriteOptionalProperty("name"u8, ParticipantName, options); + writer.WriteOptionalCollection("tool_calls"u8, ToolCalls, options); + writer.WriteOptionalProperty("function_call"u8, FunctionCall, options); writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); writer.WriteEndObject(); } diff --git a/.dotnet/src/Custom/Chat/AssistantChatMessage.cs b/.dotnet/src/Custom/Chat/AssistantChatMessage.cs index 0549fcd2c..46928d9a4 100644 --- a/.dotnet/src/Custom/Chat/AssistantChatMessage.cs +++ b/.dotnet/src/Custom/Chat/AssistantChatMessage.cs @@ -11,16 +11,31 @@ namespace OpenAI.Chat; [CodeGenModel("ChatCompletionRequestAssistantMessage")] public partial class AssistantChatMessage : ChatMessage { - // CUSTOM: Made internal. - /// Initializes a new instance of . - internal AssistantChatMessage() + /// + /// Creates a new instance of using a collection of content items. + /// For assistant messages, this can be one or more of type text or exactly one of type refusal. + /// + /// + /// The collection of content items associated with the message. + /// + public AssistantChatMessage(IEnumerable contentParts) + : base(ChatMessageRole.Assistant, contentParts) { + Argument.AssertNotNullOrEmpty(contentParts, nameof(contentParts)); } - // Assistant messages may present ONE OF: - // - Ordinary text content without tools or a function, in which case the content is required. - // - A list of tool calls, together with optional text content - // - A function call, together with optional text content + /// + /// Creates a new instance of using a collection of content items. + /// For assistant messages, this can be one or more of type text or exactly one of type refusal. + /// + /// + /// The collection of text and image content items associated with the message. + /// + public AssistantChatMessage(params ChatMessageContentPart[] contentParts) + : base(ChatMessageRole.Assistant, contentParts) + { + Argument.AssertNotNullOrEmpty(contentParts, nameof(contentParts)); + } /// /// Creates a new instance of that represents ordinary text content and @@ -28,12 +43,9 @@ internal AssistantChatMessage() /// /// The text content of the message. public AssistantChatMessage(string content) + : base(ChatMessageRole.Assistant, content) { Argument.AssertNotNull(content, nameof(content)); - - Role = "assistant"; - Content = [ChatMessageContentPart.CreateTextMessageContentPart(content)]; - ToolCalls = new ChangeTrackingList(); } /// @@ -43,14 +55,14 @@ public AssistantChatMessage(string content) /// The tool_calls made by the model. /// Optional text content associated with the message. public AssistantChatMessage(IEnumerable toolCalls, string content = null) + : base(ChatMessageRole.Assistant, content) { Argument.AssertNotNull(toolCalls, nameof(toolCalls)); - Role = "assistant"; - Content = (content == null) - ? new ChangeTrackingList() - : [ChatMessageContentPart.CreateTextMessageContentPart(content)]; - ToolCalls = new List(toolCalls); + foreach (ChatToolCall toolCall in toolCalls) + { + ToolCalls.Add(toolCall); + } } /// @@ -60,14 +72,10 @@ public AssistantChatMessage(IEnumerable toolCalls, string content /// The function_call made by the model. /// Optional text content associated with the message. public AssistantChatMessage(ChatFunctionCall functionCall, string content = null) + : base(ChatMessageRole.Assistant, content) { Argument.AssertNotNull(functionCall, nameof(functionCall)); - Role = "assistant"; - Content = (content == null) - ? new ChangeTrackingList() - : [ChatMessageContentPart.CreateTextMessageContentPart(content)]; - ToolCalls = new ChangeTrackingList(); FunctionCall = functionCall; } @@ -86,6 +94,7 @@ public AssistantChatMessage(ChatFunctionCall functionCall, string content = null /// The role of the provided chat completion response was not . /// public AssistantChatMessage(ChatCompletion chatCompletion) + : base(ChatMessageRole.Assistant, chatCompletion?.Content) { Argument.AssertNotNull(chatCompletion, nameof(chatCompletion)); @@ -94,10 +103,12 @@ public AssistantChatMessage(ChatCompletion chatCompletion) throw new NotSupportedException($"Cannot instantiate an {nameof(AssistantChatMessage)} from a {nameof(ChatCompletion)} with role: {chatCompletion.Role}."); } - Role = "assistant"; - Content = (IList)chatCompletion.Content; - ToolCalls = (IList)chatCompletion.ToolCalls; + Refusal = chatCompletion.Refusal; FunctionCall = chatCompletion.FunctionCall; + foreach (ChatToolCall toolCall in chatCompletion.ToolCalls ?? []) + { + ToolCalls.Add(toolCall); + } } // CUSTOM: Renamed. @@ -107,4 +118,11 @@ public AssistantChatMessage(ChatCompletion chatCompletion) /// [CodeGenMember("Name")] public string ParticipantName { get; set; } + + // CUSTOM: Common initialization for input model collection property. + [CodeGenMember("ToolCalls")] + public IList ToolCalls { get; } = new ChangeTrackingList(); + + // CUSTOM: Made internal. + internal AssistantChatMessage() { } } \ No newline at end of file diff --git a/.dotnet/src/Custom/Chat/ChatCompletion.cs b/.dotnet/src/Custom/Chat/ChatCompletion.cs index 0efd2e53f..7f0681f3f 100644 --- a/.dotnet/src/Custom/Chat/ChatCompletion.cs +++ b/.dotnet/src/Custom/Chat/ChatCompletion.cs @@ -1,4 +1,5 @@ using System; +using System.ClientModel.Primitives; using System.Collections.Generic; namespace OpenAI.Chat; @@ -7,6 +8,7 @@ namespace OpenAI.Chat; public partial class ChatCompletion { private IReadOnlyList _contentTokenLogProbabilities; + private IReadOnlyList _refusalTokenLogProbabilities; // CUSTOM: Made private. This property does not add value in the context of a strongly-typed class. /// The object type, which is always `chat.completion`. @@ -40,6 +42,11 @@ public partial class ChatCompletion ? Choices[0].Logprobs.Content : _contentTokenLogProbabilities ??= new ChangeTrackingList(); + // CUSTOM: Flattened refusal logprobs property. + public IReadOnlyList RefusalTokenLogProbabilities => (Choices[0]?.Logprobs != null) + ? Choices[0].Logprobs.Refusal + : _refusalTokenLogProbabilities ??= new ChangeTrackingList(); + // CUSTOM: Flattened choice message property. /// /// The role of the author of this message. @@ -61,9 +68,18 @@ public partial class ChatCompletion // CUSTOM: Flattened choice message property. public ChatFunctionCall FunctionCall => Choices[0].Message.FunctionCall; + // CUSTOM: Flattened choice message property. + public string Refusal => Choices[0].Message.Refusal; + /// /// Returns text representation of the first part of the first choice. /// /// - public override string ToString() => Content[0].Text; + public override string ToString() => Content.Count > 0 ? Content[0].Text + : ToolCalls.Count > 0 ? ModelReaderWriter.Write(ToolCalls[0]).ToString() + : null; + + // CUSTOM: Made internal. + [CodeGenMember("ServiceTier")] + internal InternalCreateChatCompletionResponseServiceTier? _serviceTier; } diff --git a/.dotnet/src/Custom/Chat/ChatCompletionOptions.cs b/.dotnet/src/Custom/Chat/ChatCompletionOptions.cs index e1d152936..212195db1 100644 --- a/.dotnet/src/Custom/Chat/ChatCompletionOptions.cs +++ b/.dotnet/src/Custom/Chat/ChatCompletionOptions.cs @@ -112,6 +112,23 @@ public ChatCompletionOptions() [CodeGenMember("ParallelToolCalls")] public bool? ParallelToolCallsEnabled { get; set; } + /// + /// An object specifying the format that the model must output. + /// + /// + ///

+ /// Compatible with GPT-4o, GPT-4o mini, GPT-4 Turbo and all GPT-3.5 Turbo models newer than gpt-3.5-turbo-1106. + ///

+ ///

+ /// Learn more in the Structured Outputs guide. + ///

+ ///
+ //[CodeGenMember("ResponseFormat")] + //public ChatResponseFormat ResponseFormat { get; set; } + + [CodeGenMember("ServiceTier")] + internal InternalCreateChatCompletionRequestServiceTier? _serviceTier; + // CUSTOM: Renamed. /// /// A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. diff --git a/.dotnet/src/Custom/Chat/ChatMessage.Serialization.cs b/.dotnet/src/Custom/Chat/ChatMessage.Serialization.cs index 3ad48ee5e..007212010 100644 --- a/.dotnet/src/Custom/Chat/ChatMessage.Serialization.cs +++ b/.dotnet/src/Custom/Chat/ChatMessage.Serialization.cs @@ -19,11 +19,16 @@ internal void SerializeContentValue(Utf8JsonWriter writer, ModelReaderWriterOpti internal static void DeserializeContentValue(JsonProperty property, ref IList content, ModelReaderWriterOptions options = null) { content ??= new ChangeTrackingList(); - if (property.Value.ValueKind == JsonValueKind.String) + + if (property.Value.ValueKind == JsonValueKind.Null) + { + return; + } + else if (property.Value.ValueKind == JsonValueKind.String) { content.Add(ChatMessageContentPart.CreateTextMessageContentPart(property.Value.GetString())); } - else + else if (property.Value.ValueKind == JsonValueKind.Array) { foreach (var item in property.Value.EnumerateArray()) { diff --git a/.dotnet/src/Custom/Chat/ChatMessage.cs b/.dotnet/src/Custom/Chat/ChatMessage.cs index 99fca4302..7278d5172 100644 --- a/.dotnet/src/Custom/Chat/ChatMessage.cs +++ b/.dotnet/src/Custom/Chat/ChatMessage.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; namespace OpenAI.Chat; @@ -55,40 +56,75 @@ namespace OpenAI.Chat; [CodeGenSerialization(nameof(Content), SerializationValueHook = nameof(SerializeContentValue), DeserializationValueHook = nameof(DeserializeContentValue))] public abstract partial class ChatMessage { + protected internal ChatMessage(ChatMessageRole role, IEnumerable contentParts) + { + Role = role; + foreach (ChatMessageContentPart contentPart in contentParts ?? []) + { + Content.Add(contentPart); + } + } + + protected internal ChatMessage(ChatMessageRole role, string content) + : this(role, content is null ? null : [ChatMessageContentPart.CreateTextMessageContentPart(content)]) + { } + /// /// The content associated with the message. The interpretation of this content will vary depending on the message type. /// - public IList Content { get; protected set; } + public IList Content { get; } = new ChangeTrackingList(); + + // CUSTOM: use strongly-typed role. + [CodeGenMember("Role")] + internal ChatMessageRole Role { get; set; } /// - public static SystemChatMessage CreateSystemMessage(string content) => new SystemChatMessage(content); + public static SystemChatMessage CreateSystemMessage(string content) => new(content); + + /// + public static SystemChatMessage CreateSystemMessage(IEnumerable contentParts) => new(contentParts); + + /// + public static SystemChatMessage CreateSystemMessage(params ChatMessageContentPart[] contentParts) => new(contentParts); /// - public static UserChatMessage CreateUserMessage(string content) => new UserChatMessage(content); + public static UserChatMessage CreateUserMessage(string content) => new(content); /// - public static UserChatMessage CreateUserMessage(IEnumerable contentParts) => new UserChatMessage(contentParts); + public static UserChatMessage CreateUserMessage(IEnumerable contentParts) => new(contentParts); /// - public static UserChatMessage CreateUserMessage(params ChatMessageContentPart[] contentParts) => new UserChatMessage(contentParts); + public static UserChatMessage CreateUserMessage(params ChatMessageContentPart[] contentParts) => new(contentParts); /// - public static AssistantChatMessage CreateAssistantMessage(string content) => new AssistantChatMessage(content); + public static AssistantChatMessage CreateAssistantMessage(string content) => new(content); + + /// + public static AssistantChatMessage CreateAssistantMessage(IEnumerable contentParts) => new(contentParts); + + /// + public static AssistantChatMessage CreateAssistantMessage(params ChatMessageContentPart[] contentParts) => new(contentParts); /// - public static AssistantChatMessage CreateAssistantMessage(IEnumerable toolCalls, string content = null) => new AssistantChatMessage(toolCalls, content); + public static AssistantChatMessage CreateAssistantMessage(IEnumerable toolCalls, string content = null) => new(toolCalls, content); /// - public static AssistantChatMessage CreateAssistantMessage(ChatFunctionCall functionCall, string content = null) => new AssistantChatMessage(functionCall, content); + public static AssistantChatMessage CreateAssistantMessage(ChatFunctionCall functionCall, string content = null) => new(functionCall, content); /// - public static AssistantChatMessage CreateAssistantMessage(ChatCompletion chatCompletion) => new AssistantChatMessage(chatCompletion); + public static AssistantChatMessage CreateAssistantMessage(ChatCompletion chatCompletion) => new(chatCompletion); /// - public static ToolChatMessage CreateToolChatMessage(string toolCallId, string content) => new ToolChatMessage(toolCallId, content); + public static ToolChatMessage CreateToolChatMessage(string toolCallId, string content) => new(toolCallId, content); + + /// + public static ToolChatMessage CreateToolChatMessage(string toolCallId, IEnumerable contentParts) => new(toolCallId, contentParts); + + /// + public static ToolChatMessage CreateToolChatMessage(string toolCallId, params ChatMessageContentPart[] contentParts) => new(toolCallId, contentParts); /// - public static FunctionChatMessage CreateFunctionMessage(string functionName, string content) => new FunctionChatMessage(functionName, content); + public static FunctionChatMessage CreateFunctionMessage(string functionName, string content) => new(functionName, content); /// /// Creates UserChatMessage. diff --git a/.dotnet/src/Custom/Chat/ChatMessageContentPart.Serialization.cs b/.dotnet/src/Custom/Chat/ChatMessageContentPart.Serialization.cs index 42e6ad202..42d75589c 100644 --- a/.dotnet/src/Custom/Chat/ChatMessageContentPart.Serialization.cs +++ b/.dotnet/src/Custom/Chat/ChatMessageContentPart.Serialization.cs @@ -14,18 +14,21 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReader internal static void WriteCoreContentPart(ChatMessageContentPart instance, Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(instance._kind.ToString()); if (instance._kind == ChatMessageContentPartKind.Text) { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(instance._kind.ToString()); writer.WritePropertyName("text"u8); writer.WriteStringValue(instance._text); } + else if (instance._kind == ChatMessageContentPartKind.Refusal) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(instance._refusal); + } else if (instance._kind == ChatMessageContentPartKind.Image) { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(instance._kind.ToString()); writer.WritePropertyName("image_url"u8); writer.WriteObjectValue(instance._imageUrl, options); } @@ -33,6 +36,29 @@ internal static void WriteCoreContentPart(ChatMessageContentPart instance, Utf8J writer.WriteEndObject(); } + internal static void WriteCoreContentPartList(IList instances, Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + if (!Optional.IsCollectionDefined(instances)) + { + return; + } + + writer.WritePropertyName("content"u8); + if (instances.Count == 1 && !string.IsNullOrEmpty(instances[0].Text)) + { + writer.WriteStringValue(instances[0].Text); + } + else + { + writer.WriteStartArray(); + foreach (var item in instances) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + } + internal static ChatMessageContentPart DeserializeChatMessageContentPart(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -44,6 +70,7 @@ internal static ChatMessageContentPart DeserializeChatMessageContentPart(JsonEle string kind = default; string text = default; + string refusal = default; InternalChatCompletionRequestMessageContentPartImageImageUrl imageUrl = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -64,12 +91,17 @@ internal static ChatMessageContentPart DeserializeChatMessageContentPart(JsonEle imageUrl = InternalChatCompletionRequestMessageContentPartImageImageUrl.DeserializeInternalChatCompletionRequestMessageContentPartImageImageUrl(property.Value, options); continue; } + if (property.NameEquals("refusal"u8)) + { + refusal = property.Value.GetString(); + continue; + } if (true) { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new ChatMessageContentPart(kind, text, imageUrl, serializedAdditionalRawData); + return new ChatMessageContentPart(kind, text, refusal, imageUrl, serializedAdditionalRawData); } } diff --git a/.dotnet/src/Custom/Chat/ChatMessageContentPart.cs b/.dotnet/src/Custom/Chat/ChatMessageContentPart.cs index 603008327..2267b7877 100644 --- a/.dotnet/src/Custom/Chat/ChatMessageContentPart.cs +++ b/.dotnet/src/Custom/Chat/ChatMessageContentPart.cs @@ -12,6 +12,7 @@ public partial class ChatMessageContentPart { private readonly ChatMessageContentPartKind _kind; private readonly string _text; + private readonly string _refusal; private readonly InternalChatCompletionRequestMessageContentPartImageImageUrl _imageUrl; private readonly string _dataUri; @@ -51,10 +52,11 @@ internal ChatMessageContentPart(BinaryData imageBytes, string imageBytesMediaTyp /// The text. /// The image URI. /// Keeps track of any properties unknown to the library. - internal ChatMessageContentPart(string kind, string text, InternalChatCompletionRequestMessageContentPartImageImageUrl imageUrl, IDictionary serializedAdditionalRawData) + internal ChatMessageContentPart(string kind, string text, string refusal, InternalChatCompletionRequestMessageContentPartImageImageUrl imageUrl, IDictionary serializedAdditionalRawData) { _kind = new ChatMessageContentPartKind(kind); _text = text; + _refusal = refusal; _imageUrl = imageUrl; SerializedAdditionalRawData = serializedAdditionalRawData; } @@ -69,6 +71,11 @@ internal ChatMessageContentPart(string kind, string text, InternalChatCompletion /// public string Text => _text; + /// + /// The refusal message from the assistant. + /// + public string Refusal => _refusal; + /// /// The image URI content. /// @@ -101,6 +108,23 @@ public static ChatMessageContentPart CreateTextMessageContentPart(string text) return new(text); } + /// + /// Creates a new instance of that encapsulates an assistant refusal message. + /// + /// The refusal message from the assistant. + /// A new instance of . + public static ChatMessageContentPart CreateRefusalMessageContentPart(string refusal) + { + Argument.AssertNotNull(refusal, nameof(refusal)); + + return new ChatMessageContentPart( + ChatMessageContentPartKind.Refusal.ToString(), + text: null, + refusal: refusal, + imageUrl: null, + serializedAdditionalRawData: null); + } + /// /// Creates a new instance of that encapsulates image content obtained from /// an internet location that will be accessible to the model when evaluating a message with this content. diff --git a/.dotnet/src/Custom/Chat/ChatMessageContentPartKind.cs b/.dotnet/src/Custom/Chat/ChatMessageContentPartKind.cs index ce5a097ed..73ba771ad 100644 --- a/.dotnet/src/Custom/Chat/ChatMessageContentPartKind.cs +++ b/.dotnet/src/Custom/Chat/ChatMessageContentPartKind.cs @@ -18,10 +18,13 @@ public ChatMessageContentPartKind(string value) } private const string TextValue = "text"; + private const string RefusalValue = "refusal"; private const string ImageValue = "image_url"; /// Text. public static ChatMessageContentPartKind Text { get; } = new ChatMessageContentPartKind(TextValue); + /// Refusal. + public static ChatMessageContentPartKind Refusal { get; } = new(RefusalValue); /// Image. public static ChatMessageContentPartKind Image { get; } = new ChatMessageContentPartKind(ImageValue); diff --git a/.dotnet/src/Custom/Chat/ChatResponseFormat.cs b/.dotnet/src/Custom/Chat/ChatResponseFormat.cs index 96ec8b837..2b7feb1b8 100644 --- a/.dotnet/src/Custom/Chat/ChatResponseFormat.cs +++ b/.dotnet/src/Custom/Chat/ChatResponseFormat.cs @@ -1,45 +1,82 @@ -using OpenAI.Models; +using OpenAI.Internal; +using System; +using System.ClientModel.Primitives; +using System.ComponentModel; namespace OpenAI.Chat; -/// -/// Represents a requested response_format for the model to use, enabling "JSON mode" for guaranteed valid output. -/// -/// -/// Important: when using JSON mode, the model must also be instructed to produce JSON via a -/// system or user message. -/// -/// Without this paired, message-based accompaniment, the model may generate an unending stream of whitespace until the -/// generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. -/// -/// -/// Also note that the message content may be partially cut off if finish_reason is length, which -/// indicates that the generation exceeded max_tokens or the conversation exceeded the max context length for -/// the model. -/// -/// -[CodeGenModel("CreateChatCompletionRequestResponseFormat")] -public partial class ChatResponseFormat +[CodeGenModel("ChatResponseFormat")] +public abstract partial class ChatResponseFormat : IEquatable { - // CUSTOM: Made internal. + public static ChatResponseFormat Text { get; } = new InternalChatResponseFormatText(); + public static ChatResponseFormat JsonObject { get; } = new InternalChatResponseFormatJsonObject(); - /// Must be one of `text` or `json_object`. - [CodeGenMember("Type")] - internal InternalCreateChatCompletionRequestResponseFormatType? Type { get; set; } + public static ChatResponseFormat CreateTextFormat() => new InternalChatResponseFormatText(); + public static ChatResponseFormat CreateJsonObjectFormat() => new InternalChatResponseFormatJsonObject(); + public static ChatResponseFormat CreateJsonSchemaFormat( + string name, + BinaryData jsonSchema, + string description = null, + bool? strictSchemaEnabled = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNull(jsonSchema, nameof(jsonSchema)); + + InternalResponseFormatJsonSchemaJsonSchema internalSchema = new( + description, + name, + jsonSchema, + strictSchemaEnabled, + null); + return new InternalChatResponseFormatJsonSchema(internalSchema); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public static bool operator ==(ChatResponseFormat first, ChatResponseFormat second) + { + if (first is null) + { + return second is null; + } + return first.Equals(second); + } - // CUSTOM: Made internal. - /// Initializes a new instance of . - internal ChatResponseFormat() + [EditorBrowsable(EditorBrowsableState.Never)] + public static bool operator !=(ChatResponseFormat first, ChatResponseFormat second) + => !(first == second); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) { + return (this as IEquatable).Equals(obj as ChatResponseFormat) + || ToString().Equals(obj?.ToString()); } - internal ChatResponseFormat(InternalCreateChatCompletionRequestResponseFormatType? type) + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => ToString().GetHashCode(); + + [EditorBrowsable(EditorBrowsableState.Never)] + bool IEquatable.Equals(ChatResponseFormat other) { - Type = type; + if (other is null) + { + return false; + } + + if (Object.ReferenceEquals(this, other)) + { + return true; + } + + return (this is InternalChatResponseFormatText && other is InternalChatResponseFormatText) + || (this is InternalChatResponseFormatJsonObject && other is InternalChatResponseFormatJsonObject) + || (this is InternalChatResponseFormatJsonSchema thisJsonSchema + && other is InternalChatResponseFormatJsonSchema otherJsonSchema + && thisJsonSchema.JsonSchema.Name.Equals(otherJsonSchema.JsonSchema.Name)); } - /// text. - public static ChatResponseFormat Text { get; } = new ChatResponseFormat(InternalCreateChatCompletionRequestResponseFormatType.Text); - /// json_object. - public static ChatResponseFormat JsonObject { get; } = new ChatResponseFormat(InternalCreateChatCompletionRequestResponseFormatType.JsonObject); + public override string ToString() + { + return ModelReaderWriter.Write(this).ToString(); + } } \ No newline at end of file diff --git a/.dotnet/src/Custom/Chat/ChatTool.cs b/.dotnet/src/Custom/Chat/ChatTool.cs index eab0ec3b4..f1fc403ad 100644 --- a/.dotnet/src/Custom/Chat/ChatTool.cs +++ b/.dotnet/src/Custom/Chat/ChatTool.cs @@ -68,6 +68,8 @@ internal ChatTool(InternalFunctionDefinition function) /// public BinaryData FunctionParameters => Function?.Parameters; + public bool? StrictParameterSchemaEnabled => Function?.Strict; + // CUSTOM: Added custom constructor. /// /// Creates a new instance of . @@ -75,14 +77,15 @@ internal ChatTool(InternalFunctionDefinition function) /// The name of the function. /// The description of the function. /// The parameters into the function, in JSON Schema format. - public static ChatTool CreateFunctionTool(string functionName, string functionDescription = null, BinaryData functionParameters = null) + public static ChatTool CreateFunctionTool(string functionName, string functionDescription = null, BinaryData functionParameters = null, bool? strictParameterSchemaEnabled = null) { Argument.AssertNotNull(functionName, nameof(functionName)); InternalFunctionDefinition function = new(functionName) { Description = functionDescription, - Parameters = functionParameters + Parameters = functionParameters, + Strict = strictParameterSchemaEnabled, }; return new(function); diff --git a/.dotnet/src/Custom/Chat/FunctionChatMessage.Serialization.cs b/.dotnet/src/Custom/Chat/FunctionChatMessage.Serialization.cs index cb46e2760..0bf7c4b18 100644 --- a/.dotnet/src/Custom/Chat/FunctionChatMessage.Serialization.cs +++ b/.dotnet/src/Custom/Chat/FunctionChatMessage.Serialization.cs @@ -19,68 +19,16 @@ internal static void SerializeFunctionChatMessage(FunctionChatMessage instance, protected override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToSerialString()); writer.WritePropertyName("name"u8); writer.WriteStringValue(FunctionName); - writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role); if (Optional.IsCollectionDefined(Content)) { - if (Content[0] != null) - { - writer.WritePropertyName("content"u8); - writer.WriteStringValue(Content[0].Text); - } - else - { - writer.WriteNull("content"); - } + writer.WritePropertyName("content"u8); + writer.WriteStringValue(Content?[0]?.Text); } writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); writer.WriteEndObject(); } - - internal static FunctionChatMessage DeserializeFunctionChatMessage(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - string role = default; - IList content = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("role"u8)) - { - role = property.Value.GetString(); - continue; - } - if (property.NameEquals("content"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - array.Add(ChatMessageContentPart.CreateTextMessageContentPart(property.Value.GetString())); - content = array; - continue; - } - if (true) - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new FunctionChatMessage(role, content ?? new ChangeTrackingList(), serializedAdditionalRawData, name); - } } diff --git a/.dotnet/src/Custom/Chat/FunctionChatMessage.cs b/.dotnet/src/Custom/Chat/FunctionChatMessage.cs index 7e03f2d95..10468f427 100644 --- a/.dotnet/src/Custom/Chat/FunctionChatMessage.cs +++ b/.dotnet/src/Custom/Chat/FunctionChatMessage.cs @@ -23,14 +23,11 @@ public partial class FunctionChatMessage : ChatMessage /// restriction (e.g. JSON) imposed on this content. /// public FunctionChatMessage(string functionName, string content = null) + : base(ChatMessageRole.Function, content) { Argument.AssertNotNull(functionName, nameof(functionName)); - Role = "function"; FunctionName = functionName; - Content = (content == null) - ? new ChangeTrackingList() - : [ChatMessageContentPart.CreateTextMessageContentPart(content)]; } // CUSTOM: Renamed. diff --git a/.dotnet/src/Custom/Chat/Internal/GeneratorStubs.cs b/.dotnet/src/Custom/Chat/Internal/GeneratorStubs.cs index 5288b2600..f52ceaa79 100644 --- a/.dotnet/src/Custom/Chat/Internal/GeneratorStubs.cs +++ b/.dotnet/src/Custom/Chat/Internal/GeneratorStubs.cs @@ -60,9 +60,6 @@ internal readonly partial struct InternalCreateChatCompletionFunctionResponseObj [CodeGenModel("CreateChatCompletionRequestModel")] internal readonly partial struct InternalCreateChatCompletionRequestModel { } -[CodeGenModel("CreateChatCompletionRequestResponseFormatType")] -internal readonly partial struct InternalCreateChatCompletionRequestResponseFormatType { } - [CodeGenModel("CreateChatCompletionRequestToolChoice")] internal readonly partial struct InternalCreateChatCompletionRequestToolChoice { } @@ -93,4 +90,12 @@ internal partial class InternalCreateChatCompletionStreamResponseUsage { } [CodeGenModel("FunctionParameters")] internal partial class InternalFunctionParameters { } - +[CodeGenModel("ChatResponseFormatText")] internal partial class InternalChatResponseFormatText { } +[CodeGenModel("ChatResponseFormatJsonObject")] internal partial class InternalChatResponseFormatJsonObject { } +[CodeGenModel("ChatResponseFormatJsonSchema")] internal partial class InternalChatResponseFormatJsonSchema { } +[CodeGenModel("UnknownChatResponseFormat")] internal partial class InternalUnknownChatResponseFormat { } +[CodeGenModel("ChatCompletionRequestMessageContentPartRefusal")] internal partial class InternalChatCompletionRequestMessageContentPartRefusal { } +[CodeGenModel("ChatCompletionRequestMessageContentPartRefusalType")] internal readonly partial struct InternalChatCompletionRequestMessageContentPartRefusalType { } +[CodeGenModel("CreateChatCompletionRequestServiceTier")] internal readonly partial struct InternalCreateChatCompletionRequestServiceTier { } +[CodeGenModel("CreateChatCompletionResponseServiceTier")] internal readonly partial struct InternalCreateChatCompletionResponseServiceTier { } +[CodeGenModel("CreateChatCompletionStreamResponseServiceTier")] internal readonly partial struct InternalCreateChatCompletionStreamResponseServiceTier { } diff --git a/.dotnet/src/Custom/Chat/Internal/InternalChatCompletionResponseMessage.Serialization.cs b/.dotnet/src/Custom/Chat/Internal/InternalChatCompletionResponseMessage.Serialization.cs index c8fd80d8e..4ed0cadda 100644 --- a/.dotnet/src/Custom/Chat/Internal/InternalChatCompletionResponseMessage.Serialization.cs +++ b/.dotnet/src/Custom/Chat/Internal/InternalChatCompletionResponseMessage.Serialization.cs @@ -69,6 +69,7 @@ internal static InternalChatCompletionResponseMessage DeserializeInternalChatCom return null; } IReadOnlyList content = default; + string refusal = default; IReadOnlyList toolCalls = default; ChatMessageRole role = default; ChatFunctionCall functionCall = default; @@ -87,6 +88,15 @@ internal static InternalChatCompletionResponseMessage DeserializeInternalChatCom content = array; continue; } + if (property.NameEquals("refusal"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + refusal = property.Value.GetString(); + continue; + } if (property.NameEquals("tool_calls"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -121,6 +131,6 @@ internal static InternalChatCompletionResponseMessage DeserializeInternalChatCom } } serializedAdditionalRawData = rawDataDictionary; - return new InternalChatCompletionResponseMessage(content ?? new ChangeTrackingList(), toolCalls ?? new ChangeTrackingList(), role, functionCall, serializedAdditionalRawData); + return new InternalChatCompletionResponseMessage(content ?? new ChangeTrackingList(), refusal, toolCalls ?? new ChangeTrackingList(), role, functionCall, serializedAdditionalRawData); } } diff --git a/.dotnet/src/Custom/Chat/Internal/InternalChatCompletionStreamResponseDelta.Serialization.cs b/.dotnet/src/Custom/Chat/Internal/InternalChatCompletionStreamResponseDelta.Serialization.cs index 0a4fa1ea1..0239d2571 100644 --- a/.dotnet/src/Custom/Chat/Internal/InternalChatCompletionStreamResponseDelta.Serialization.cs +++ b/.dotnet/src/Custom/Chat/Internal/InternalChatCompletionStreamResponseDelta.Serialization.cs @@ -75,6 +75,7 @@ internal static InternalChatCompletionStreamResponseDelta DeserializeInternalCha StreamingChatFunctionCallUpdate functionCall = default; IReadOnlyList toolCalls = default; ChatMessageRole? role = default; + string refusal = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -122,12 +123,21 @@ internal static InternalChatCompletionStreamResponseDelta DeserializeInternalCha role = property.Value.GetString().ToChatMessageRole(); continue; } + if (property.NameEquals("refusal"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + refusal = property.Value.GetString(); + continue; + } if (true) { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new InternalChatCompletionStreamResponseDelta(content ?? new ChangeTrackingList(), functionCall, toolCalls ?? new ChangeTrackingList(), role, serializedAdditionalRawData); + return new InternalChatCompletionStreamResponseDelta(content ?? new ChangeTrackingList(), functionCall, toolCalls ?? new ChangeTrackingList(), role, refusal, serializedAdditionalRawData); } } diff --git a/.dotnet/src/Custom/Chat/Internal/UnknownChatMessage.Serialization.cs b/.dotnet/src/Custom/Chat/Internal/UnknownChatMessage.Serialization.cs index b3eca176b..02b8d2096 100644 --- a/.dotnet/src/Custom/Chat/Internal/UnknownChatMessage.Serialization.cs +++ b/.dotnet/src/Custom/Chat/Internal/UnknownChatMessage.Serialization.cs @@ -20,17 +20,8 @@ protected override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOption { writer.WriteStartObject(); writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role); - if (Optional.IsCollectionDefined(Content)) - { - writer.WritePropertyName("content"u8); - writer.WriteStartArray(); - foreach (var item in Content) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } + writer.WriteStringValue(Role.ToSerialString()); + ChatMessageContentPart.WriteCoreContentPartList(Content, writer, options); writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); writer.WriteEndObject(); } @@ -43,7 +34,7 @@ internal static UnknownChatMessage DeserializeUnknownChatMessage(JsonElement ele { return null; } - string role = "Unknown"; + ChatMessageRole? role = null; IList content = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -51,7 +42,7 @@ internal static UnknownChatMessage DeserializeUnknownChatMessage(JsonElement ele { if (property.NameEquals("role"u8)) { - role = property.Value.GetString(); + role = property.Value.GetString().ToChatMessageRole(); continue; } if (property.NameEquals("content"u8)) @@ -74,6 +65,6 @@ internal static UnknownChatMessage DeserializeUnknownChatMessage(JsonElement ele } } serializedAdditionalRawData = rawDataDictionary; - return new UnknownChatMessage(role, content ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new UnknownChatMessage(role.Value, content ?? new ChangeTrackingList(), serializedAdditionalRawData); } } diff --git a/.dotnet/src/Custom/Chat/StreamingChatCompletionUpdate.cs b/.dotnet/src/Custom/Chat/StreamingChatCompletionUpdate.cs index 84c2f9b39..2ce62bd84 100644 --- a/.dotnet/src/Custom/Chat/StreamingChatCompletionUpdate.cs +++ b/.dotnet/src/Custom/Chat/StreamingChatCompletionUpdate.cs @@ -13,6 +13,7 @@ public partial class StreamingChatCompletionUpdate private IReadOnlyList _contentUpdate; private IReadOnlyList _toolCallUpdates; private IReadOnlyList _contentTokenLogProbabilities; + private IReadOnlyList _refusalTokenLogProbabilities; // CUSTOM: // - Made private. This property does not add value in the context of a strongly-typed class. @@ -42,6 +43,10 @@ public partial class StreamingChatCompletionUpdate [CodeGenMember("Usage")] public ChatTokenUsage Usage { get; } + // CUSTOM: Made internal. + [CodeGenMember("ServiceTier")] + internal InternalCreateChatCompletionStreamResponseServiceTier? ServiceTier { get; } + // CUSTOM: Flattened choice property. /// /// Gets the associated with this update. @@ -58,6 +63,11 @@ public partial class StreamingChatCompletionUpdate ? Choices[0].Logprobs.Content : _contentTokenLogProbabilities ??= new ChangeTrackingList(); + // CUSTOM: Flattened refusal logprobs property. + public IReadOnlyList RefusalTokenLogProbabilities => (Choices.Count > 0 && Choices[0].Logprobs != null) + ? Choices[0].Logprobs.Refusal + : _refusalTokenLogProbabilities ??= new ChangeTrackingList(); + // CUSTOM: Flattened choice delta property. /// /// Gets the content fragment associated with this update. @@ -99,6 +109,11 @@ public partial class StreamingChatCompletionUpdate public StreamingChatFunctionCallUpdate FunctionCallUpdate => (Choices.Count > 0) ? Choices[0].Delta.FunctionCall : null; + + // CUSTOM: Flattened choice delta property. + public string RefusalUpdate => (Choices.Count > 0) + ? Choices[0].Delta?.Refusal + : null; internal static List DeserializeStreamingChatCompletionUpdates(JsonElement element) { diff --git a/.dotnet/src/Custom/Chat/SystemChatMessage.Serialization.cs b/.dotnet/src/Custom/Chat/SystemChatMessage.Serialization.cs index 6e98120cb..b1063b03f 100644 --- a/.dotnet/src/Custom/Chat/SystemChatMessage.Serialization.cs +++ b/.dotnet/src/Custom/Chat/SystemChatMessage.Serialization.cs @@ -17,18 +17,10 @@ internal static void SerializeSystemChatMessage(SystemChatMessage instance, Utf8 protected override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); - if (Optional.IsDefined(ParticipantName)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(ParticipantName); - } writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role); - if (Optional.IsCollectionDefined(Content)) - { - writer.WritePropertyName("content"u8); - writer.WriteStringValue(Content[0].Text); - } + writer.WriteStringValue(Role.ToSerialString()); + ChatMessageContentPart.WriteCoreContentPartList(Content, writer, options); + writer.WriteOptionalProperty("name"u8, ParticipantName, options); writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); writer.WriteEndObject(); } diff --git a/.dotnet/src/Custom/Chat/SystemChatMessage.cs b/.dotnet/src/Custom/Chat/SystemChatMessage.cs index 21de09d3f..ed991f4d5 100644 --- a/.dotnet/src/Custom/Chat/SystemChatMessage.cs +++ b/.dotnet/src/Custom/Chat/SystemChatMessage.cs @@ -9,21 +9,40 @@ namespace OpenAI.Chat; /// restrictions for a model-based assistant. /// [CodeGenModel("ChatCompletionRequestSystemMessage")] -[CodeGenSuppress("SystemChatMessage", typeof(IEnumerable))] -// [CodeGenSuppress("SystemChatMessage", typeof(string), typeof(IList), typeof(IDictionary), typeof(string))] public partial class SystemChatMessage : ChatMessage { /// - /// Creates a new instance of . + /// Creates a new instance of using a collection of content items. + /// For system messages, these can only be of type text. /// - /// The system message text that guides the model's behavior. + /// + /// The collection of content items associated with the message. + /// + public SystemChatMessage(IEnumerable contentParts) + : base(ChatMessageRole.System, contentParts) + { } + + /// + /// Creates a new instance of using a collection of content items. + /// For system messages, these can only be of type text. + /// + /// + /// The collection of content items associated with the message. + /// + public SystemChatMessage(params ChatMessageContentPart[] contentParts) + : base(ChatMessageRole.System, contentParts) + { + Argument.AssertNotNullOrEmpty(contentParts, nameof(contentParts)); + } + + /// + /// Creates a new instance of with a single item of text content. + /// + /// The text content of the message. public SystemChatMessage(string content) + : base(ChatMessageRole.System, content) { Argument.AssertNotNull(content, nameof(content)); - - Role = "system"; - Content = new ChangeTrackingList( - (IList)[ChatMessageContentPart.CreateTextMessageContentPart(content)]); } /// diff --git a/.dotnet/src/Custom/Chat/ToolChatMessage.Serialization.cs b/.dotnet/src/Custom/Chat/ToolChatMessage.Serialization.cs index a32e807f8..9eb64d17e 100644 --- a/.dotnet/src/Custom/Chat/ToolChatMessage.Serialization.cs +++ b/.dotnet/src/Custom/Chat/ToolChatMessage.Serialization.cs @@ -1,6 +1,4 @@ -using System; using System.ClientModel.Primitives; -using System.Collections.Generic; using System.Text.Json; namespace OpenAI.Chat; @@ -17,15 +15,11 @@ internal static void SerializeToolChatMessage(ToolChatMessage instance, Utf8Json protected override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToSerialString()); writer.WritePropertyName("tool_call_id"u8); writer.WriteStringValue(ToolCallId); - writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role); - if (Optional.IsCollectionDefined(Content)) - { - writer.WritePropertyName("content"u8); - writer.WriteStringValue(Content[0].Text); - } + ChatMessageContentPart.WriteCoreContentPartList(Content, writer, options); writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); writer.WriteEndObject(); } diff --git a/.dotnet/src/Custom/Chat/ToolChatMessage.cs b/.dotnet/src/Custom/Chat/ToolChatMessage.cs index 92936ba29..c85f8efed 100644 --- a/.dotnet/src/Custom/Chat/ToolChatMessage.cs +++ b/.dotnet/src/Custom/Chat/ToolChatMessage.cs @@ -24,21 +24,56 @@ namespace OpenAI.Chat; public partial class ToolChatMessage : ChatMessage { /// - /// Creates a new instance of . + /// Creates a new instance of using a collection of content items. + /// For tool messages, these can only be of type text. /// - /// The id correlating to a made by the model. - /// - /// The textual content, produced by the defined tool in response to the correlated , - /// that resolves the tool call and allows the logical conversation to continue. No format restrictions (e.g. - /// JSON) are imposed on the content emitted by tools. + /// + /// The ID of the tool call that this message responds to. /// + /// + /// The collection of content items associated with the message. + /// + public ToolChatMessage(string toolCallId, IEnumerable contentParts) + : base(ChatMessageRole.Tool, contentParts) + { + Argument.AssertNotNullOrEmpty(toolCallId, nameof(toolCallId)); + Argument.AssertNotNullOrEmpty(contentParts, nameof(contentParts)); + + ToolCallId = toolCallId; + } + + /// + /// Creates a new instance of using a collection of content items. + /// For tool messages, these can only be of type text. + /// + /// + /// The ID of the tool call that this message responds to. + /// + /// + /// The collection of content items associated with the message. + /// + public ToolChatMessage(string toolCallId, params ChatMessageContentPart[] contentParts) + : base(ChatMessageRole.Tool, contentParts) + { + Argument.AssertNotNullOrEmpty(toolCallId, nameof(toolCallId)); + Argument.AssertNotNullOrEmpty(contentParts, nameof(contentParts)); + + ToolCallId = toolCallId; + } + + /// + /// Creates a new instance of with a single item of text content. + /// + /// + /// The ID of the tool call that this message responds to. + /// + /// The text content of the message. public ToolChatMessage(string toolCallId, string content) + : base(ChatMessageRole.Tool, content) { - Argument.AssertNotNull(toolCallId, nameof(toolCallId)); + Argument.AssertNotNullOrEmpty(toolCallId, nameof(toolCallId)); Argument.AssertNotNull(content, nameof(content)); - Role = "tool"; ToolCallId = toolCallId; - Content = [ChatMessageContentPart.CreateTextMessageContentPart(content)]; } } diff --git a/.dotnet/src/Custom/Chat/UserChatMessage.Serialization.cs b/.dotnet/src/Custom/Chat/UserChatMessage.Serialization.cs index 9dd81b1b8..fcd98a834 100644 --- a/.dotnet/src/Custom/Chat/UserChatMessage.Serialization.cs +++ b/.dotnet/src/Custom/Chat/UserChatMessage.Serialization.cs @@ -17,30 +17,10 @@ internal static void SerializeUserChatMessage(UserChatMessage instance, Utf8Json protected override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); - if (Optional.IsDefined(ParticipantName)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(ParticipantName); - } writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role); - if (Optional.IsCollectionDefined(Content)) - { - writer.WritePropertyName("content"u8); - if (Content.Count == 1 && !string.IsNullOrEmpty(Content[0].Text)) - { - writer.WriteStringValue(Content[0].Text); - } - else - { - writer.WriteStartArray(); - foreach (var item in Content) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - } + writer.WriteStringValue(Role.ToSerialString()); + ChatMessageContentPart.WriteCoreContentPartList(Content, writer, options); + writer.WriteOptionalProperty("name"u8, ParticipantName, options); writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); writer.WriteEndObject(); } diff --git a/.dotnet/src/Custom/Chat/UserChatMessage.cs b/.dotnet/src/Custom/Chat/UserChatMessage.cs index 0b2f3ef5d..18a881117 100644 --- a/.dotnet/src/Custom/Chat/UserChatMessage.cs +++ b/.dotnet/src/Custom/Chat/UserChatMessage.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; namespace OpenAI.Chat; @@ -13,48 +12,40 @@ namespace OpenAI.Chat; [CodeGenSuppress("UserChatMessage", typeof(ReadOnlyMemory))] public partial class UserChatMessage : ChatMessage { - /// - /// Creates a new instance of with ordinary text content. - /// - /// The textual content associated with the message. - public UserChatMessage(string content) - { - Argument.AssertNotNull(content, nameof(content)); - - Role = "user"; - Content = [ChatMessageContentPart.CreateTextMessageContentPart(content)]; - } - /// /// Creates a new instance of using a collection of content items that can /// include text and image information. This content format is currently only applicable to the - /// gpt-4-vision-preview model and will not be accepted by other models. + /// gpt-4o and later models and will not be accepted by older models. /// /// /// The collection of text and image content items associated with the message. /// public UserChatMessage(IEnumerable content) + : base(ChatMessageRole.User, content) { Argument.AssertNotNullOrEmpty(content, nameof(content)); - - Role = "user"; - Content = content.ToList(); } /// /// Creates a new instance of using a collection of content items that can /// include text and image information. This content format is currently only applicable to the - /// gpt-4-vision-preview model and will not be accepted by other models. + /// gpt-4o and later models and will not be accepted by older models. /// /// /// The collection of text and image content items associated with the message. /// public UserChatMessage(params ChatMessageContentPart[] content) - { - Argument.AssertNotNullOrEmpty(content, nameof(content)); + : base(ChatMessageRole.User, content) + { } - Role = "user"; - Content = content.ToList(); + /// + /// Creates a new instance of with ordinary text content. + /// + /// The textual content associated with the message. + public UserChatMessage(string content) + : base(ChatMessageRole.User, content) + { + Argument.AssertNotNull(content, nameof(content)); } // CUSTOM: Rename. diff --git a/.dotnet/src/Custom/Common/Internal/GeneratorStubs.cs b/.dotnet/src/Custom/Common/Internal/GeneratorStubs.cs new file mode 100644 index 000000000..d0c7de7f2 --- /dev/null +++ b/.dotnet/src/Custom/Common/Internal/GeneratorStubs.cs @@ -0,0 +1,11 @@ +using System; + +namespace OpenAI.Internal; + +[CodeGenModel("OmniTypedResponseFormat")] internal partial class InternalOmniTypedResponseFormat { } +[CodeGenModel("ResponseFormatJsonObject")] internal partial class InternalResponseFormatJsonObject { } +[CodeGenModel("ResponseFormatJsonSchema")] internal partial class InternalResponseFormatJsonSchema { } +[CodeGenModel("ResponseFormatJsonSchemaJsonSchema")] internal partial class InternalResponseFormatJsonSchemaJsonSchema { [CodeGenMember("Schema")] public BinaryData Schema { get; set; } } +[CodeGenModel("ResponseFormatJsonSchemaSchema")] internal partial class InternalResponseFormatJsonSchemaSchema { } +[CodeGenModel("ResponseFormatText")] internal partial class InternalResponseFormatText { } +[CodeGenModel("UnknownOmniTypedResponseFormat")] internal partial class InternalUnknownOmniTypedResponseFormat { } diff --git a/.dotnet/src/Custom/Files/FileClient.cs b/.dotnet/src/Custom/Files/FileClient.cs index c18d8c713..1905aa714 100644 --- a/.dotnet/src/Custom/Files/FileClient.cs +++ b/.dotnet/src/Custom/Files/FileClient.cs @@ -25,6 +25,8 @@ namespace OpenAI.Files; [CodeGenSuppress("DownloadFile", typeof(string))] public partial class FileClient { + private InternalUploadsClient _internalUploadsClient; + // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. @@ -66,6 +68,7 @@ protected internal FileClient(ClientPipeline pipeline, OpenAIClientOptions optio _pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); + _internalUploadsClient = new(pipeline, options); } /// Uploads a file that can be used across various operations. diff --git a/.dotnet/src/Custom/Files/Internal/GeneratorStubs.cs b/.dotnet/src/Custom/Files/Internal/GeneratorStubs.cs index 617be9be4..e21e8755d 100644 --- a/.dotnet/src/Custom/Files/Internal/GeneratorStubs.cs +++ b/.dotnet/src/Custom/Files/Internal/GeneratorStubs.cs @@ -10,4 +10,14 @@ internal readonly partial struct InternalDeleteFileResponseObject { } internal readonly partial struct InternalListFilesResponseObject { } [CodeGenModel("OpenAIFileObject")] -internal readonly partial struct InternalOpenAIFileObject { } \ No newline at end of file +internal readonly partial struct InternalOpenAIFileObject { } + +[CodeGenModel("AddUploadPartRequest")] internal partial class InternalAddUploadPartRequest { } +[CodeGenModel("CompleteUploadRequest")] internal partial class InternalCompleteUploadRequest { } +[CodeGenModel("CreateUploadRequest")] internal partial class InternalCreateUploadRequest { } +[CodeGenModel("CreateUploadRequestPurpose")] internal readonly partial struct InternalCreateUploadRequestPurpose { } +[CodeGenModel("Upload")] internal partial class InternalUpload { } +[CodeGenModel("UploadObject")] internal readonly partial struct InternalUploadObject { } +[CodeGenModel("UploadPart")] internal partial class InternalUploadPart { } +[CodeGenModel("UploadPartObject")] internal readonly partial struct InternalUploadPartObject { } +[CodeGenModel("UploadStatus")] internal readonly partial struct InternalUploadStatus { } diff --git a/.dotnet/src/Custom/Files/Internal/InternalUploadsClient.cs b/.dotnet/src/Custom/Files/Internal/InternalUploadsClient.cs new file mode 100644 index 000000000..0e9b3915b --- /dev/null +++ b/.dotnet/src/Custom/Files/Internal/InternalUploadsClient.cs @@ -0,0 +1,53 @@ +using System; +using System.ClientModel; +using System.ClientModel.Primitives; + +namespace OpenAI.Files; + +[CodeGenClient("Uploads")] +[CodeGenSuppress("InternalUploadsClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] +internal partial class InternalUploadsClient +{ + // CUSTOM: + // - Used a custom pipeline. + // - Demoted the endpoint parameter to be a property in the options class. + /// Initializes a new instance of . + /// The API key to authenticate with the service. + /// is null. + internal InternalUploadsClient(ApiKeyCredential credential) : this(credential, new OpenAIClientOptions()) + { + } + + // CUSTOM: + // - Used a custom pipeline. + // - Demoted the endpoint parameter to be a property in the options class. + /// Initializes a new instance of . + /// The API key to authenticate with the service. + /// The options to configure the client. + /// is null. + internal InternalUploadsClient(ApiKeyCredential credential, OpenAIClientOptions options) + { + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new OpenAIClientOptions(); + + _pipeline = OpenAIClient.CreatePipeline(credential, options); + _endpoint = OpenAIClient.GetEndpoint(options); + } + + // CUSTOM: + // - Used a custom pipeline. + // - Demoted the endpoint parameter to be a property in the options class. + // - Made protected. + /// Initializes a new instance of . + /// The HTTP pipeline to send and receive REST requests and responses. + /// The options to configure the client. + /// is null. + protected internal InternalUploadsClient(ClientPipeline pipeline, OpenAIClientOptions options) + { + Argument.AssertNotNull(pipeline, nameof(pipeline)); + options ??= new OpenAIClientOptions(); + + _pipeline = pipeline; + _endpoint = OpenAIClient.GetEndpoint(options); + } +} diff --git a/.dotnet/src/Custom/FineTuning/Internal/GeneratorStubs.cs b/.dotnet/src/Custom/FineTuning/Internal/GeneratorStubs.cs index cf7b626a9..833c958ff 100644 --- a/.dotnet/src/Custom/FineTuning/Internal/GeneratorStubs.cs +++ b/.dotnet/src/Custom/FineTuning/Internal/GeneratorStubs.cs @@ -87,4 +87,11 @@ internal readonly partial struct InternalListFineTuningJobEventsResponseObject { internal partial class InternalListPaginatedFineTuningJobsResponse { } [CodeGenModel("ListPaginatedFineTuningJobsResponseObject")] -internal readonly partial struct InternalListPaginatedFineTuningJobsResponseObject { } \ No newline at end of file +internal readonly partial struct InternalListPaginatedFineTuningJobsResponseObject { } + +[CodeGenModel("CreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum")] internal readonly partial struct InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum { } +[CodeGenModel("CreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum")] internal readonly partial struct InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum { } +[CodeGenModel("CreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum")] internal readonly partial struct InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum { } +[CodeGenModel("FineTuningJobHyperparametersBatchSizeChoiceEnum")] internal readonly partial struct InternalFineTuningJobHyperparametersBatchSizeChoiceEnum { } +[CodeGenModel("FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum")] internal readonly partial struct InternalFineTuningJobHyperparametersLearningRateMultiplierChoiceEnum { } +[CodeGenModel("FineTuningJobHyperparametersNEpochsChoiceEnum")] internal readonly partial struct InternalFineTuningJobHyperparametersNEpochsChoiceEnum { } diff --git a/.dotnet/src/Custom/OpenAIClient.cs b/.dotnet/src/Custom/OpenAIClient.cs index 08005f934..d01ab6174 100644 --- a/.dotnet/src/Custom/OpenAIClient.cs +++ b/.dotnet/src/Custom/OpenAIClient.cs @@ -38,6 +38,7 @@ namespace OpenAI; [CodeGenSuppress("_cachedInternalAssistantMessageClient")] [CodeGenSuppress("_cachedInternalAssistantRunClient")] [CodeGenSuppress("_cachedInternalAssistantThreadClient")] +[CodeGenSuppress("_cachedInternalUploadsClient")] [CodeGenSuppress("_cachedLegacyCompletionClient")] [CodeGenSuppress("_cachedModelClient")] [CodeGenSuppress("_cachedModerationClient")] @@ -53,6 +54,7 @@ namespace OpenAI; [CodeGenSuppress("GetInternalAssistantMessageClientClient")] [CodeGenSuppress("GetInternalAssistantRunClientClient")] [CodeGenSuppress("GetInternalAssistantThreadClientClient")] +[CodeGenSuppress("GetInternalUploadsClientClient")] [CodeGenSuppress("GetLegacyCompletionClientClient")] [CodeGenSuppress("GetModelClientClient")] [CodeGenSuppress("GetModerationClientClient")] diff --git a/.dotnet/src/Generated/InternalUploadsClient.cs b/.dotnet/src/Generated/InternalUploadsClient.cs new file mode 100644 index 000000000..4c6d033aa --- /dev/null +++ b/.dotnet/src/Generated/InternalUploadsClient.cs @@ -0,0 +1,244 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Threading.Tasks; + +namespace OpenAI.Files +{ + // Data plane generated sub-client. + internal partial class InternalUploadsClient + { + private const string AuthorizationHeader = "Authorization"; + private readonly ApiKeyCredential _keyCredential; + private const string AuthorizationApiKeyPrefix = "Bearer"; + private readonly ClientPipeline _pipeline; + private readonly Uri _endpoint; + + public virtual ClientPipeline Pipeline => _pipeline; + + protected InternalUploadsClient() + { + } + + public virtual async Task> CreateUploadAsync(InternalCreateUploadRequest requestBody) + { + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using BinaryContent content = requestBody.ToBinaryContent(); + ClientResult result = await CreateUploadAsync(content, null).ConfigureAwait(false); + return ClientResult.FromValue(InternalUpload.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + } + + public virtual ClientResult CreateUpload(InternalCreateUploadRequest requestBody) + { + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using BinaryContent content = requestBody.ToBinaryContent(); + ClientResult result = CreateUpload(content, null); + return ClientResult.FromValue(InternalUpload.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + } + + public virtual async Task CreateUploadAsync(BinaryContent content, RequestOptions options = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using PipelineMessage message = CreateCreateUploadRequest(content, options); + return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + } + + public virtual ClientResult CreateUpload(BinaryContent content, RequestOptions options = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using PipelineMessage message = CreateCreateUploadRequest(content, options); + return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + } + + public virtual async Task> AddUploadPartAsync(string uploadId, InternalAddUploadPartRequest requestBody) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using MultipartFormDataBinaryContent content = requestBody.ToMultipartBinaryBody(); + ClientResult result = await AddUploadPartAsync(uploadId, content, content.ContentType, (RequestOptions)null).ConfigureAwait(false); + return ClientResult.FromValue(InternalUploadPart.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + } + + public virtual ClientResult AddUploadPart(string uploadId, InternalAddUploadPartRequest requestBody) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using MultipartFormDataBinaryContent content = requestBody.ToMultipartBinaryBody(); + ClientResult result = AddUploadPart(uploadId, content, content.ContentType, (RequestOptions)null); + return ClientResult.FromValue(InternalUploadPart.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + } + + public virtual async Task AddUploadPartAsync(string uploadId, BinaryContent content, string contentType, RequestOptions options = null) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(content, nameof(content)); + + using PipelineMessage message = CreateAddUploadPartRequest(uploadId, content, contentType, options); + return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + } + + public virtual ClientResult AddUploadPart(string uploadId, BinaryContent content, string contentType, RequestOptions options = null) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(content, nameof(content)); + + using PipelineMessage message = CreateAddUploadPartRequest(uploadId, content, contentType, options); + return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + } + + public virtual async Task> CompleteUploadAsync(string uploadId, InternalCompleteUploadRequest requestBody) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using BinaryContent content = requestBody.ToBinaryContent(); + ClientResult result = await CompleteUploadAsync(uploadId, content, null).ConfigureAwait(false); + return ClientResult.FromValue(InternalUpload.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + } + + public virtual ClientResult CompleteUpload(string uploadId, InternalCompleteUploadRequest requestBody) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using BinaryContent content = requestBody.ToBinaryContent(); + ClientResult result = CompleteUpload(uploadId, content, null); + return ClientResult.FromValue(InternalUpload.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + } + + public virtual async Task CompleteUploadAsync(string uploadId, BinaryContent content, RequestOptions options = null) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(content, nameof(content)); + + using PipelineMessage message = CreateCompleteUploadRequest(uploadId, content, options); + return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + } + + public virtual ClientResult CompleteUpload(string uploadId, BinaryContent content, RequestOptions options = null) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(content, nameof(content)); + + using PipelineMessage message = CreateCompleteUploadRequest(uploadId, content, options); + return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + } + + public virtual async Task> CancelUploadAsync(string uploadId) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + + ClientResult result = await CancelUploadAsync(uploadId, null).ConfigureAwait(false); + return ClientResult.FromValue(InternalUpload.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + } + + public virtual ClientResult CancelUpload(string uploadId) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + + ClientResult result = CancelUpload(uploadId, null); + return ClientResult.FromValue(InternalUpload.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + } + + public virtual async Task CancelUploadAsync(string uploadId, RequestOptions options) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + + using PipelineMessage message = CreateCancelUploadRequest(uploadId, options); + return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + } + + public virtual ClientResult CancelUpload(string uploadId, RequestOptions options) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + + using PipelineMessage message = CreateCancelUploadRequest(uploadId, options); + return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + } + + internal PipelineMessage CreateCreateUploadRequest(BinaryContent content, RequestOptions options) + { + var message = _pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + var request = message.Request; + request.Method = "POST"; + var uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/uploads", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateAddUploadPartRequest(string uploadId, BinaryContent content, string contentType, RequestOptions options) + { + var message = _pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + var request = message.Request; + request.Method = "POST"; + var uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/uploads/", false); + uri.AppendPath(uploadId, true); + uri.AppendPath("/parts", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", contentType); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateCompleteUploadRequest(string uploadId, BinaryContent content, RequestOptions options) + { + var message = _pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + var request = message.Request; + request.Method = "POST"; + var uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/uploads/", false); + uri.AppendPath(uploadId, true); + uri.AppendPath("/complete", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateCancelUploadRequest(string uploadId, RequestOptions options) + { + var message = _pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + var request = message.Request; + request.Method = "POST"; + var uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/uploads/", false); + uri.AppendPath(uploadId, true); + uri.AppendPath("/cancel", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + private static PipelineMessageClassifier _pipelineMessageClassifier200; + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + } +} diff --git a/.dotnet/src/Generated/Models/AssistantChatMessage.Serialization.cs b/.dotnet/src/Generated/Models/AssistantChatMessage.Serialization.cs index 4695f5fee..89a7d76f5 100644 --- a/.dotnet/src/Generated/Models/AssistantChatMessage.Serialization.cs +++ b/.dotnet/src/Generated/Models/AssistantChatMessage.Serialization.cs @@ -32,15 +32,26 @@ internal static AssistantChatMessage DeserializeAssistantChatMessage(JsonElement { return null; } + string refusal = default; string name = default; IList toolCalls = default; ChatFunctionCall functionCall = default; - string role = "assistant"; + ChatMessageRole role = default; IList content = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { + if (property.NameEquals("refusal"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + refusal = null; + continue; + } + refusal = property.Value.GetString(); + continue; + } if (property.NameEquals("name"u8)) { name = property.Value.GetString(); @@ -72,7 +83,7 @@ internal static AssistantChatMessage DeserializeAssistantChatMessage(JsonElement } if (property.NameEquals("role"u8)) { - role = property.Value.GetString(); + role = property.Value.GetString().ToChatMessageRole(); continue; } if (property.NameEquals("content"u8)) @@ -91,6 +102,7 @@ internal static AssistantChatMessage DeserializeAssistantChatMessage(JsonElement role, content ?? new ChangeTrackingList(), serializedAdditionalRawData, + refusal, name, toolCalls ?? new ChangeTrackingList(), functionCall); diff --git a/.dotnet/src/Generated/Models/AssistantChatMessage.cs b/.dotnet/src/Generated/Models/AssistantChatMessage.cs index 38f6c207d..1d3cc6723 100644 --- a/.dotnet/src/Generated/Models/AssistantChatMessage.cs +++ b/.dotnet/src/Generated/Models/AssistantChatMessage.cs @@ -9,13 +9,15 @@ namespace OpenAI.Chat { public partial class AssistantChatMessage : ChatMessage { - internal AssistantChatMessage(string role, IList content, IDictionary serializedAdditionalRawData, string participantName, IList toolCalls, ChatFunctionCall functionCall) : base(role, content, serializedAdditionalRawData) + internal AssistantChatMessage(ChatMessageRole role, IList content, IDictionary serializedAdditionalRawData, string refusal, string participantName, IList toolCalls, ChatFunctionCall functionCall) : base(role, content, serializedAdditionalRawData) { + Refusal = refusal; ParticipantName = participantName; ToolCalls = toolCalls; FunctionCall = functionCall; } - public IList ToolCalls { get; } + + public string Refusal { get; set; } public ChatFunctionCall FunctionCall { get; set; } } } diff --git a/.dotnet/src/Generated/Models/AssistantResponseFormat.Serialization.cs b/.dotnet/src/Generated/Models/AssistantResponseFormat.Serialization.cs index eaa92389d..f2fa4d9f9 100644 --- a/.dotnet/src/Generated/Models/AssistantResponseFormat.Serialization.cs +++ b/.dotnet/src/Generated/Models/AssistantResponseFormat.Serialization.cs @@ -9,19 +9,8 @@ namespace OpenAI.Assistants { + [PersistableModelProxy(typeof(InternalUnknownAssistantResponseFormat))] public partial class AssistantResponseFormat : IJsonModel { - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static AssistantResponseFormat FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAssistantResponseFormat(document.RootElement); - } - - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/.dotnet/src/Generated/Models/AssistantResponseFormat.cs b/.dotnet/src/Generated/Models/AssistantResponseFormat.cs index da67ee999..3490f8a5a 100644 --- a/.dotnet/src/Generated/Models/AssistantResponseFormat.cs +++ b/.dotnet/src/Generated/Models/AssistantResponseFormat.cs @@ -7,11 +7,19 @@ namespace OpenAI.Assistants { - public partial class AssistantResponseFormat + public abstract partial class AssistantResponseFormat { - internal AssistantResponseFormat(IDictionary serializedAdditionalRawData) + internal IDictionary SerializedAdditionalRawData { get; set; } + protected AssistantResponseFormat() { + } + + internal AssistantResponseFormat(string type, IDictionary serializedAdditionalRawData) + { + Type = type; SerializedAdditionalRawData = serializedAdditionalRawData; } + + internal string Type { get; set; } } } diff --git a/.dotnet/src/Generated/Models/ChatCompletion.Serialization.cs b/.dotnet/src/Generated/Models/ChatCompletion.Serialization.cs index ea1696d92..87d34ee83 100644 --- a/.dotnet/src/Generated/Models/ChatCompletion.Serialization.cs +++ b/.dotnet/src/Generated/Models/ChatCompletion.Serialization.cs @@ -46,6 +46,18 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp writer.WritePropertyName("model"u8); writer.WriteStringValue(Model); } + if (SerializedAdditionalRawData?.ContainsKey("service_tier") != true && Optional.IsDefined(_serviceTier)) + { + if (_serviceTier != null) + { + writer.WritePropertyName("service_tier"u8); + writer.WriteStringValue(_serviceTier.Value.ToString()); + } + else + { + writer.WriteNull("service_tier"); + } + } if (SerializedAdditionalRawData?.ContainsKey("system_fingerprint") != true && Optional.IsDefined(SystemFingerprint)) { writer.WritePropertyName("system_fingerprint"u8); @@ -107,6 +119,7 @@ internal static ChatCompletion DeserializeChatCompletion(JsonElement element, Mo IReadOnlyList choices = default; DateTimeOffset created = default; string model = default; + InternalCreateChatCompletionResponseServiceTier? serviceTier = default; string systemFingerprint = default; InternalCreateChatCompletionResponseObject @object = default; ChatTokenUsage usage = default; @@ -139,6 +152,16 @@ internal static ChatCompletion DeserializeChatCompletion(JsonElement element, Mo model = property.Value.GetString(); continue; } + if (property.NameEquals("service_tier"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + serviceTier = null; + continue; + } + serviceTier = new InternalCreateChatCompletionResponseServiceTier(property.Value.GetString()); + continue; + } if (property.NameEquals("system_fingerprint"u8)) { systemFingerprint = property.Value.GetString(); @@ -170,6 +193,7 @@ internal static ChatCompletion DeserializeChatCompletion(JsonElement element, Mo choices, created, model, + serviceTier, systemFingerprint, @object, usage, diff --git a/.dotnet/src/Generated/Models/ChatCompletion.cs b/.dotnet/src/Generated/Models/ChatCompletion.cs index 1ad8b44e2..74549a43e 100644 --- a/.dotnet/src/Generated/Models/ChatCompletion.cs +++ b/.dotnet/src/Generated/Models/ChatCompletion.cs @@ -23,12 +23,13 @@ internal ChatCompletion(string id, IEnumerable choices, DateTimeOffset createdAt, string model, string systemFingerprint, InternalCreateChatCompletionResponseObject @object, ChatTokenUsage usage, IDictionary serializedAdditionalRawData) + internal ChatCompletion(string id, IReadOnlyList choices, DateTimeOffset createdAt, string model, InternalCreateChatCompletionResponseServiceTier? serviceTier, string systemFingerprint, InternalCreateChatCompletionResponseObject @object, ChatTokenUsage usage, IDictionary serializedAdditionalRawData) { Id = id; Choices = choices; CreatedAt = createdAt; Model = model; + _serviceTier = serviceTier; SystemFingerprint = systemFingerprint; Object = @object; Usage = usage; diff --git a/.dotnet/src/Generated/Models/ChatCompletionOptions.Serialization.cs b/.dotnet/src/Generated/Models/ChatCompletionOptions.Serialization.cs index 3a571fe7a..cae873c4a 100644 --- a/.dotnet/src/Generated/Models/ChatCompletionOptions.Serialization.cs +++ b/.dotnet/src/Generated/Models/ChatCompletionOptions.Serialization.cs @@ -137,6 +137,18 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW writer.WriteNull("seed"); } } + if (SerializedAdditionalRawData?.ContainsKey("service_tier") != true && Optional.IsDefined(_serviceTier)) + { + if (_serviceTier != null) + { + writer.WritePropertyName("service_tier"u8); + writer.WriteStringValue(_serviceTier.Value.ToString()); + } + else + { + writer.WriteNull("service_tier"); + } + } if (SerializedAdditionalRawData?.ContainsKey("stop") != true && Optional.IsCollectionDefined(StopSequences)) { if (StopSequences != null) @@ -290,6 +302,7 @@ internal static ChatCompletionOptions DeserializeChatCompletionOptions(JsonEleme float? presencePenalty = default; ChatResponseFormat responseFormat = default; long? seed = default; + InternalCreateChatCompletionRequestServiceTier? serviceTier = default; IList stop = default; bool? stream = default; InternalChatCompletionStreamOptions streamOptions = default; @@ -404,6 +417,16 @@ internal static ChatCompletionOptions DeserializeChatCompletionOptions(JsonEleme seed = property.Value.GetInt64(); continue; } + if (property.NameEquals("service_tier"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + serviceTier = null; + continue; + } + serviceTier = new InternalCreateChatCompletionRequestServiceTier(property.Value.GetString()); + continue; + } if (property.NameEquals("stop"u8)) { DeserializeStopSequencesValue(property, ref stop); @@ -528,6 +551,7 @@ internal static ChatCompletionOptions DeserializeChatCompletionOptions(JsonEleme presencePenalty, responseFormat, seed, + serviceTier, stop ?? new ChangeTrackingList(), stream, streamOptions, diff --git a/.dotnet/src/Generated/Models/ChatCompletionOptions.cs b/.dotnet/src/Generated/Models/ChatCompletionOptions.cs index 4ca6247be..040f1424c 100644 --- a/.dotnet/src/Generated/Models/ChatCompletionOptions.cs +++ b/.dotnet/src/Generated/Models/ChatCompletionOptions.cs @@ -12,7 +12,7 @@ public partial class ChatCompletionOptions { internal IDictionary SerializedAdditionalRawData { get; set; } - internal ChatCompletionOptions(IList messages, InternalCreateChatCompletionRequestModel model, float? frequencyPenalty, IDictionary logitBiases, bool? includeLogProbabilities, int? topLogProbabilityCount, int? maxTokens, int? n, float? presencePenalty, ChatResponseFormat responseFormat, long? seed, IList stopSequences, bool? stream, InternalChatCompletionStreamOptions streamOptions, float? temperature, float? topP, IList tools, ChatToolChoice toolChoice, bool? parallelToolCallsEnabled, string endUserId, ChatFunctionChoice functionChoice, IList functions, IDictionary serializedAdditionalRawData) + internal ChatCompletionOptions(IList messages, InternalCreateChatCompletionRequestModel model, float? frequencyPenalty, IDictionary logitBiases, bool? includeLogProbabilities, int? topLogProbabilityCount, int? maxTokens, int? n, float? presencePenalty, ChatResponseFormat responseFormat, long? seed, InternalCreateChatCompletionRequestServiceTier? serviceTier, IList stopSequences, bool? stream, InternalChatCompletionStreamOptions streamOptions, float? temperature, float? topP, IList tools, ChatToolChoice toolChoice, bool? parallelToolCallsEnabled, string endUserId, ChatFunctionChoice functionChoice, IList functions, IDictionary serializedAdditionalRawData) { Messages = messages; Model = model; @@ -25,6 +25,7 @@ internal ChatCompletionOptions(IList messages, InternalCreateChatCo PresencePenalty = presencePenalty; ResponseFormat = responseFormat; Seed = seed; + _serviceTier = serviceTier; StopSequences = stopSequences; Stream = stream; StreamOptions = streamOptions; diff --git a/.dotnet/src/Generated/Models/ChatMessage.cs b/.dotnet/src/Generated/Models/ChatMessage.cs index 7617e8dc4..08314591b 100644 --- a/.dotnet/src/Generated/Models/ChatMessage.cs +++ b/.dotnet/src/Generated/Models/ChatMessage.cs @@ -15,13 +15,11 @@ protected ChatMessage() Content = new ChangeTrackingList(); } - internal ChatMessage(string role, IList content, IDictionary serializedAdditionalRawData) + internal ChatMessage(ChatMessageRole role, IList content, IDictionary serializedAdditionalRawData) { Role = role; Content = content; SerializedAdditionalRawData = serializedAdditionalRawData; } - - internal string Role { get; set; } } } diff --git a/.dotnet/src/Generated/Models/ChatResponseFormat.Serialization.cs b/.dotnet/src/Generated/Models/ChatResponseFormat.Serialization.cs index a98c5ce1a..2c055865b 100644 --- a/.dotnet/src/Generated/Models/ChatResponseFormat.Serialization.cs +++ b/.dotnet/src/Generated/Models/ChatResponseFormat.Serialization.cs @@ -5,11 +5,11 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Collections.Generic; using System.Text.Json; namespace OpenAI.Chat { + [PersistableModelProxy(typeof(InternalUnknownChatResponseFormat))] public partial class ChatResponseFormat : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) @@ -21,10 +21,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true && Optional.IsDefined(Type)) + if (SerializedAdditionalRawData?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.Value.ToString()); + writer.WriteStringValue(Type); } if (SerializedAdditionalRawData != null) { @@ -68,28 +68,16 @@ internal static ChatResponseFormat DeserializeChatResponseFormat(JsonElement ele { return null; } - InternalCreateChatCompletionRequestResponseFormatType? type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + if (element.TryGetProperty("type", out JsonElement discriminator)) { - if (property.NameEquals("type"u8)) + switch (discriminator.GetString()) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new InternalCreateChatCompletionRequestResponseFormatType(property.Value.GetString()); - continue; - } - if (true) - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + case "json_object": return InternalChatResponseFormatJsonObject.DeserializeInternalChatResponseFormatJsonObject(element, options); + case "json_schema": return InternalChatResponseFormatJsonSchema.DeserializeInternalChatResponseFormatJsonSchema(element, options); + case "text": return InternalChatResponseFormatText.DeserializeInternalChatResponseFormatText(element, options); } } - serializedAdditionalRawData = rawDataDictionary; - return new ChatResponseFormat(type, serializedAdditionalRawData); + return InternalUnknownChatResponseFormat.DeserializeInternalUnknownChatResponseFormat(element, options); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/.dotnet/src/Generated/Models/ChatResponseFormat.cs b/.dotnet/src/Generated/Models/ChatResponseFormat.cs index 78f6d60f9..54eb0a8bd 100644 --- a/.dotnet/src/Generated/Models/ChatResponseFormat.cs +++ b/.dotnet/src/Generated/Models/ChatResponseFormat.cs @@ -7,14 +7,19 @@ namespace OpenAI.Chat { - public partial class ChatResponseFormat + public abstract partial class ChatResponseFormat { internal IDictionary SerializedAdditionalRawData { get; set; } + protected ChatResponseFormat() + { + } - internal ChatResponseFormat(InternalCreateChatCompletionRequestResponseFormatType? type, IDictionary serializedAdditionalRawData) + internal ChatResponseFormat(string type, IDictionary serializedAdditionalRawData) { Type = type; SerializedAdditionalRawData = serializedAdditionalRawData; } + + internal string Type { get; set; } } } diff --git a/.dotnet/src/Generated/Models/FunctionChatMessage.Serialization.cs b/.dotnet/src/Generated/Models/FunctionChatMessage.Serialization.cs index ea0a1d297..398f7d5cc 100644 --- a/.dotnet/src/Generated/Models/FunctionChatMessage.Serialization.cs +++ b/.dotnet/src/Generated/Models/FunctionChatMessage.Serialization.cs @@ -5,6 +5,7 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; +using System.Collections.Generic; using System.Text.Json; namespace OpenAI.Chat @@ -23,6 +24,46 @@ FunctionChatMessage IJsonModel.Create(ref Utf8JsonReader re return DeserializeFunctionChatMessage(document.RootElement, options); } + internal static FunctionChatMessage DeserializeFunctionChatMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + ChatMessageRole role = default; + IList content = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("role"u8)) + { + role = property.Value.GetString().ToChatMessageRole(); + continue; + } + if (property.NameEquals("content"u8)) + { + DeserializeContentValue(property, ref content); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FunctionChatMessage(role, content ?? new ChangeTrackingList(), serializedAdditionalRawData, name); + } + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; diff --git a/.dotnet/src/Generated/Models/FunctionChatMessage.cs b/.dotnet/src/Generated/Models/FunctionChatMessage.cs index 1c814213f..abcbb2170 100644 --- a/.dotnet/src/Generated/Models/FunctionChatMessage.cs +++ b/.dotnet/src/Generated/Models/FunctionChatMessage.cs @@ -10,7 +10,7 @@ namespace OpenAI.Chat [Obsolete("This field is marked as deprecated.")] public partial class FunctionChatMessage : ChatMessage { - internal FunctionChatMessage(string role, IList content, IDictionary serializedAdditionalRawData, string functionName) : base(role, content, serializedAdditionalRawData) + internal FunctionChatMessage(ChatMessageRole role, IList content, IDictionary serializedAdditionalRawData, string functionName) : base(role, content, serializedAdditionalRawData) { FunctionName = functionName; } diff --git a/.dotnet/src/Generated/Models/InternalAddUploadPartRequest.Serialization.cs b/.dotnet/src/Generated/Models/InternalAddUploadPartRequest.Serialization.cs new file mode 100644 index 000000000..f76b44afb --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalAddUploadPartRequest.Serialization.cs @@ -0,0 +1,165 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; + +namespace OpenAI.Files +{ + internal partial class InternalAddUploadPartRequest : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalAddUploadPartRequest)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("data") != true) + { + writer.WritePropertyName("data"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(global::System.BinaryData.FromStream(Data)); +#else + using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(Data))) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalAddUploadPartRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalAddUploadPartRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalAddUploadPartRequest(document.RootElement, options); + } + + internal static InternalAddUploadPartRequest DeserializeInternalAddUploadPartRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Stream data = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("data"u8)) + { + data = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalAddUploadPartRequest(data, serializedAdditionalRawData); + } + + private BinaryData SerializeMultipart(ModelReaderWriterOptions options) + { + using MultipartFormDataBinaryContent content = ToMultipartBinaryBody(); + using MemoryStream stream = new MemoryStream(); + content.WriteTo(stream); + if (stream.Position > int.MaxValue) + { + return BinaryData.FromStream(stream); + } + else + { + return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); + } + } + + internal virtual MultipartFormDataBinaryContent ToMultipartBinaryBody() + { + MultipartFormDataBinaryContent content = new MultipartFormDataBinaryContent(); + content.Add(Data, "data", "data", "application/octet-stream"); + return content; + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + case "MFD": + return SerializeMultipart(options); + default: + throw new FormatException($"The model {nameof(InternalAddUploadPartRequest)} does not support writing '{options.Format}' format."); + } + } + + InternalAddUploadPartRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalAddUploadPartRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalAddUploadPartRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + + internal static InternalAddUploadPartRequest FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalAddUploadPartRequest(document.RootElement); + } + + internal virtual BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalAddUploadPartRequest.cs b/.dotnet/src/Generated/Models/InternalAddUploadPartRequest.cs new file mode 100644 index 000000000..f6035f34b --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalAddUploadPartRequest.cs @@ -0,0 +1,33 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; + +namespace OpenAI.Files +{ + internal partial class InternalAddUploadPartRequest + { + internal IDictionary SerializedAdditionalRawData { get; set; } + public InternalAddUploadPartRequest(Stream data) + { + Argument.AssertNotNull(data, nameof(data)); + + Data = data; + } + + internal InternalAddUploadPartRequest(Stream data, IDictionary serializedAdditionalRawData) + { + Data = data; + SerializedAdditionalRawData = serializedAdditionalRawData; + } + + internal InternalAddUploadPartRequest() + { + } + + public Stream Data { get; } + } +} diff --git a/.dotnet/src/Generated/Models/InternalAssistantResponseFormatJsonObject.Serialization.cs b/.dotnet/src/Generated/Models/InternalAssistantResponseFormatJsonObject.Serialization.cs new file mode 100644 index 000000000..80afbf5f6 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalAssistantResponseFormatJsonObject.Serialization.cs @@ -0,0 +1,122 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Assistants +{ + internal partial class InternalAssistantResponseFormatJsonObject : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalAssistantResponseFormatJsonObject)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalAssistantResponseFormatJsonObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalAssistantResponseFormatJsonObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalAssistantResponseFormatJsonObject(document.RootElement, options); + } + + internal static InternalAssistantResponseFormatJsonObject DeserializeInternalAssistantResponseFormatJsonObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalAssistantResponseFormatJsonObject(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalAssistantResponseFormatJsonObject)} does not support writing '{options.Format}' format."); + } + } + + InternalAssistantResponseFormatJsonObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalAssistantResponseFormatJsonObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalAssistantResponseFormatJsonObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/.dotnet/src/Generated/Models/InternalAssistantResponseFormatJsonObject.cs b/.dotnet/src/Generated/Models/InternalAssistantResponseFormatJsonObject.cs new file mode 100644 index 000000000..b6caf3d33 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalAssistantResponseFormatJsonObject.cs @@ -0,0 +1,21 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Assistants +{ + internal partial class InternalAssistantResponseFormatJsonObject : AssistantResponseFormat + { + internal InternalAssistantResponseFormatJsonObject() + { + Type = "json_object"; + } + + internal InternalAssistantResponseFormatJsonObject(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.Serialization.cs b/.dotnet/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.Serialization.cs new file mode 100644 index 000000000..24865dbf9 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.Serialization.cs @@ -0,0 +1,134 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using OpenAI.Internal; + +namespace OpenAI.Assistants +{ + internal partial class InternalAssistantResponseFormatJsonSchema : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalAssistantResponseFormatJsonSchema)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("json_schema") != true) + { + writer.WritePropertyName("json_schema"u8); + writer.WriteObjectValue(JsonSchema, options); + } + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalAssistantResponseFormatJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalAssistantResponseFormatJsonSchema)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalAssistantResponseFormatJsonSchema(document.RootElement, options); + } + + internal static InternalAssistantResponseFormatJsonSchema DeserializeInternalAssistantResponseFormatJsonSchema(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + InternalResponseFormatJsonSchemaJsonSchema jsonSchema = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("json_schema"u8)) + { + jsonSchema = InternalResponseFormatJsonSchemaJsonSchema.DeserializeInternalResponseFormatJsonSchemaJsonSchema(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalAssistantResponseFormatJsonSchema(type, serializedAdditionalRawData, jsonSchema); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalAssistantResponseFormatJsonSchema)} does not support writing '{options.Format}' format."); + } + } + + InternalAssistantResponseFormatJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalAssistantResponseFormatJsonSchema(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalAssistantResponseFormatJsonSchema)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/.dotnet/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.cs b/.dotnet/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.cs new file mode 100644 index 000000000..d2b71a861 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.cs @@ -0,0 +1,32 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; +using OpenAI.Internal; + +namespace OpenAI.Assistants +{ + internal partial class InternalAssistantResponseFormatJsonSchema : AssistantResponseFormat + { + internal InternalAssistantResponseFormatJsonSchema(InternalResponseFormatJsonSchemaJsonSchema jsonSchema) + { + Argument.AssertNotNull(jsonSchema, nameof(jsonSchema)); + + Type = "json_schema"; + JsonSchema = jsonSchema; + } + + internal InternalAssistantResponseFormatJsonSchema(string type, IDictionary serializedAdditionalRawData, InternalResponseFormatJsonSchemaJsonSchema jsonSchema) : base(type, serializedAdditionalRawData) + { + JsonSchema = jsonSchema; + } + + internal InternalAssistantResponseFormatJsonSchema() + { + } + + public InternalResponseFormatJsonSchemaJsonSchema JsonSchema { get; } + } +} diff --git a/.dotnet/src/Generated/Models/InternalAssistantsApiResponseFormat.Serialization.cs b/.dotnet/src/Generated/Models/InternalAssistantResponseFormatText.Serialization.cs similarity index 60% rename from .dotnet/src/Generated/Models/InternalAssistantsApiResponseFormat.Serialization.cs rename to .dotnet/src/Generated/Models/InternalAssistantResponseFormatText.Serialization.cs index f1c047365..a2ae06eea 100644 --- a/.dotnet/src/Generated/Models/InternalAssistantsApiResponseFormat.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalAssistantResponseFormatText.Serialization.cs @@ -10,21 +10,21 @@ namespace OpenAI.Assistants { - internal partial class InternalAssistantsApiResponseFormat : IJsonModel + internal partial class InternalAssistantResponseFormatText : IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalAssistantsApiResponseFormat)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(InternalAssistantResponseFormatText)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true && Optional.IsDefined(Type)) + if (SerializedAdditionalRawData?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.Value.ToString()); + writer.WriteStringValue(Type); } if (SerializedAdditionalRawData != null) { @@ -48,19 +48,19 @@ void IJsonModel.Write(Utf8JsonWriter writer writer.WriteEndObject(); } - InternalAssistantsApiResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalAssistantResponseFormatText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalAssistantsApiResponseFormat)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalAssistantResponseFormatText)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAssistantsApiResponseFormat(document.RootElement, options); + return DeserializeInternalAssistantResponseFormatText(document.RootElement, options); } - internal static InternalAssistantsApiResponseFormat DeserializeInternalAssistantsApiResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalAssistantResponseFormatText DeserializeInternalAssistantResponseFormatText(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -68,18 +68,14 @@ internal static InternalAssistantsApiResponseFormat DeserializeInternalAssistant { return null; } - InternalAssistantsApiResponseFormatType? type = default; + string type = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("type"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new InternalAssistantsApiResponseFormatType(property.Value.GetString()); + type = property.Value.GetString(); continue; } if (true) @@ -89,49 +85,38 @@ internal static InternalAssistantsApiResponseFormat DeserializeInternalAssistant } } serializedAdditionalRawData = rawDataDictionary; - return new InternalAssistantsApiResponseFormat(type, serializedAdditionalRawData); + return new InternalAssistantResponseFormatText(type, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(InternalAssistantsApiResponseFormat)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(InternalAssistantResponseFormatText)} does not support writing '{options.Format}' format."); } } - InternalAssistantsApiResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + InternalAssistantResponseFormatText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data); - return DeserializeInternalAssistantsApiResponseFormat(document.RootElement, options); + return DeserializeInternalAssistantResponseFormatText(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalAssistantsApiResponseFormat)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(InternalAssistantResponseFormatText)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static InternalAssistantsApiResponseFormat FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAssistantsApiResponseFormat(document.RootElement); - } - - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; } } diff --git a/.dotnet/src/Generated/Models/InternalAssistantResponseFormatText.cs b/.dotnet/src/Generated/Models/InternalAssistantResponseFormatText.cs new file mode 100644 index 000000000..899b65998 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalAssistantResponseFormatText.cs @@ -0,0 +1,21 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Assistants +{ + internal partial class InternalAssistantResponseFormatText : AssistantResponseFormat + { + internal InternalAssistantResponseFormatText() + { + Type = "text"; + } + + internal InternalAssistantResponseFormatText(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalAssistantsApiResponseFormat.cs b/.dotnet/src/Generated/Models/InternalAssistantsApiResponseFormat.cs deleted file mode 100644 index 9333fb55c..000000000 --- a/.dotnet/src/Generated/Models/InternalAssistantsApiResponseFormat.cs +++ /dev/null @@ -1,25 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace OpenAI.Assistants -{ - internal partial class InternalAssistantsApiResponseFormat - { - internal IDictionary SerializedAdditionalRawData { get; set; } - public InternalAssistantsApiResponseFormat() - { - } - - internal InternalAssistantsApiResponseFormat(InternalAssistantsApiResponseFormatType? type, IDictionary serializedAdditionalRawData) - { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - public InternalAssistantsApiResponseFormatType? Type { get; set; } - } -} diff --git a/.dotnet/src/Generated/Models/InternalAssistantsApiResponseFormatType.cs b/.dotnet/src/Generated/Models/InternalAssistantsApiResponseFormatType.cs deleted file mode 100644 index 60e13d230..000000000 --- a/.dotnet/src/Generated/Models/InternalAssistantsApiResponseFormatType.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace OpenAI.Assistants -{ - internal readonly partial struct InternalAssistantsApiResponseFormatType : IEquatable - { - private readonly string _value; - - public InternalAssistantsApiResponseFormatType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string TextValue = "text"; - private const string JsonObjectValue = "json_object"; - - public static InternalAssistantsApiResponseFormatType Text { get; } = new InternalAssistantsApiResponseFormatType(TextValue); - public static InternalAssistantsApiResponseFormatType JsonObject { get; } = new InternalAssistantsApiResponseFormatType(JsonObjectValue); - public static bool operator ==(InternalAssistantsApiResponseFormatType left, InternalAssistantsApiResponseFormatType right) => left.Equals(right); - public static bool operator !=(InternalAssistantsApiResponseFormatType left, InternalAssistantsApiResponseFormatType right) => !left.Equals(right); - public static implicit operator InternalAssistantsApiResponseFormatType(string value) => new InternalAssistantsApiResponseFormatType(value); - - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is InternalAssistantsApiResponseFormatType other && Equals(other); - public bool Equals(InternalAssistantsApiResponseFormatType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - public override string ToString() => _value; - } -} diff --git a/.dotnet/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.Serialization.cs b/.dotnet/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.Serialization.cs new file mode 100644 index 000000000..093b83c78 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.Serialization.cs @@ -0,0 +1,144 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Chat +{ + internal partial class InternalChatCompletionRequestMessageContentPartRefusal : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalChatCompletionRequestMessageContentPartRefusal)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + } + if (SerializedAdditionalRawData?.ContainsKey("refusal") != true) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(Refusal); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalChatCompletionRequestMessageContentPartRefusal IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalChatCompletionRequestMessageContentPartRefusal)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalChatCompletionRequestMessageContentPartRefusal(document.RootElement, options); + } + + internal static InternalChatCompletionRequestMessageContentPartRefusal DeserializeInternalChatCompletionRequestMessageContentPartRefusal(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + InternalChatCompletionRequestMessageContentPartRefusalType type = default; + string refusal = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new InternalChatCompletionRequestMessageContentPartRefusalType(property.Value.GetString()); + continue; + } + if (property.NameEquals("refusal"u8)) + { + refusal = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalChatCompletionRequestMessageContentPartRefusal(type, refusal, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalChatCompletionRequestMessageContentPartRefusal)} does not support writing '{options.Format}' format."); + } + } + + InternalChatCompletionRequestMessageContentPartRefusal IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalChatCompletionRequestMessageContentPartRefusal(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalChatCompletionRequestMessageContentPartRefusal)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static InternalChatCompletionRequestMessageContentPartRefusal FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionRequestMessageContentPartRefusal(document.RootElement); + } + + internal virtual BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.cs b/.dotnet/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.cs new file mode 100644 index 000000000..ea0eaa097 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.cs @@ -0,0 +1,35 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Chat +{ + internal partial class InternalChatCompletionRequestMessageContentPartRefusal + { + internal IDictionary SerializedAdditionalRawData { get; set; } + public InternalChatCompletionRequestMessageContentPartRefusal(string refusal) + { + Argument.AssertNotNull(refusal, nameof(refusal)); + + Refusal = refusal; + } + + internal InternalChatCompletionRequestMessageContentPartRefusal(InternalChatCompletionRequestMessageContentPartRefusalType type, string refusal, IDictionary serializedAdditionalRawData) + { + Type = type; + Refusal = refusal; + SerializedAdditionalRawData = serializedAdditionalRawData; + } + + internal InternalChatCompletionRequestMessageContentPartRefusal() + { + } + + public InternalChatCompletionRequestMessageContentPartRefusalType Type { get; } = InternalChatCompletionRequestMessageContentPartRefusalType.Refusal; + + public string Refusal { get; } + } +} diff --git a/.dotnet/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusalType.cs b/.dotnet/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusalType.cs new file mode 100644 index 000000000..d1c3e8498 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusalType.cs @@ -0,0 +1,34 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace OpenAI.Chat +{ + internal readonly partial struct InternalChatCompletionRequestMessageContentPartRefusalType : IEquatable + { + private readonly string _value; + + public InternalChatCompletionRequestMessageContentPartRefusalType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string RefusalValue = "refusal"; + + public static InternalChatCompletionRequestMessageContentPartRefusalType Refusal { get; } = new InternalChatCompletionRequestMessageContentPartRefusalType(RefusalValue); + public static bool operator ==(InternalChatCompletionRequestMessageContentPartRefusalType left, InternalChatCompletionRequestMessageContentPartRefusalType right) => left.Equals(right); + public static bool operator !=(InternalChatCompletionRequestMessageContentPartRefusalType left, InternalChatCompletionRequestMessageContentPartRefusalType right) => !left.Equals(right); + public static implicit operator InternalChatCompletionRequestMessageContentPartRefusalType(string value) => new InternalChatCompletionRequestMessageContentPartRefusalType(value); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InternalChatCompletionRequestMessageContentPartRefusalType other && Equals(other); + public bool Equals(InternalChatCompletionRequestMessageContentPartRefusalType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; + } +} diff --git a/.dotnet/src/Generated/Models/InternalChatCompletionResponseMessage.cs b/.dotnet/src/Generated/Models/InternalChatCompletionResponseMessage.cs index 114a9ae55..f29262217 100644 --- a/.dotnet/src/Generated/Models/InternalChatCompletionResponseMessage.cs +++ b/.dotnet/src/Generated/Models/InternalChatCompletionResponseMessage.cs @@ -11,10 +11,17 @@ namespace OpenAI.Chat internal partial class InternalChatCompletionResponseMessage { internal IDictionary SerializedAdditionalRawData { get; set; } + internal InternalChatCompletionResponseMessage(IEnumerable content, string refusal) + { + Content = content?.ToList(); + Refusal = refusal; + ToolCalls = new ChangeTrackingList(); + } - internal InternalChatCompletionResponseMessage(IReadOnlyList content, IReadOnlyList toolCalls, ChatMessageRole role, ChatFunctionCall functionCall, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionResponseMessage(IReadOnlyList content, string refusal, IReadOnlyList toolCalls, ChatMessageRole role, ChatFunctionCall functionCall, IDictionary serializedAdditionalRawData) { Content = content; + Refusal = refusal; ToolCalls = toolCalls; Role = role; FunctionCall = functionCall; @@ -24,6 +31,7 @@ internal InternalChatCompletionResponseMessage(IReadOnlyList ToolCalls { get; } } } diff --git a/.dotnet/src/Generated/Models/InternalChatCompletionStreamResponseDelta.cs b/.dotnet/src/Generated/Models/InternalChatCompletionStreamResponseDelta.cs index 34085b941..9bdd14f0a 100644 --- a/.dotnet/src/Generated/Models/InternalChatCompletionStreamResponseDelta.cs +++ b/.dotnet/src/Generated/Models/InternalChatCompletionStreamResponseDelta.cs @@ -11,15 +11,17 @@ internal partial class InternalChatCompletionStreamResponseDelta { internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalChatCompletionStreamResponseDelta(IReadOnlyList content, StreamingChatFunctionCallUpdate functionCall, IReadOnlyList toolCalls, ChatMessageRole? role, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionStreamResponseDelta(IReadOnlyList content, StreamingChatFunctionCallUpdate functionCall, IReadOnlyList toolCalls, ChatMessageRole? role, string refusal, IDictionary serializedAdditionalRawData) { Content = content; FunctionCall = functionCall; ToolCalls = toolCalls; Role = role; + Refusal = refusal; SerializedAdditionalRawData = serializedAdditionalRawData; } public StreamingChatFunctionCallUpdate FunctionCall { get; } public IReadOnlyList ToolCalls { get; } + public string Refusal { get; } } } diff --git a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchBase.Serialization.cs b/.dotnet/src/Generated/Models/InternalChatResponseFormatJsonObject.Serialization.cs similarity index 52% rename from .dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchBase.Serialization.cs rename to .dotnet/src/Generated/Models/InternalChatResponseFormatJsonObject.Serialization.cs index 40957b72a..9c63f887b 100644 --- a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchBase.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalChatResponseFormatJsonObject.Serialization.cs @@ -8,19 +8,24 @@ using System.Collections.Generic; using System.Text.Json; -namespace OpenAI.Assistants +namespace OpenAI.Chat { - internal partial class InternalCreateAssistantRequestToolResourcesFileSearchBase : IJsonModel + internal partial class InternalChatResponseFormatJsonObject : IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResourcesFileSearchBase)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(InternalChatResponseFormatJsonObject)} does not support writing '{format}' format."); } writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } if (SerializedAdditionalRawData != null) { foreach (var item in SerializedAdditionalRawData) @@ -43,19 +48,19 @@ void IJsonModel.Write writer.WriteEndObject(); } - InternalCreateAssistantRequestToolResourcesFileSearchBase IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatResponseFormatJsonObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResourcesFileSearchBase)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalChatResponseFormatJsonObject)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalCreateAssistantRequestToolResourcesFileSearchBase(document.RootElement, options); + return DeserializeInternalChatResponseFormatJsonObject(document.RootElement, options); } - internal static InternalCreateAssistantRequestToolResourcesFileSearchBase DeserializeInternalCreateAssistantRequestToolResourcesFileSearchBase(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatResponseFormatJsonObject DeserializeInternalChatResponseFormatJsonObject(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -63,10 +68,16 @@ internal static InternalCreateAssistantRequestToolResourcesFileSearchBase Deseri { return null; } + string type = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } if (true) { rawDataDictionary ??= new Dictionary(); @@ -74,47 +85,47 @@ internal static InternalCreateAssistantRequestToolResourcesFileSearchBase Deseri } } serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateAssistantRequestToolResourcesFileSearchBase(serializedAdditionalRawData); + return new InternalChatResponseFormatJsonObject(type, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResourcesFileSearchBase)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(InternalChatResponseFormatJsonObject)} does not support writing '{options.Format}' format."); } } - InternalCreateAssistantRequestToolResourcesFileSearchBase IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + InternalChatResponseFormatJsonObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data); - return DeserializeInternalCreateAssistantRequestToolResourcesFileSearchBase(document.RootElement, options); + return DeserializeInternalChatResponseFormatJsonObject(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResourcesFileSearchBase)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(InternalChatResponseFormatJsonObject)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateAssistantRequestToolResourcesFileSearchBase FromResponse(PipelineResponse response) + internal static new InternalChatResponseFormatJsonObject FromResponse(PipelineResponse response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateAssistantRequestToolResourcesFileSearchBase(document.RootElement); + return DeserializeInternalChatResponseFormatJsonObject(document.RootElement); } - internal virtual BinaryContent ToBinaryContent() + internal override BinaryContent ToBinaryContent() { return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); } diff --git a/.dotnet/src/Generated/Models/InternalChatResponseFormatJsonObject.cs b/.dotnet/src/Generated/Models/InternalChatResponseFormatJsonObject.cs new file mode 100644 index 000000000..a3d489404 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalChatResponseFormatJsonObject.cs @@ -0,0 +1,21 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Chat +{ + internal partial class InternalChatResponseFormatJsonObject : ChatResponseFormat + { + public InternalChatResponseFormatJsonObject() + { + Type = "json_object"; + } + + internal InternalChatResponseFormatJsonObject(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalChatResponseFormatJsonSchema.Serialization.cs b/.dotnet/src/Generated/Models/InternalChatResponseFormatJsonSchema.Serialization.cs new file mode 100644 index 000000000..c5c0cca64 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalChatResponseFormatJsonSchema.Serialization.cs @@ -0,0 +1,145 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using OpenAI.Internal; + +namespace OpenAI.Chat +{ + internal partial class InternalChatResponseFormatJsonSchema : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalChatResponseFormatJsonSchema)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("json_schema") != true) + { + writer.WritePropertyName("json_schema"u8); + writer.WriteObjectValue(JsonSchema, options); + } + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalChatResponseFormatJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalChatResponseFormatJsonSchema)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalChatResponseFormatJsonSchema(document.RootElement, options); + } + + internal static InternalChatResponseFormatJsonSchema DeserializeInternalChatResponseFormatJsonSchema(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + InternalResponseFormatJsonSchemaJsonSchema jsonSchema = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("json_schema"u8)) + { + jsonSchema = InternalResponseFormatJsonSchemaJsonSchema.DeserializeInternalResponseFormatJsonSchemaJsonSchema(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalChatResponseFormatJsonSchema(type, serializedAdditionalRawData, jsonSchema); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalChatResponseFormatJsonSchema)} does not support writing '{options.Format}' format."); + } + } + + InternalChatResponseFormatJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalChatResponseFormatJsonSchema(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalChatResponseFormatJsonSchema)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static new InternalChatResponseFormatJsonSchema FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatResponseFormatJsonSchema(document.RootElement); + } + + internal override BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalChatResponseFormatJsonSchema.cs b/.dotnet/src/Generated/Models/InternalChatResponseFormatJsonSchema.cs new file mode 100644 index 000000000..d519acb14 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalChatResponseFormatJsonSchema.cs @@ -0,0 +1,32 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; +using OpenAI.Internal; + +namespace OpenAI.Chat +{ + internal partial class InternalChatResponseFormatJsonSchema : ChatResponseFormat + { + public InternalChatResponseFormatJsonSchema(InternalResponseFormatJsonSchemaJsonSchema jsonSchema) + { + Argument.AssertNotNull(jsonSchema, nameof(jsonSchema)); + + Type = "json_schema"; + JsonSchema = jsonSchema; + } + + internal InternalChatResponseFormatJsonSchema(string type, IDictionary serializedAdditionalRawData, InternalResponseFormatJsonSchemaJsonSchema jsonSchema) : base(type, serializedAdditionalRawData) + { + JsonSchema = jsonSchema; + } + + internal InternalChatResponseFormatJsonSchema() + { + } + + public InternalResponseFormatJsonSchemaJsonSchema JsonSchema { get; } + } +} diff --git a/.dotnet/src/Generated/Models/InternalChatResponseFormatText.Serialization.cs b/.dotnet/src/Generated/Models/InternalChatResponseFormatText.Serialization.cs new file mode 100644 index 000000000..c0f373c9d --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalChatResponseFormatText.Serialization.cs @@ -0,0 +1,133 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Chat +{ + internal partial class InternalChatResponseFormatText : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalChatResponseFormatText)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalChatResponseFormatText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalChatResponseFormatText)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalChatResponseFormatText(document.RootElement, options); + } + + internal static InternalChatResponseFormatText DeserializeInternalChatResponseFormatText(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalChatResponseFormatText(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalChatResponseFormatText)} does not support writing '{options.Format}' format."); + } + } + + InternalChatResponseFormatText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalChatResponseFormatText(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalChatResponseFormatText)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static new InternalChatResponseFormatText FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatResponseFormatText(document.RootElement); + } + + internal override BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalChatResponseFormatText.cs b/.dotnet/src/Generated/Models/InternalChatResponseFormatText.cs new file mode 100644 index 000000000..49e7771f0 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalChatResponseFormatText.cs @@ -0,0 +1,21 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Chat +{ + internal partial class InternalChatResponseFormatText : ChatResponseFormat + { + public InternalChatResponseFormatText() + { + Type = "text"; + } + + internal InternalChatResponseFormatText(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResourcesFileSearch.Serialization.cs b/.dotnet/src/Generated/Models/InternalCompleteUploadRequest.Serialization.cs similarity index 53% rename from .dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResourcesFileSearch.Serialization.cs rename to .dotnet/src/Generated/Models/InternalCompleteUploadRequest.Serialization.cs index d8f1c1e75..30ee85a04 100644 --- a/.dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResourcesFileSearch.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalCompleteUploadRequest.Serialization.cs @@ -8,29 +8,34 @@ using System.Collections.Generic; using System.Text.Json; -namespace OpenAI.Assistants +namespace OpenAI.Files { - internal partial class InternalModifyAssistantRequestToolResourcesFileSearch : IJsonModel + internal partial class InternalCompleteUploadRequest : IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalModifyAssistantRequestToolResourcesFileSearch)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(InternalCompleteUploadRequest)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("vector_store_ids") != true && Optional.IsCollectionDefined(VectorStoreIds)) + if (SerializedAdditionalRawData?.ContainsKey("part_ids") != true) { - writer.WritePropertyName("vector_store_ids"u8); + writer.WritePropertyName("part_ids"u8); writer.WriteStartArray(); - foreach (var item in VectorStoreIds) + foreach (var item in PartIds) { writer.WriteStringValue(item); } writer.WriteEndArray(); } + if (SerializedAdditionalRawData?.ContainsKey("md5") != true && Optional.IsDefined(Md5)) + { + writer.WritePropertyName("md5"u8); + writer.WriteStringValue(Md5); + } if (SerializedAdditionalRawData != null) { foreach (var item in SerializedAdditionalRawData) @@ -53,19 +58,19 @@ void IJsonModel.Write(Utf writer.WriteEndObject(); } - InternalModifyAssistantRequestToolResourcesFileSearch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCompleteUploadRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalModifyAssistantRequestToolResourcesFileSearch)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalCompleteUploadRequest)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalModifyAssistantRequestToolResourcesFileSearch(document.RootElement, options); + return DeserializeInternalCompleteUploadRequest(document.RootElement, options); } - internal static InternalModifyAssistantRequestToolResourcesFileSearch DeserializeInternalModifyAssistantRequestToolResourcesFileSearch(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCompleteUploadRequest DeserializeInternalCompleteUploadRequest(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -73,23 +78,25 @@ internal static InternalModifyAssistantRequestToolResourcesFileSearch Deserializ { return null; } - IList vectorStoreIds = default; + IList partIds = default; + string md5 = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("vector_store_ids"u8)) + if (property.NameEquals("part_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } List array = new List(); foreach (var item in property.Value.EnumerateArray()) { array.Add(item.GetString()); } - vectorStoreIds = array; + partIds = array; + continue; + } + if (property.NameEquals("md5"u8)) + { + md5 = property.Value.GetString(); continue; } if (true) @@ -99,44 +106,44 @@ internal static InternalModifyAssistantRequestToolResourcesFileSearch Deserializ } } serializedAdditionalRawData = rawDataDictionary; - return new InternalModifyAssistantRequestToolResourcesFileSearch(vectorStoreIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalCompleteUploadRequest(partIds, md5, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(InternalModifyAssistantRequestToolResourcesFileSearch)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(InternalCompleteUploadRequest)} does not support writing '{options.Format}' format."); } } - InternalModifyAssistantRequestToolResourcesFileSearch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + InternalCompleteUploadRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data); - return DeserializeInternalModifyAssistantRequestToolResourcesFileSearch(document.RootElement, options); + return DeserializeInternalCompleteUploadRequest(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalModifyAssistantRequestToolResourcesFileSearch)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(InternalCompleteUploadRequest)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalModifyAssistantRequestToolResourcesFileSearch FromResponse(PipelineResponse response) + internal static InternalCompleteUploadRequest FromResponse(PipelineResponse response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalModifyAssistantRequestToolResourcesFileSearch(document.RootElement); + return DeserializeInternalCompleteUploadRequest(document.RootElement); } internal virtual BinaryContent ToBinaryContent() diff --git a/.dotnet/src/Generated/Models/InternalCompleteUploadRequest.cs b/.dotnet/src/Generated/Models/InternalCompleteUploadRequest.cs new file mode 100644 index 000000000..74d4d5346 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalCompleteUploadRequest.cs @@ -0,0 +1,35 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace OpenAI.Files +{ + internal partial class InternalCompleteUploadRequest + { + internal IDictionary SerializedAdditionalRawData { get; set; } + public InternalCompleteUploadRequest(IEnumerable partIds) + { + Argument.AssertNotNull(partIds, nameof(partIds)); + + PartIds = partIds.ToList(); + } + + internal InternalCompleteUploadRequest(IList partIds, string md5, IDictionary serializedAdditionalRawData) + { + PartIds = partIds; + Md5 = md5; + SerializedAdditionalRawData = serializedAdditionalRawData; + } + + internal InternalCompleteUploadRequest() + { + } + + public IList PartIds { get; } + public string Md5 { get; set; } + } +} diff --git a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestModel.cs b/.dotnet/src/Generated/Models/InternalCreateAssistantRequestModel.cs index dbe430270..dff777d4f 100644 --- a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestModel.cs +++ b/.dotnet/src/Generated/Models/InternalCreateAssistantRequestModel.cs @@ -17,7 +17,10 @@ public InternalCreateAssistantRequestModel(string value) } private const string Gpt4oValue = "gpt-4o"; + private const string Gpt4o20240806Value = "gpt-4o-2024-08-06"; private const string Gpt4o20240513Value = "gpt-4o-2024-05-13"; + private const string Gpt4oMiniValue = "gpt-4o-mini"; + private const string Gpt4oMini20240718Value = "gpt-4o-mini-2024-07-18"; private const string Gpt4TurboValue = "gpt-4-turbo"; private const string Gpt4Turbo20240409Value = "gpt-4-turbo-2024-04-09"; private const string Gpt40125PreviewValue = "gpt-4-0125-preview"; @@ -38,7 +41,10 @@ public InternalCreateAssistantRequestModel(string value) private const string Gpt35Turbo16k0613Value = "gpt-3.5-turbo-16k-0613"; public static InternalCreateAssistantRequestModel Gpt4o { get; } = new InternalCreateAssistantRequestModel(Gpt4oValue); + public static InternalCreateAssistantRequestModel Gpt4o20240806 { get; } = new InternalCreateAssistantRequestModel(Gpt4o20240806Value); public static InternalCreateAssistantRequestModel Gpt4o20240513 { get; } = new InternalCreateAssistantRequestModel(Gpt4o20240513Value); + public static InternalCreateAssistantRequestModel Gpt4oMini { get; } = new InternalCreateAssistantRequestModel(Gpt4oMiniValue); + public static InternalCreateAssistantRequestModel Gpt4oMini20240718 { get; } = new InternalCreateAssistantRequestModel(Gpt4oMini20240718Value); public static InternalCreateAssistantRequestModel Gpt4Turbo { get; } = new InternalCreateAssistantRequestModel(Gpt4TurboValue); public static InternalCreateAssistantRequestModel Gpt4Turbo20240409 { get; } = new InternalCreateAssistantRequestModel(Gpt4Turbo20240409Value); public static InternalCreateAssistantRequestModel Gpt40125Preview { get; } = new InternalCreateAssistantRequestModel(Gpt40125PreviewValue); diff --git a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResources.Serialization.cs b/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResources.Serialization.cs index 9b879c1ec..d21e16129 100644 --- a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResources.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResources.Serialization.cs @@ -29,14 +29,7 @@ void IJsonModel.Write(Utf8JsonWrite if (SerializedAdditionalRawData?.ContainsKey("file_search") != true && Optional.IsDefined(FileSearch)) { writer.WritePropertyName("file_search"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(FileSearch); -#else - using (JsonDocument document = JsonDocument.Parse(FileSearch)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif + writer.WriteObjectValue(FileSearch, options); } if (SerializedAdditionalRawData != null) { @@ -81,7 +74,7 @@ internal static InternalCreateAssistantRequestToolResources DeserializeInternalC return null; } InternalCreateAssistantRequestToolResourcesCodeInterpreter codeInterpreter = default; - BinaryData fileSearch = default; + FileSearchToolResources fileSearch = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -101,7 +94,7 @@ internal static InternalCreateAssistantRequestToolResources DeserializeInternalC { continue; } - fileSearch = BinaryData.FromString(property.Value.GetRawText()); + fileSearch = FileSearchToolResources.DeserializeFileSearchToolResources(property.Value, options); continue; } if (true) diff --git a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResources.cs b/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResources.cs index 4ed163de6..3ac5aa737 100644 --- a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResources.cs +++ b/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResources.cs @@ -14,7 +14,7 @@ public InternalCreateAssistantRequestToolResources() { } - internal InternalCreateAssistantRequestToolResources(InternalCreateAssistantRequestToolResourcesCodeInterpreter codeInterpreter, BinaryData fileSearch, IDictionary serializedAdditionalRawData) + internal InternalCreateAssistantRequestToolResources(InternalCreateAssistantRequestToolResourcesCodeInterpreter codeInterpreter, FileSearchToolResources fileSearch, IDictionary serializedAdditionalRawData) { CodeInterpreter = codeInterpreter; FileSearch = fileSearch; @@ -22,6 +22,6 @@ internal InternalCreateAssistantRequestToolResources(InternalCreateAssistantRequ } public InternalCreateAssistantRequestToolResourcesCodeInterpreter CodeInterpreter { get; set; } - public BinaryData FileSearch { get; set; } + public FileSearchToolResources FileSearch { get; set; } } } diff --git a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchBase.cs b/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchBase.cs deleted file mode 100644 index 31dff8351..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchBase.cs +++ /dev/null @@ -1,22 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace OpenAI.Assistants -{ - internal partial class InternalCreateAssistantRequestToolResourcesFileSearchBase - { - internal IDictionary SerializedAdditionalRawData { get; set; } - public InternalCreateAssistantRequestToolResourcesFileSearchBase() - { - } - - internal InternalCreateAssistantRequestToolResourcesFileSearchBase(IDictionary serializedAdditionalRawData) - { - SerializedAdditionalRawData = serializedAdditionalRawData; - } - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers.Serialization.cs b/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers.Serialization.cs deleted file mode 100644 index af3257e65..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers.Serialization.cs +++ /dev/null @@ -1,147 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace OpenAI.Assistants -{ - internal partial class InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("vector_stores") != true && Optional.IsCollectionDefined(VectorStores)) - { - writer.WritePropertyName("vector_stores"u8); - writer.WriteStartArray(); - foreach (var item in VectorStores) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers(document.RootElement, options); - } - - internal static InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers DeserializeInternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IList vectorStores = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("vector_stores"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(VectorStoreCreationHelper.DeserializeVectorStoreCreationHelper(item, options)); - } - vectorStores = array; - continue; - } - if (true) - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers(vectorStores ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers)} does not support writing '{options.Format}' format."); - } - } - - InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeInternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers(document.RootElement); - } - - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers.cs b/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers.cs deleted file mode 100644 index bb2896dc6..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers.cs +++ /dev/null @@ -1,26 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace OpenAI.Assistants -{ - internal partial class InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers - { - internal IDictionary SerializedAdditionalRawData { get; set; } - public InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers() - { - VectorStores = new ChangeTrackingList(); - } - - internal InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers(IList vectorStores, IDictionary serializedAdditionalRawData) - { - VectorStores = vectorStores; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - public IList VectorStores { get; } - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences.Serialization.cs b/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences.Serialization.cs deleted file mode 100644 index 4193507ce..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences.Serialization.cs +++ /dev/null @@ -1,147 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace OpenAI.Assistants -{ - internal partial class InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("vector_store_ids") != true && Optional.IsCollectionDefined(VectorStoreIds)) - { - writer.WritePropertyName("vector_store_ids"u8); - writer.WriteStartArray(); - foreach (var item in VectorStoreIds) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences(document.RootElement, options); - } - - internal static InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences DeserializeInternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IList vectorStoreIds = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("vector_store_ids"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - vectorStoreIds = array; - continue; - } - if (true) - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences(vectorStoreIds ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences)} does not support writing '{options.Format}' format."); - } - } - - InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeInternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences(document.RootElement); - } - - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences.cs b/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences.cs deleted file mode 100644 index ba6da6ac4..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences.cs +++ /dev/null @@ -1,26 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace OpenAI.Assistants -{ - internal partial class InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences - { - internal IDictionary SerializedAdditionalRawData { get; set; } - public InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences() - { - VectorStoreIds = new ChangeTrackingList(); - } - - internal InternalCreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences(IList vectorStoreIds, IDictionary serializedAdditionalRawData) - { - VectorStoreIds = vectorStoreIds; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - public IList VectorStoreIds { get; } - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateChatCompletionRequestModel.cs b/.dotnet/src/Generated/Models/InternalCreateChatCompletionRequestModel.cs index 3ee5bd5d5..4b14c7809 100644 --- a/.dotnet/src/Generated/Models/InternalCreateChatCompletionRequestModel.cs +++ b/.dotnet/src/Generated/Models/InternalCreateChatCompletionRequestModel.cs @@ -18,6 +18,10 @@ public InternalCreateChatCompletionRequestModel(string value) private const string Gpt4oValue = "gpt-4o"; private const string Gpt4o20240513Value = "gpt-4o-2024-05-13"; + private const string Gpt4o20240806Value = "gpt-4o-2024-08-06"; + private const string Chatgpt4oLatestValue = "chatgpt-4o-latest"; + private const string Gpt4oMiniValue = "gpt-4o-mini"; + private const string Gpt4oMini20240718Value = "gpt-4o-mini-2024-07-18"; private const string Gpt4TurboValue = "gpt-4-turbo"; private const string Gpt4Turbo20240409Value = "gpt-4-turbo-2024-04-09"; private const string Gpt40125PreviewValue = "gpt-4-0125-preview"; @@ -40,6 +44,10 @@ public InternalCreateChatCompletionRequestModel(string value) public static InternalCreateChatCompletionRequestModel Gpt4o { get; } = new InternalCreateChatCompletionRequestModel(Gpt4oValue); public static InternalCreateChatCompletionRequestModel Gpt4o20240513 { get; } = new InternalCreateChatCompletionRequestModel(Gpt4o20240513Value); + public static InternalCreateChatCompletionRequestModel Gpt4o20240806 { get; } = new InternalCreateChatCompletionRequestModel(Gpt4o20240806Value); + public static InternalCreateChatCompletionRequestModel Chatgpt4oLatest { get; } = new InternalCreateChatCompletionRequestModel(Chatgpt4oLatestValue); + public static InternalCreateChatCompletionRequestModel Gpt4oMini { get; } = new InternalCreateChatCompletionRequestModel(Gpt4oMiniValue); + public static InternalCreateChatCompletionRequestModel Gpt4oMini20240718 { get; } = new InternalCreateChatCompletionRequestModel(Gpt4oMini20240718Value); public static InternalCreateChatCompletionRequestModel Gpt4Turbo { get; } = new InternalCreateChatCompletionRequestModel(Gpt4TurboValue); public static InternalCreateChatCompletionRequestModel Gpt4Turbo20240409 { get; } = new InternalCreateChatCompletionRequestModel(Gpt4Turbo20240409Value); public static InternalCreateChatCompletionRequestModel Gpt40125Preview { get; } = new InternalCreateChatCompletionRequestModel(Gpt40125PreviewValue); diff --git a/.dotnet/src/Generated/Models/InternalCreateChatCompletionRequestResponseFormatType.cs b/.dotnet/src/Generated/Models/InternalCreateChatCompletionRequestResponseFormatType.cs deleted file mode 100644 index 535b6a509..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateChatCompletionRequestResponseFormatType.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace OpenAI.Chat -{ - internal readonly partial struct InternalCreateChatCompletionRequestResponseFormatType : IEquatable - { - private readonly string _value; - - public InternalCreateChatCompletionRequestResponseFormatType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string TextValue = "text"; - private const string JsonObjectValue = "json_object"; - - public static InternalCreateChatCompletionRequestResponseFormatType Text { get; } = new InternalCreateChatCompletionRequestResponseFormatType(TextValue); - public static InternalCreateChatCompletionRequestResponseFormatType JsonObject { get; } = new InternalCreateChatCompletionRequestResponseFormatType(JsonObjectValue); - public static bool operator ==(InternalCreateChatCompletionRequestResponseFormatType left, InternalCreateChatCompletionRequestResponseFormatType right) => left.Equals(right); - public static bool operator !=(InternalCreateChatCompletionRequestResponseFormatType left, InternalCreateChatCompletionRequestResponseFormatType right) => !left.Equals(right); - public static implicit operator InternalCreateChatCompletionRequestResponseFormatType(string value) => new InternalCreateChatCompletionRequestResponseFormatType(value); - - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is InternalCreateChatCompletionRequestResponseFormatType other && Equals(other); - public bool Equals(InternalCreateChatCompletionRequestResponseFormatType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - public override string ToString() => _value; - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateChatCompletionRequestServiceTier.cs b/.dotnet/src/Generated/Models/InternalCreateChatCompletionRequestServiceTier.cs new file mode 100644 index 000000000..7d6f7f657 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalCreateChatCompletionRequestServiceTier.cs @@ -0,0 +1,36 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace OpenAI.Chat +{ + internal readonly partial struct InternalCreateChatCompletionRequestServiceTier : IEquatable + { + private readonly string _value; + + public InternalCreateChatCompletionRequestServiceTier(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + private const string DefaultValue = "default"; + + public static InternalCreateChatCompletionRequestServiceTier Auto { get; } = new InternalCreateChatCompletionRequestServiceTier(AutoValue); + public static InternalCreateChatCompletionRequestServiceTier Default { get; } = new InternalCreateChatCompletionRequestServiceTier(DefaultValue); + public static bool operator ==(InternalCreateChatCompletionRequestServiceTier left, InternalCreateChatCompletionRequestServiceTier right) => left.Equals(right); + public static bool operator !=(InternalCreateChatCompletionRequestServiceTier left, InternalCreateChatCompletionRequestServiceTier right) => !left.Equals(right); + public static implicit operator InternalCreateChatCompletionRequestServiceTier(string value) => new InternalCreateChatCompletionRequestServiceTier(value); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InternalCreateChatCompletionRequestServiceTier other && Equals(other); + public bool Equals(InternalCreateChatCompletionRequestServiceTier other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; + } +} diff --git a/.dotnet/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.Serialization.cs b/.dotnet/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.Serialization.cs index db61936aa..1fee709bf 100644 --- a/.dotnet/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.Serialization.cs @@ -38,6 +38,23 @@ void IJsonModel.Write(Utf8Js writer.WriteNull("content"); } } + if (SerializedAdditionalRawData?.ContainsKey("refusal") != true) + { + if (Refusal != null && Optional.IsCollectionDefined(Refusal)) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStartArray(); + foreach (var item in Refusal) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("refusal"); + } + } if (SerializedAdditionalRawData != null) { foreach (var item in SerializedAdditionalRawData) @@ -81,6 +98,7 @@ internal static InternalCreateChatCompletionResponseChoiceLogprobs DeserializeIn return null; } IReadOnlyList content = default; + IReadOnlyList refusal = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -100,6 +118,21 @@ internal static InternalCreateChatCompletionResponseChoiceLogprobs DeserializeIn content = array; continue; } + if (property.NameEquals("refusal"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + refusal = new ChangeTrackingList(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatTokenLogProbabilityInfo.DeserializeChatTokenLogProbabilityInfo(item, options)); + } + refusal = array; + continue; + } if (true) { rawDataDictionary ??= new Dictionary(); @@ -107,7 +140,7 @@ internal static InternalCreateChatCompletionResponseChoiceLogprobs DeserializeIn } } serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateChatCompletionResponseChoiceLogprobs(content, serializedAdditionalRawData); + return new InternalCreateChatCompletionResponseChoiceLogprobs(content, refusal, serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/.dotnet/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.cs b/.dotnet/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.cs index d81088a5c..a03030ec2 100644 --- a/.dotnet/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.cs +++ b/.dotnet/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.cs @@ -11,14 +11,16 @@ namespace OpenAI.Chat internal partial class InternalCreateChatCompletionResponseChoiceLogprobs { internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalCreateChatCompletionResponseChoiceLogprobs(IEnumerable content) + internal InternalCreateChatCompletionResponseChoiceLogprobs(IEnumerable content, IEnumerable refusal) { Content = content?.ToList(); + Refusal = refusal?.ToList(); } - internal InternalCreateChatCompletionResponseChoiceLogprobs(IReadOnlyList content, IDictionary serializedAdditionalRawData) + internal InternalCreateChatCompletionResponseChoiceLogprobs(IReadOnlyList content, IReadOnlyList refusal, IDictionary serializedAdditionalRawData) { Content = content; + Refusal = refusal; SerializedAdditionalRawData = serializedAdditionalRawData; } @@ -27,5 +29,6 @@ internal InternalCreateChatCompletionResponseChoiceLogprobs() } public IReadOnlyList Content { get; } + public IReadOnlyList Refusal { get; } } } diff --git a/.dotnet/src/Generated/Models/InternalCreateChatCompletionResponseServiceTier.cs b/.dotnet/src/Generated/Models/InternalCreateChatCompletionResponseServiceTier.cs new file mode 100644 index 000000000..599297be0 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalCreateChatCompletionResponseServiceTier.cs @@ -0,0 +1,36 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace OpenAI.Chat +{ + internal readonly partial struct InternalCreateChatCompletionResponseServiceTier : IEquatable + { + private readonly string _value; + + public InternalCreateChatCompletionResponseServiceTier(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ScaleValue = "scale"; + private const string DefaultValue = "default"; + + public static InternalCreateChatCompletionResponseServiceTier Scale { get; } = new InternalCreateChatCompletionResponseServiceTier(ScaleValue); + public static InternalCreateChatCompletionResponseServiceTier Default { get; } = new InternalCreateChatCompletionResponseServiceTier(DefaultValue); + public static bool operator ==(InternalCreateChatCompletionResponseServiceTier left, InternalCreateChatCompletionResponseServiceTier right) => left.Equals(right); + public static bool operator !=(InternalCreateChatCompletionResponseServiceTier left, InternalCreateChatCompletionResponseServiceTier right) => !left.Equals(right); + public static implicit operator InternalCreateChatCompletionResponseServiceTier(string value) => new InternalCreateChatCompletionResponseServiceTier(value); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InternalCreateChatCompletionResponseServiceTier other && Equals(other); + public bool Equals(InternalCreateChatCompletionResponseServiceTier other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; + } +} diff --git a/.dotnet/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.Serialization.cs b/.dotnet/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.Serialization.cs index 28f81317f..43ebedfc9 100644 --- a/.dotnet/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.Serialization.cs @@ -38,6 +38,23 @@ void IJsonModel.Write( writer.WriteNull("content"); } } + if (SerializedAdditionalRawData?.ContainsKey("refusal") != true) + { + if (Refusal != null && Optional.IsCollectionDefined(Refusal)) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStartArray(); + foreach (var item in Refusal) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("refusal"); + } + } if (SerializedAdditionalRawData != null) { foreach (var item in SerializedAdditionalRawData) @@ -81,6 +98,7 @@ internal static InternalCreateChatCompletionStreamResponseChoiceLogprobs Deseria return null; } IReadOnlyList content = default; + IReadOnlyList refusal = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -100,6 +118,21 @@ internal static InternalCreateChatCompletionStreamResponseChoiceLogprobs Deseria content = array; continue; } + if (property.NameEquals("refusal"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + refusal = new ChangeTrackingList(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatTokenLogProbabilityInfo.DeserializeChatTokenLogProbabilityInfo(item, options)); + } + refusal = array; + continue; + } if (true) { rawDataDictionary ??= new Dictionary(); @@ -107,7 +140,7 @@ internal static InternalCreateChatCompletionStreamResponseChoiceLogprobs Deseria } } serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateChatCompletionStreamResponseChoiceLogprobs(content, serializedAdditionalRawData); + return new InternalCreateChatCompletionStreamResponseChoiceLogprobs(content, refusal, serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/.dotnet/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.cs b/.dotnet/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.cs index f0a780dd9..03a852399 100644 --- a/.dotnet/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.cs +++ b/.dotnet/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.cs @@ -11,14 +11,16 @@ namespace OpenAI.Chat internal partial class InternalCreateChatCompletionStreamResponseChoiceLogprobs { internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalCreateChatCompletionStreamResponseChoiceLogprobs(IEnumerable content) + internal InternalCreateChatCompletionStreamResponseChoiceLogprobs(IEnumerable content, IEnumerable refusal) { Content = content?.ToList(); + Refusal = refusal?.ToList(); } - internal InternalCreateChatCompletionStreamResponseChoiceLogprobs(IReadOnlyList content, IDictionary serializedAdditionalRawData) + internal InternalCreateChatCompletionStreamResponseChoiceLogprobs(IReadOnlyList content, IReadOnlyList refusal, IDictionary serializedAdditionalRawData) { Content = content; + Refusal = refusal; SerializedAdditionalRawData = serializedAdditionalRawData; } @@ -27,5 +29,6 @@ internal InternalCreateChatCompletionStreamResponseChoiceLogprobs() } public IReadOnlyList Content { get; } + public IReadOnlyList Refusal { get; } } } diff --git a/.dotnet/src/Generated/Models/InternalCreateChatCompletionStreamResponseServiceTier.cs b/.dotnet/src/Generated/Models/InternalCreateChatCompletionStreamResponseServiceTier.cs new file mode 100644 index 000000000..0f2eb1326 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalCreateChatCompletionStreamResponseServiceTier.cs @@ -0,0 +1,36 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace OpenAI.Chat +{ + internal readonly partial struct InternalCreateChatCompletionStreamResponseServiceTier : IEquatable + { + private readonly string _value; + + public InternalCreateChatCompletionStreamResponseServiceTier(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ScaleValue = "scale"; + private const string DefaultValue = "default"; + + public static InternalCreateChatCompletionStreamResponseServiceTier Scale { get; } = new InternalCreateChatCompletionStreamResponseServiceTier(ScaleValue); + public static InternalCreateChatCompletionStreamResponseServiceTier Default { get; } = new InternalCreateChatCompletionStreamResponseServiceTier(DefaultValue); + public static bool operator ==(InternalCreateChatCompletionStreamResponseServiceTier left, InternalCreateChatCompletionStreamResponseServiceTier right) => left.Equals(right); + public static bool operator !=(InternalCreateChatCompletionStreamResponseServiceTier left, InternalCreateChatCompletionStreamResponseServiceTier right) => !left.Equals(right); + public static implicit operator InternalCreateChatCompletionStreamResponseServiceTier(string value) => new InternalCreateChatCompletionStreamResponseServiceTier(value); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InternalCreateChatCompletionStreamResponseServiceTier other && Equals(other); + public bool Equals(InternalCreateChatCompletionStreamResponseServiceTier other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; + } +} diff --git a/.dotnet/src/Generated/Models/InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum.cs b/.dotnet/src/Generated/Models/InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum.cs new file mode 100644 index 000000000..f104417d9 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum.cs @@ -0,0 +1,34 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace OpenAI.FineTuning +{ + internal readonly partial struct InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum : IEquatable + { + private readonly string _value; + + public InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + + public static InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum Auto { get; } = new InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum(AutoValue); + public static bool operator ==(InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum left, InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum right) => left.Equals(right); + public static bool operator !=(InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum left, InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum right) => !left.Equals(right); + public static implicit operator InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum(string value) => new InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum(value); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum other && Equals(other); + public bool Equals(InternalCreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; + } +} diff --git a/.dotnet/src/Generated/Models/InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum.cs b/.dotnet/src/Generated/Models/InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum.cs new file mode 100644 index 000000000..9ff39cc7d --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum.cs @@ -0,0 +1,34 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace OpenAI.FineTuning +{ + internal readonly partial struct InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum : IEquatable + { + private readonly string _value; + + public InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + + public static InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum Auto { get; } = new InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum(AutoValue); + public static bool operator ==(InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum left, InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum right) => left.Equals(right); + public static bool operator !=(InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum left, InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum right) => !left.Equals(right); + public static implicit operator InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum(string value) => new InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum(value); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum other && Equals(other); + public bool Equals(InternalCreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; + } +} diff --git a/.dotnet/src/Generated/Models/InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum.cs b/.dotnet/src/Generated/Models/InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum.cs new file mode 100644 index 000000000..8fad11a4b --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum.cs @@ -0,0 +1,34 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace OpenAI.FineTuning +{ + internal readonly partial struct InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum : IEquatable + { + private readonly string _value; + + public InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + + public static InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum Auto { get; } = new InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum(AutoValue); + public static bool operator ==(InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum left, InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum right) => left.Equals(right); + public static bool operator !=(InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum left, InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum right) => !left.Equals(right); + public static implicit operator InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum(string value) => new InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum(value); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum other && Equals(other); + public bool Equals(InternalCreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; + } +} diff --git a/.dotnet/src/Generated/Models/InternalCreateFineTuningJobRequestModel.cs b/.dotnet/src/Generated/Models/InternalCreateFineTuningJobRequestModel.cs index ad3f54906..e85d5c334 100644 --- a/.dotnet/src/Generated/Models/InternalCreateFineTuningJobRequestModel.cs +++ b/.dotnet/src/Generated/Models/InternalCreateFineTuningJobRequestModel.cs @@ -19,10 +19,12 @@ public InternalCreateFineTuningJobRequestModel(string value) private const string Babbage002Value = "babbage-002"; private const string Davinci002Value = "davinci-002"; private const string Gpt35TurboValue = "gpt-3.5-turbo"; + private const string Gpt4oMiniValue = "gpt-4o-mini"; public static InternalCreateFineTuningJobRequestModel Babbage002 { get; } = new InternalCreateFineTuningJobRequestModel(Babbage002Value); public static InternalCreateFineTuningJobRequestModel Davinci002 { get; } = new InternalCreateFineTuningJobRequestModel(Davinci002Value); public static InternalCreateFineTuningJobRequestModel Gpt35Turbo { get; } = new InternalCreateFineTuningJobRequestModel(Gpt35TurboValue); + public static InternalCreateFineTuningJobRequestModel Gpt4oMini { get; } = new InternalCreateFineTuningJobRequestModel(Gpt4oMiniValue); public static bool operator ==(InternalCreateFineTuningJobRequestModel left, InternalCreateFineTuningJobRequestModel right) => left.Equals(right); public static bool operator !=(InternalCreateFineTuningJobRequestModel left, InternalCreateFineTuningJobRequestModel right) => !left.Equals(right); public static implicit operator InternalCreateFineTuningJobRequestModel(string value) => new InternalCreateFineTuningJobRequestModel(value); diff --git a/.dotnet/src/Generated/Models/InternalCreateRunRequestModel.cs b/.dotnet/src/Generated/Models/InternalCreateRunRequestModel.cs index 56b07d83d..27b73a31b 100644 --- a/.dotnet/src/Generated/Models/InternalCreateRunRequestModel.cs +++ b/.dotnet/src/Generated/Models/InternalCreateRunRequestModel.cs @@ -17,7 +17,10 @@ public InternalCreateRunRequestModel(string value) } private const string Gpt4oValue = "gpt-4o"; + private const string Gpt4o20240806Value = "gpt-4o-2024-08-06"; private const string Gpt4o20240513Value = "gpt-4o-2024-05-13"; + private const string Gpt4oMiniValue = "gpt-4o-mini"; + private const string Gpt4oMini20240718Value = "gpt-4o-mini-2024-07-18"; private const string Gpt4TurboValue = "gpt-4-turbo"; private const string Gpt4Turbo20240409Value = "gpt-4-turbo-2024-04-09"; private const string Gpt40125PreviewValue = "gpt-4-0125-preview"; @@ -38,7 +41,10 @@ public InternalCreateRunRequestModel(string value) private const string Gpt35Turbo16k0613Value = "gpt-3.5-turbo-16k-0613"; public static InternalCreateRunRequestModel Gpt4o { get; } = new InternalCreateRunRequestModel(Gpt4oValue); + public static InternalCreateRunRequestModel Gpt4o20240806 { get; } = new InternalCreateRunRequestModel(Gpt4o20240806Value); public static InternalCreateRunRequestModel Gpt4o20240513 { get; } = new InternalCreateRunRequestModel(Gpt4o20240513Value); + public static InternalCreateRunRequestModel Gpt4oMini { get; } = new InternalCreateRunRequestModel(Gpt4oMiniValue); + public static InternalCreateRunRequestModel Gpt4oMini20240718 { get; } = new InternalCreateRunRequestModel(Gpt4oMini20240718Value); public static InternalCreateRunRequestModel Gpt4Turbo { get; } = new InternalCreateRunRequestModel(Gpt4TurboValue); public static InternalCreateRunRequestModel Gpt4Turbo20240409 { get; } = new InternalCreateRunRequestModel(Gpt4Turbo20240409Value); public static InternalCreateRunRequestModel Gpt40125Preview { get; } = new InternalCreateRunRequestModel(Gpt40125PreviewValue); diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestModel.cs b/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestModel.cs index ecabe34e7..04d84a623 100644 --- a/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestModel.cs +++ b/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestModel.cs @@ -17,7 +17,10 @@ public InternalCreateThreadAndRunRequestModel(string value) } private const string Gpt4oValue = "gpt-4o"; + private const string Gpt4o20240806Value = "gpt-4o-2024-08-06"; private const string Gpt4o20240513Value = "gpt-4o-2024-05-13"; + private const string Gpt4oMiniValue = "gpt-4o-mini"; + private const string Gpt4oMini20240718Value = "gpt-4o-mini-2024-07-18"; private const string Gpt4TurboValue = "gpt-4-turbo"; private const string Gpt4Turbo20240409Value = "gpt-4-turbo-2024-04-09"; private const string Gpt40125PreviewValue = "gpt-4-0125-preview"; @@ -38,7 +41,10 @@ public InternalCreateThreadAndRunRequestModel(string value) private const string Gpt35Turbo16k0613Value = "gpt-3.5-turbo-16k-0613"; public static InternalCreateThreadAndRunRequestModel Gpt4o { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4oValue); + public static InternalCreateThreadAndRunRequestModel Gpt4o20240806 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4o20240806Value); public static InternalCreateThreadAndRunRequestModel Gpt4o20240513 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4o20240513Value); + public static InternalCreateThreadAndRunRequestModel Gpt4oMini { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4oMiniValue); + public static InternalCreateThreadAndRunRequestModel Gpt4oMini20240718 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4oMini20240718Value); public static InternalCreateThreadAndRunRequestModel Gpt4Turbo { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4TurboValue); public static InternalCreateThreadAndRunRequestModel Gpt4Turbo20240409 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4Turbo20240409Value); public static InternalCreateThreadAndRunRequestModel Gpt40125Preview { get; } = new InternalCreateThreadAndRunRequestModel(Gpt40125PreviewValue); diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestResponseFormat.cs b/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestResponseFormat.cs deleted file mode 100644 index e268b7603..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestResponseFormat.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace OpenAI.Assistants -{ - internal readonly partial struct InternalCreateThreadAndRunRequestResponseFormat : IEquatable - { - private readonly string _value; - - public InternalCreateThreadAndRunRequestResponseFormat(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NoneValue = "none"; - private const string AutoValue = "auto"; - - public static InternalCreateThreadAndRunRequestResponseFormat None { get; } = new InternalCreateThreadAndRunRequestResponseFormat(NoneValue); - public static InternalCreateThreadAndRunRequestResponseFormat Auto { get; } = new InternalCreateThreadAndRunRequestResponseFormat(AutoValue); - public static bool operator ==(InternalCreateThreadAndRunRequestResponseFormat left, InternalCreateThreadAndRunRequestResponseFormat right) => left.Equals(right); - public static bool operator !=(InternalCreateThreadAndRunRequestResponseFormat left, InternalCreateThreadAndRunRequestResponseFormat right) => !left.Equals(right); - public static implicit operator InternalCreateThreadAndRunRequestResponseFormat(string value) => new InternalCreateThreadAndRunRequestResponseFormat(value); - - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is InternalCreateThreadAndRunRequestResponseFormat other && Equals(other); - public bool Equals(InternalCreateThreadAndRunRequestResponseFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - public override string ToString() => _value; - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.Serialization.cs b/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.Serialization.cs index 3e3112c91..aff6e9e50 100644 --- a/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.Serialization.cs @@ -74,7 +74,7 @@ internal static InternalCreateThreadAndRunRequestToolResources DeserializeIntern return null; } InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter codeInterpreter = default; - InternalCreateThreadAndRunRequestToolResourcesFileSearch fileSearch = default; + InternalToolResourcesFileSearchIdsOnly fileSearch = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -94,7 +94,7 @@ internal static InternalCreateThreadAndRunRequestToolResources DeserializeIntern { continue; } - fileSearch = InternalCreateThreadAndRunRequestToolResourcesFileSearch.DeserializeInternalCreateThreadAndRunRequestToolResourcesFileSearch(property.Value, options); + fileSearch = InternalToolResourcesFileSearchIdsOnly.DeserializeInternalToolResourcesFileSearchIdsOnly(property.Value, options); continue; } if (true) diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.cs b/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.cs index 452a48065..a07a484a3 100644 --- a/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.cs +++ b/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.cs @@ -14,7 +14,7 @@ public InternalCreateThreadAndRunRequestToolResources() { } - internal InternalCreateThreadAndRunRequestToolResources(InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter codeInterpreter, InternalCreateThreadAndRunRequestToolResourcesFileSearch fileSearch, IDictionary serializedAdditionalRawData) + internal InternalCreateThreadAndRunRequestToolResources(InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter codeInterpreter, InternalToolResourcesFileSearchIdsOnly fileSearch, IDictionary serializedAdditionalRawData) { CodeInterpreter = codeInterpreter; FileSearch = fileSearch; @@ -22,6 +22,6 @@ internal InternalCreateThreadAndRunRequestToolResources(InternalCreateThreadAndR } public InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter CodeInterpreter { get; set; } - public InternalCreateThreadAndRunRequestToolResourcesFileSearch FileSearch { get; set; } + public InternalToolResourcesFileSearchIdsOnly FileSearch { get; set; } } } diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesFileSearch.Serialization.cs b/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesFileSearch.Serialization.cs deleted file mode 100644 index 32a57d4a3..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesFileSearch.Serialization.cs +++ /dev/null @@ -1,147 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace OpenAI.Assistants -{ - internal partial class InternalCreateThreadAndRunRequestToolResourcesFileSearch : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalCreateThreadAndRunRequestToolResourcesFileSearch)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("vector_store_ids") != true && Optional.IsCollectionDefined(VectorStoreIds)) - { - writer.WritePropertyName("vector_store_ids"u8); - writer.WriteStartArray(); - foreach (var item in VectorStoreIds) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalCreateThreadAndRunRequestToolResourcesFileSearch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalCreateThreadAndRunRequestToolResourcesFileSearch)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalCreateThreadAndRunRequestToolResourcesFileSearch(document.RootElement, options); - } - - internal static InternalCreateThreadAndRunRequestToolResourcesFileSearch DeserializeInternalCreateThreadAndRunRequestToolResourcesFileSearch(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IList vectorStoreIds = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("vector_store_ids"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - vectorStoreIds = array; - continue; - } - if (true) - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateThreadAndRunRequestToolResourcesFileSearch(vectorStoreIds ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalCreateThreadAndRunRequestToolResourcesFileSearch)} does not support writing '{options.Format}' format."); - } - } - - InternalCreateThreadAndRunRequestToolResourcesFileSearch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeInternalCreateThreadAndRunRequestToolResourcesFileSearch(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalCreateThreadAndRunRequestToolResourcesFileSearch)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static InternalCreateThreadAndRunRequestToolResourcesFileSearch FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateThreadAndRunRequestToolResourcesFileSearch(document.RootElement); - } - - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesFileSearch.cs b/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesFileSearch.cs deleted file mode 100644 index 5a5c4b1f1..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesFileSearch.cs +++ /dev/null @@ -1,26 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace OpenAI.Assistants -{ - internal partial class InternalCreateThreadAndRunRequestToolResourcesFileSearch - { - internal IDictionary SerializedAdditionalRawData { get; set; } - public InternalCreateThreadAndRunRequestToolResourcesFileSearch() - { - VectorStoreIds = new ChangeTrackingList(); - } - - internal InternalCreateThreadAndRunRequestToolResourcesFileSearch(IList vectorStoreIds, IDictionary serializedAdditionalRawData) - { - VectorStoreIds = vectorStoreIds; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - public IList VectorStoreIds { get; } - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResources.Serialization.cs b/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResources.Serialization.cs index 24c1889b5..39b6689b2 100644 --- a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResources.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResources.Serialization.cs @@ -29,14 +29,7 @@ void IJsonModel.Write(Utf8JsonWriter w if (SerializedAdditionalRawData?.ContainsKey("file_search") != true && Optional.IsDefined(FileSearch)) { writer.WritePropertyName("file_search"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(FileSearch); -#else - using (JsonDocument document = JsonDocument.Parse(FileSearch)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif + writer.WriteObjectValue(FileSearch, options); } if (SerializedAdditionalRawData != null) { @@ -81,7 +74,7 @@ internal static InternalCreateThreadRequestToolResources DeserializeInternalCrea return null; } InternalCreateThreadRequestToolResourcesCodeInterpreter codeInterpreter = default; - BinaryData fileSearch = default; + FileSearchToolResources fileSearch = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -101,7 +94,7 @@ internal static InternalCreateThreadRequestToolResources DeserializeInternalCrea { continue; } - fileSearch = BinaryData.FromString(property.Value.GetRawText()); + fileSearch = FileSearchToolResources.DeserializeFileSearchToolResources(property.Value, options); continue; } if (true) diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResources.cs b/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResources.cs index ca16742e9..08a68fce1 100644 --- a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResources.cs +++ b/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResources.cs @@ -14,7 +14,7 @@ public InternalCreateThreadRequestToolResources() { } - internal InternalCreateThreadRequestToolResources(InternalCreateThreadRequestToolResourcesCodeInterpreter codeInterpreter, BinaryData fileSearch, IDictionary serializedAdditionalRawData) + internal InternalCreateThreadRequestToolResources(InternalCreateThreadRequestToolResourcesCodeInterpreter codeInterpreter, FileSearchToolResources fileSearch, IDictionary serializedAdditionalRawData) { CodeInterpreter = codeInterpreter; FileSearch = fileSearch; @@ -22,6 +22,6 @@ internal InternalCreateThreadRequestToolResources(InternalCreateThreadRequestToo } public InternalCreateThreadRequestToolResourcesCodeInterpreter CodeInterpreter { get; set; } - public BinaryData FileSearch { get; set; } + public FileSearchToolResources FileSearch { get; set; } } } diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers.Serialization.cs b/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers.Serialization.cs deleted file mode 100644 index a158ff57a..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers.Serialization.cs +++ /dev/null @@ -1,147 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace OpenAI.Assistants -{ - internal partial class InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("vector_stores") != true && Optional.IsCollectionDefined(VectorStores)) - { - writer.WritePropertyName("vector_stores"u8); - writer.WriteStartArray(); - foreach (var item in VectorStores) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers(document.RootElement, options); - } - - internal static InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers DeserializeInternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IList vectorStores = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("vector_stores"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore.DeserializeInternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore(item, options)); - } - vectorStores = array; - continue; - } - if (true) - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers(vectorStores ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers)} does not support writing '{options.Format}' format."); - } - } - - InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeInternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers(document.RootElement); - } - - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers.cs b/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers.cs deleted file mode 100644 index f1854538c..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers.cs +++ /dev/null @@ -1,26 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace OpenAI.Assistants -{ - internal partial class InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers - { - internal IDictionary SerializedAdditionalRawData { get; set; } - public InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers() - { - VectorStores = new ChangeTrackingList(); - } - - internal InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers(IList vectorStores, IDictionary serializedAdditionalRawData) - { - VectorStores = vectorStores; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - public IList VectorStores { get; } - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore.Serialization.cs b/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore.Serialization.cs deleted file mode 100644 index be93ed9cf..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore.Serialization.cs +++ /dev/null @@ -1,173 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace OpenAI.Assistants -{ - internal partial class InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_ids") != true && Optional.IsCollectionDefined(FileIds)) - { - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) - { - writer.WritePropertyName("metadata"u8); - writer.WriteStartObject(); - foreach (var item in Metadata) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore(document.RootElement, options); - } - - internal static InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore DeserializeInternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IList fileIds = default; - IDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("file_ids"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - fileIds = array; - continue; - } - if (property.NameEquals("metadata"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - metadata = dictionary; - continue; - } - if (true) - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore(fileIds ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore)} does not support writing '{options.Format}' format."); - } - } - - InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeInternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore(document.RootElement); - } - - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore.cs b/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore.cs deleted file mode 100644 index 430b2c563..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore.cs +++ /dev/null @@ -1,29 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace OpenAI.Assistants -{ - internal partial class InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore - { - internal IDictionary SerializedAdditionalRawData { get; set; } - public InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore() - { - FileIds = new ChangeTrackingList(); - Metadata = new ChangeTrackingDictionary(); - } - - internal InternalCreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpersVectorStore(IList fileIds, IDictionary metadata, IDictionary serializedAdditionalRawData) - { - FileIds = fileIds; - Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - public IList FileIds { get; } - public IDictionary Metadata { get; } - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences.Serialization.cs b/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences.Serialization.cs deleted file mode 100644 index e8e18dba6..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences.Serialization.cs +++ /dev/null @@ -1,147 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace OpenAI.Assistants -{ - internal partial class InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("vector_store_ids") != true && Optional.IsCollectionDefined(VectorStoreIds)) - { - writer.WritePropertyName("vector_store_ids"u8); - writer.WriteStartArray(); - foreach (var item in VectorStoreIds) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences(document.RootElement, options); - } - - internal static InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences DeserializeInternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IList vectorStoreIds = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("vector_store_ids"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - vectorStoreIds = array; - continue; - } - if (true) - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences(vectorStoreIds ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences)} does not support writing '{options.Format}' format."); - } - } - - InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeInternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences(document.RootElement); - } - - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences.cs b/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences.cs deleted file mode 100644 index 140500897..000000000 --- a/.dotnet/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences.cs +++ /dev/null @@ -1,26 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace OpenAI.Assistants -{ - internal partial class InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences - { - internal IDictionary SerializedAdditionalRawData { get; set; } - public InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences() - { - VectorStoreIds = new ChangeTrackingList(); - } - - internal InternalCreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences(IList vectorStoreIds, IDictionary serializedAdditionalRawData) - { - VectorStoreIds = vectorStoreIds; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - public IList VectorStoreIds { get; } - } -} diff --git a/.dotnet/src/Generated/Models/InternalCreateUploadRequest.Serialization.cs b/.dotnet/src/Generated/Models/InternalCreateUploadRequest.Serialization.cs new file mode 100644 index 000000000..e2ed769ba --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalCreateUploadRequest.Serialization.cs @@ -0,0 +1,166 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Files +{ + internal partial class InternalCreateUploadRequest : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalCreateUploadRequest)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("filename") != true) + { + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + } + if (SerializedAdditionalRawData?.ContainsKey("purpose") != true) + { + writer.WritePropertyName("purpose"u8); + writer.WriteStringValue(Purpose.ToString()); + } + if (SerializedAdditionalRawData?.ContainsKey("bytes") != true) + { + writer.WritePropertyName("bytes"u8); + writer.WriteNumberValue(Bytes); + } + if (SerializedAdditionalRawData?.ContainsKey("mime_type") != true) + { + writer.WritePropertyName("mime_type"u8); + writer.WriteStringValue(MimeType); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalCreateUploadRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalCreateUploadRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalCreateUploadRequest(document.RootElement, options); + } + + internal static InternalCreateUploadRequest DeserializeInternalCreateUploadRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string filename = default; + InternalCreateUploadRequestPurpose purpose = default; + int bytes = default; + string mimeType = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); + continue; + } + if (property.NameEquals("purpose"u8)) + { + purpose = new InternalCreateUploadRequestPurpose(property.Value.GetString()); + continue; + } + if (property.NameEquals("bytes"u8)) + { + bytes = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("mime_type"u8)) + { + mimeType = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalCreateUploadRequest(filename, purpose, bytes, mimeType, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalCreateUploadRequest)} does not support writing '{options.Format}' format."); + } + } + + InternalCreateUploadRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalCreateUploadRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalCreateUploadRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static InternalCreateUploadRequest FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateUploadRequest(document.RootElement); + } + + internal virtual BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalCreateUploadRequest.cs b/.dotnet/src/Generated/Models/InternalCreateUploadRequest.cs new file mode 100644 index 000000000..f580307a6 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalCreateUploadRequest.cs @@ -0,0 +1,42 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Files +{ + internal partial class InternalCreateUploadRequest + { + internal IDictionary SerializedAdditionalRawData { get; set; } + public InternalCreateUploadRequest(string filename, InternalCreateUploadRequestPurpose purpose, int bytes, string mimeType) + { + Argument.AssertNotNull(filename, nameof(filename)); + Argument.AssertNotNull(mimeType, nameof(mimeType)); + + Filename = filename; + Purpose = purpose; + Bytes = bytes; + MimeType = mimeType; + } + + internal InternalCreateUploadRequest(string filename, InternalCreateUploadRequestPurpose purpose, int bytes, string mimeType, IDictionary serializedAdditionalRawData) + { + Filename = filename; + Purpose = purpose; + Bytes = bytes; + MimeType = mimeType; + SerializedAdditionalRawData = serializedAdditionalRawData; + } + + internal InternalCreateUploadRequest() + { + } + + public string Filename { get; } + public InternalCreateUploadRequestPurpose Purpose { get; } + public int Bytes { get; } + public string MimeType { get; } + } +} diff --git a/.dotnet/src/Generated/Models/InternalCreateUploadRequestPurpose.cs b/.dotnet/src/Generated/Models/InternalCreateUploadRequestPurpose.cs new file mode 100644 index 000000000..6b76958f0 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalCreateUploadRequestPurpose.cs @@ -0,0 +1,40 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace OpenAI.Files +{ + internal readonly partial struct InternalCreateUploadRequestPurpose : IEquatable + { + private readonly string _value; + + public InternalCreateUploadRequestPurpose(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AssistantsValue = "assistants"; + private const string BatchValue = "batch"; + private const string FineTuneValue = "fine-tune"; + private const string VisionValue = "vision"; + + public static InternalCreateUploadRequestPurpose Assistants { get; } = new InternalCreateUploadRequestPurpose(AssistantsValue); + public static InternalCreateUploadRequestPurpose Batch { get; } = new InternalCreateUploadRequestPurpose(BatchValue); + public static InternalCreateUploadRequestPurpose FineTune { get; } = new InternalCreateUploadRequestPurpose(FineTuneValue); + public static InternalCreateUploadRequestPurpose Vision { get; } = new InternalCreateUploadRequestPurpose(VisionValue); + public static bool operator ==(InternalCreateUploadRequestPurpose left, InternalCreateUploadRequestPurpose right) => left.Equals(right); + public static bool operator !=(InternalCreateUploadRequestPurpose left, InternalCreateUploadRequestPurpose right) => !left.Equals(right); + public static implicit operator InternalCreateUploadRequestPurpose(string value) => new InternalCreateUploadRequestPurpose(value); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InternalCreateUploadRequestPurpose other && Equals(other); + public bool Equals(InternalCreateUploadRequestPurpose other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; + } +} diff --git a/.dotnet/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.Serialization.cs b/.dotnet/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.Serialization.cs index e60bfb399..9c1712f3c 100644 --- a/.dotnet/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.Serialization.cs @@ -22,6 +22,18 @@ void IJsonModel.Write(Utf } writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("refusal") != true && Optional.IsDefined(Refusal)) + { + if (Refusal != null) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(Refusal); + } + else + { + writer.WriteNull("refusal"); + } + } if (SerializedAdditionalRawData?.ContainsKey("name") != true && Optional.IsDefined(ParticipantName)) { writer.WritePropertyName("name"u8); @@ -33,7 +45,7 @@ void IJsonModel.Write(Utf writer.WriteStartArray(); foreach (var item in ToolCalls) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } @@ -52,7 +64,7 @@ void IJsonModel.Write(Utf if (SerializedAdditionalRawData?.ContainsKey("role") != true) { writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role); + writer.WriteStringValue(Role.ToSerialString()); } if (SerializedAdditionalRawData?.ContainsKey("content") != true && Optional.IsCollectionDefined(Content)) { @@ -101,15 +113,26 @@ internal static InternalFineTuneChatCompletionRequestAssistantMessage Deserializ { return null; } + string refusal = default; string name = default; IList toolCalls = default; ChatFunctionCall functionCall = default; - string role = default; + ChatMessageRole role = default; IList content = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { + if (property.NameEquals("refusal"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + refusal = null; + continue; + } + refusal = property.Value.GetString(); + continue; + } if (property.NameEquals("name"u8)) { name = property.Value.GetString(); @@ -141,7 +164,7 @@ internal static InternalFineTuneChatCompletionRequestAssistantMessage Deserializ } if (property.NameEquals("role"u8)) { - role = property.Value.GetString(); + role = property.Value.GetString().ToChatMessageRole(); continue; } if (property.NameEquals("content"u8)) @@ -160,6 +183,7 @@ internal static InternalFineTuneChatCompletionRequestAssistantMessage Deserializ role, content ?? new ChangeTrackingList(), serializedAdditionalRawData, + refusal, name, toolCalls ?? new ChangeTrackingList(), functionCall); diff --git a/.dotnet/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.cs b/.dotnet/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.cs index 51139e9f8..e7f33bc58 100644 --- a/.dotnet/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.cs +++ b/.dotnet/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.cs @@ -14,7 +14,7 @@ public InternalFineTuneChatCompletionRequestAssistantMessage() { } - internal InternalFineTuneChatCompletionRequestAssistantMessage(string role, IList content, IDictionary serializedAdditionalRawData, string participantName, IList toolCalls, ChatFunctionCall functionCall) : base(role, content, serializedAdditionalRawData, participantName, toolCalls, functionCall) + internal InternalFineTuneChatCompletionRequestAssistantMessage(ChatMessageRole role, IList content, IDictionary serializedAdditionalRawData, string refusal, string participantName, IList toolCalls, ChatFunctionCall functionCall) : base(role, content, serializedAdditionalRawData, refusal, participantName, toolCalls, functionCall) { } } diff --git a/.dotnet/src/Generated/Models/InternalFineTuningJobHyperparametersNEpochsChoiceEnum.cs b/.dotnet/src/Generated/Models/InternalFineTuningJobHyperparametersNEpochsChoiceEnum.cs new file mode 100644 index 000000000..02f0f0754 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalFineTuningJobHyperparametersNEpochsChoiceEnum.cs @@ -0,0 +1,34 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace OpenAI.FineTuning +{ + internal readonly partial struct InternalFineTuningJobHyperparametersNEpochsChoiceEnum : IEquatable + { + private readonly string _value; + + public InternalFineTuningJobHyperparametersNEpochsChoiceEnum(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + + public static InternalFineTuningJobHyperparametersNEpochsChoiceEnum Auto { get; } = new InternalFineTuningJobHyperparametersNEpochsChoiceEnum(AutoValue); + public static bool operator ==(InternalFineTuningJobHyperparametersNEpochsChoiceEnum left, InternalFineTuningJobHyperparametersNEpochsChoiceEnum right) => left.Equals(right); + public static bool operator !=(InternalFineTuningJobHyperparametersNEpochsChoiceEnum left, InternalFineTuningJobHyperparametersNEpochsChoiceEnum right) => !left.Equals(right); + public static implicit operator InternalFineTuningJobHyperparametersNEpochsChoiceEnum(string value) => new InternalFineTuningJobHyperparametersNEpochsChoiceEnum(value); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InternalFineTuningJobHyperparametersNEpochsChoiceEnum other && Equals(other); + public bool Equals(InternalFineTuningJobHyperparametersNEpochsChoiceEnum other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; + } +} diff --git a/.dotnet/src/Generated/Models/InternalFunctionDefinition.Serialization.cs b/.dotnet/src/Generated/Models/InternalFunctionDefinition.Serialization.cs index 095286f50..57335523d 100644 --- a/.dotnet/src/Generated/Models/InternalFunctionDefinition.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalFunctionDefinition.Serialization.cs @@ -43,6 +43,18 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } #endif } + if (SerializedAdditionalRawData?.ContainsKey("strict") != true && Optional.IsDefined(Strict)) + { + if (Strict != null) + { + writer.WritePropertyName("strict"u8); + writer.WriteBooleanValue(Strict.Value); + } + else + { + writer.WriteNull("strict"); + } + } if (SerializedAdditionalRawData != null) { foreach (var item in SerializedAdditionalRawData) @@ -88,6 +100,7 @@ internal static InternalFunctionDefinition DeserializeInternalFunctionDefinition string description = default; string name = default; BinaryData parameters = default; + bool? strict = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -111,6 +124,16 @@ internal static InternalFunctionDefinition DeserializeInternalFunctionDefinition parameters = BinaryData.FromString(property.Value.GetRawText()); continue; } + if (property.NameEquals("strict"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + strict = null; + continue; + } + strict = property.Value.GetBoolean(); + continue; + } if (true) { rawDataDictionary ??= new Dictionary(); @@ -118,7 +141,7 @@ internal static InternalFunctionDefinition DeserializeInternalFunctionDefinition } } serializedAdditionalRawData = rawDataDictionary; - return new InternalFunctionDefinition(description, name, parameters, serializedAdditionalRawData); + return new InternalFunctionDefinition(description, name, parameters, strict, serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/.dotnet/src/Generated/Models/InternalFunctionDefinition.cs b/.dotnet/src/Generated/Models/InternalFunctionDefinition.cs index 836a40e4b..9e385deb8 100644 --- a/.dotnet/src/Generated/Models/InternalFunctionDefinition.cs +++ b/.dotnet/src/Generated/Models/InternalFunctionDefinition.cs @@ -17,11 +17,12 @@ public InternalFunctionDefinition(string name) Name = name; } - internal InternalFunctionDefinition(string description, string name, BinaryData parameters, IDictionary serializedAdditionalRawData) + internal InternalFunctionDefinition(string description, string name, BinaryData parameters, bool? strict, IDictionary serializedAdditionalRawData) { Description = description; Name = name; Parameters = parameters; + Strict = strict; SerializedAdditionalRawData = serializedAdditionalRawData; } @@ -31,5 +32,6 @@ internal InternalFunctionDefinition() public string Description { get; set; } public string Name { get; set; } + public bool? Strict { get; set; } } } diff --git a/.dotnet/src/Generated/Models/InternalMessageContentRefusalObjectType.cs b/.dotnet/src/Generated/Models/InternalMessageContentRefusalObjectType.cs new file mode 100644 index 000000000..7a127f292 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalMessageContentRefusalObjectType.cs @@ -0,0 +1,34 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace OpenAI.Assistants +{ + internal readonly partial struct InternalMessageContentRefusalObjectType : IEquatable + { + private readonly string _value; + + public InternalMessageContentRefusalObjectType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string RefusalValue = "refusal"; + + public static InternalMessageContentRefusalObjectType Refusal { get; } = new InternalMessageContentRefusalObjectType(RefusalValue); + public static bool operator ==(InternalMessageContentRefusalObjectType left, InternalMessageContentRefusalObjectType right) => left.Equals(right); + public static bool operator !=(InternalMessageContentRefusalObjectType left, InternalMessageContentRefusalObjectType right) => !left.Equals(right); + public static implicit operator InternalMessageContentRefusalObjectType(string value) => new InternalMessageContentRefusalObjectType(value); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InternalMessageContentRefusalObjectType other && Equals(other); + public bool Equals(InternalMessageContentRefusalObjectType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; + } +} diff --git a/.dotnet/src/Generated/Models/InternalMessageDeltaContent.Serialization.cs b/.dotnet/src/Generated/Models/InternalMessageDeltaContent.Serialization.cs index b8ac6343c..7b0d037e3 100644 --- a/.dotnet/src/Generated/Models/InternalMessageDeltaContent.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalMessageDeltaContent.Serialization.cs @@ -74,6 +74,7 @@ internal static InternalMessageDeltaContent DeserializeInternalMessageDeltaConte { case "image_file": return InternalMessageDeltaContentImageFileObject.DeserializeInternalMessageDeltaContentImageFileObject(element, options); case "image_url": return InternalMessageDeltaContentImageUrlObject.DeserializeInternalMessageDeltaContentImageUrlObject(element, options); + case "refusal": return InternalMessageDeltaContentRefusalObject.DeserializeInternalMessageDeltaContentRefusalObject(element, options); case "text": return InternalMessageDeltaContentTextObject.DeserializeInternalMessageDeltaContentTextObject(element, options); } } diff --git a/.dotnet/src/Generated/Models/InternalMessageDeltaContentRefusalObject.Serialization.cs b/.dotnet/src/Generated/Models/InternalMessageDeltaContentRefusalObject.Serialization.cs new file mode 100644 index 000000000..1668fc35c --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalMessageDeltaContentRefusalObject.Serialization.cs @@ -0,0 +1,155 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Assistants +{ + internal partial class InternalMessageDeltaContentRefusalObject : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalMessageDeltaContentRefusalObject)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("index") != true) + { + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + } + if (SerializedAdditionalRawData?.ContainsKey("refusal") != true && Optional.IsDefined(Refusal)) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(Refusal); + } + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalMessageDeltaContentRefusalObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalMessageDeltaContentRefusalObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalMessageDeltaContentRefusalObject(document.RootElement, options); + } + + internal static InternalMessageDeltaContentRefusalObject DeserializeInternalMessageDeltaContentRefusalObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int index = default; + string refusal = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("refusal"u8)) + { + refusal = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalMessageDeltaContentRefusalObject(type, serializedAdditionalRawData, index, refusal); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalMessageDeltaContentRefusalObject)} does not support writing '{options.Format}' format."); + } + } + + InternalMessageDeltaContentRefusalObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalMessageDeltaContentRefusalObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalMessageDeltaContentRefusalObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static new InternalMessageDeltaContentRefusalObject FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaContentRefusalObject(document.RootElement); + } + + internal override BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalMessageDeltaContentRefusalObject.cs b/.dotnet/src/Generated/Models/InternalMessageDeltaContentRefusalObject.cs new file mode 100644 index 000000000..d7b88a830 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalMessageDeltaContentRefusalObject.cs @@ -0,0 +1,31 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Assistants +{ + internal partial class InternalMessageDeltaContentRefusalObject : InternalMessageDeltaContent + { + internal InternalMessageDeltaContentRefusalObject(int index) + { + Type = "refusal"; + Index = index; + } + + internal InternalMessageDeltaContentRefusalObject(string type, IDictionary serializedAdditionalRawData, int index, string refusal) : base(type, serializedAdditionalRawData) + { + Index = index; + Refusal = refusal; + } + + internal InternalMessageDeltaContentRefusalObject() + { + } + + public int Index { get; } + public string Refusal { get; } + } +} diff --git a/.dotnet/src/Generated/Models/InternalMessageRefusalContent.Serialization.cs b/.dotnet/src/Generated/Models/InternalMessageRefusalContent.Serialization.cs new file mode 100644 index 000000000..6e3c9846f --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalMessageRefusalContent.Serialization.cs @@ -0,0 +1,103 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Assistants +{ + internal partial class InternalMessageRefusalContent : IJsonModel + { + InternalMessageRefusalContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalMessageRefusalContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalMessageRefusalContent(document.RootElement, options); + } + + internal static InternalMessageRefusalContent DeserializeInternalMessageRefusalContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = default; + string refusal = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (property.NameEquals("refusal"u8)) + { + refusal = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalMessageRefusalContent(serializedAdditionalRawData, type, refusal); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalMessageRefusalContent)} does not support writing '{options.Format}' format."); + } + } + + InternalMessageRefusalContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalMessageRefusalContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalMessageRefusalContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static new InternalMessageRefusalContent FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageRefusalContent(document.RootElement); + } + + internal override BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalMessageRefusalContent.cs b/.dotnet/src/Generated/Models/InternalMessageRefusalContent.cs new file mode 100644 index 000000000..dc6f0e0af --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalMessageRefusalContent.cs @@ -0,0 +1,29 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Assistants +{ + internal partial class InternalMessageRefusalContent : MessageContent + { + public InternalMessageRefusalContent(string internalRefusal) + { + Argument.AssertNotNull(internalRefusal, nameof(internalRefusal)); + + InternalRefusal = internalRefusal; + } + + internal InternalMessageRefusalContent(IDictionary serializedAdditionalRawData, string type, string internalRefusal) : base(serializedAdditionalRawData) + { + _type = type; + InternalRefusal = internalRefusal; + } + + internal InternalMessageRefusalContent() + { + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResources.Serialization.cs b/.dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResources.Serialization.cs index 7c0d6a685..bb4a89610 100644 --- a/.dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResources.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResources.Serialization.cs @@ -74,7 +74,7 @@ internal static InternalModifyAssistantRequestToolResources DeserializeInternalM return null; } InternalModifyAssistantRequestToolResourcesCodeInterpreter codeInterpreter = default; - InternalModifyAssistantRequestToolResourcesFileSearch fileSearch = default; + InternalToolResourcesFileSearchIdsOnly fileSearch = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -94,7 +94,7 @@ internal static InternalModifyAssistantRequestToolResources DeserializeInternalM { continue; } - fileSearch = InternalModifyAssistantRequestToolResourcesFileSearch.DeserializeInternalModifyAssistantRequestToolResourcesFileSearch(property.Value, options); + fileSearch = InternalToolResourcesFileSearchIdsOnly.DeserializeInternalToolResourcesFileSearchIdsOnly(property.Value, options); continue; } if (true) diff --git a/.dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResources.cs b/.dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResources.cs index 5aa4a77d8..3bcf4c24d 100644 --- a/.dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResources.cs +++ b/.dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResources.cs @@ -14,7 +14,7 @@ public InternalModifyAssistantRequestToolResources() { } - internal InternalModifyAssistantRequestToolResources(InternalModifyAssistantRequestToolResourcesCodeInterpreter codeInterpreter, InternalModifyAssistantRequestToolResourcesFileSearch fileSearch, IDictionary serializedAdditionalRawData) + internal InternalModifyAssistantRequestToolResources(InternalModifyAssistantRequestToolResourcesCodeInterpreter codeInterpreter, InternalToolResourcesFileSearchIdsOnly fileSearch, IDictionary serializedAdditionalRawData) { CodeInterpreter = codeInterpreter; FileSearch = fileSearch; @@ -22,6 +22,6 @@ internal InternalModifyAssistantRequestToolResources(InternalModifyAssistantRequ } public InternalModifyAssistantRequestToolResourcesCodeInterpreter CodeInterpreter { get; set; } - public InternalModifyAssistantRequestToolResourcesFileSearch FileSearch { get; set; } + public InternalToolResourcesFileSearchIdsOnly FileSearch { get; set; } } } diff --git a/.dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResourcesFileSearch.cs b/.dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResourcesFileSearch.cs deleted file mode 100644 index e9b82d57a..000000000 --- a/.dotnet/src/Generated/Models/InternalModifyAssistantRequestToolResourcesFileSearch.cs +++ /dev/null @@ -1,26 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace OpenAI.Assistants -{ - internal partial class InternalModifyAssistantRequestToolResourcesFileSearch - { - internal IDictionary SerializedAdditionalRawData { get; set; } - public InternalModifyAssistantRequestToolResourcesFileSearch() - { - VectorStoreIds = new ChangeTrackingList(); - } - - internal InternalModifyAssistantRequestToolResourcesFileSearch(IList vectorStoreIds, IDictionary serializedAdditionalRawData) - { - VectorStoreIds = vectorStoreIds; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - public IList VectorStoreIds { get; } - } -} diff --git a/.dotnet/src/Generated/Models/InternalModifyThreadRequestToolResources.Serialization.cs b/.dotnet/src/Generated/Models/InternalModifyThreadRequestToolResources.Serialization.cs index af74f65f2..3354accf3 100644 --- a/.dotnet/src/Generated/Models/InternalModifyThreadRequestToolResources.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalModifyThreadRequestToolResources.Serialization.cs @@ -74,7 +74,7 @@ internal static InternalModifyThreadRequestToolResources DeserializeInternalModi return null; } InternalModifyThreadRequestToolResourcesCodeInterpreter codeInterpreter = default; - InternalModifyThreadRequestToolResourcesFileSearch fileSearch = default; + InternalToolResourcesFileSearchIdsOnly fileSearch = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -94,7 +94,7 @@ internal static InternalModifyThreadRequestToolResources DeserializeInternalModi { continue; } - fileSearch = InternalModifyThreadRequestToolResourcesFileSearch.DeserializeInternalModifyThreadRequestToolResourcesFileSearch(property.Value, options); + fileSearch = InternalToolResourcesFileSearchIdsOnly.DeserializeInternalToolResourcesFileSearchIdsOnly(property.Value, options); continue; } if (true) diff --git a/.dotnet/src/Generated/Models/InternalModifyThreadRequestToolResources.cs b/.dotnet/src/Generated/Models/InternalModifyThreadRequestToolResources.cs index 0d8078ba4..0876ba2de 100644 --- a/.dotnet/src/Generated/Models/InternalModifyThreadRequestToolResources.cs +++ b/.dotnet/src/Generated/Models/InternalModifyThreadRequestToolResources.cs @@ -14,7 +14,7 @@ public InternalModifyThreadRequestToolResources() { } - internal InternalModifyThreadRequestToolResources(InternalModifyThreadRequestToolResourcesCodeInterpreter codeInterpreter, InternalModifyThreadRequestToolResourcesFileSearch fileSearch, IDictionary serializedAdditionalRawData) + internal InternalModifyThreadRequestToolResources(InternalModifyThreadRequestToolResourcesCodeInterpreter codeInterpreter, InternalToolResourcesFileSearchIdsOnly fileSearch, IDictionary serializedAdditionalRawData) { CodeInterpreter = codeInterpreter; FileSearch = fileSearch; @@ -22,6 +22,6 @@ internal InternalModifyThreadRequestToolResources(InternalModifyThreadRequestToo } public InternalModifyThreadRequestToolResourcesCodeInterpreter CodeInterpreter { get; set; } - public InternalModifyThreadRequestToolResourcesFileSearch FileSearch { get; set; } + public InternalToolResourcesFileSearchIdsOnly FileSearch { get; set; } } } diff --git a/.dotnet/src/Generated/Models/InternalOmniTypedResponseFormat.Serialization.cs b/.dotnet/src/Generated/Models/InternalOmniTypedResponseFormat.Serialization.cs new file mode 100644 index 000000000..6ccf09de3 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalOmniTypedResponseFormat.Serialization.cs @@ -0,0 +1,125 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Text.Json; + +namespace OpenAI.Internal +{ + [PersistableModelProxy(typeof(InternalUnknownOmniTypedResponseFormat))] + internal partial class InternalOmniTypedResponseFormat : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalOmniTypedResponseFormat)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalOmniTypedResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalOmniTypedResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalOmniTypedResponseFormat(document.RootElement, options); + } + + internal static InternalOmniTypedResponseFormat DeserializeInternalOmniTypedResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "json_object": return InternalResponseFormatJsonObject.DeserializeInternalResponseFormatJsonObject(element, options); + case "json_schema": return InternalResponseFormatJsonSchema.DeserializeInternalResponseFormatJsonSchema(element, options); + case "text": return InternalResponseFormatText.DeserializeInternalResponseFormatText(element, options); + } + } + return InternalUnknownOmniTypedResponseFormat.DeserializeInternalUnknownOmniTypedResponseFormat(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalOmniTypedResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + InternalOmniTypedResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalOmniTypedResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalOmniTypedResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static InternalOmniTypedResponseFormat FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalOmniTypedResponseFormat(document.RootElement); + } + + internal virtual BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalOmniTypedResponseFormat.cs b/.dotnet/src/Generated/Models/InternalOmniTypedResponseFormat.cs new file mode 100644 index 000000000..da255f506 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalOmniTypedResponseFormat.cs @@ -0,0 +1,25 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Internal +{ + internal abstract partial class InternalOmniTypedResponseFormat + { + internal IDictionary SerializedAdditionalRawData { get; set; } + protected InternalOmniTypedResponseFormat() + { + } + + internal InternalOmniTypedResponseFormat(string type, IDictionary serializedAdditionalRawData) + { + Type = type; + SerializedAdditionalRawData = serializedAdditionalRawData; + } + + internal string Type { get; set; } + } +} diff --git a/.dotnet/src/Generated/Models/InternalResponseFormatJsonObject.Serialization.cs b/.dotnet/src/Generated/Models/InternalResponseFormatJsonObject.Serialization.cs new file mode 100644 index 000000000..66e2b97f1 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalResponseFormatJsonObject.Serialization.cs @@ -0,0 +1,133 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Internal +{ + internal partial class InternalResponseFormatJsonObject : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalResponseFormatJsonObject)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalResponseFormatJsonObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalResponseFormatJsonObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalResponseFormatJsonObject(document.RootElement, options); + } + + internal static InternalResponseFormatJsonObject DeserializeInternalResponseFormatJsonObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalResponseFormatJsonObject(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalResponseFormatJsonObject)} does not support writing '{options.Format}' format."); + } + } + + InternalResponseFormatJsonObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalResponseFormatJsonObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalResponseFormatJsonObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static new InternalResponseFormatJsonObject FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalResponseFormatJsonObject(document.RootElement); + } + + internal override BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalResponseFormatJsonObject.cs b/.dotnet/src/Generated/Models/InternalResponseFormatJsonObject.cs new file mode 100644 index 000000000..b62b1891f --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalResponseFormatJsonObject.cs @@ -0,0 +1,21 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Internal +{ + internal partial class InternalResponseFormatJsonObject : InternalOmniTypedResponseFormat + { + public InternalResponseFormatJsonObject() + { + Type = "json_object"; + } + + internal InternalResponseFormatJsonObject(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchema.Serialization.cs b/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchema.Serialization.cs new file mode 100644 index 000000000..1746508f2 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchema.Serialization.cs @@ -0,0 +1,144 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Internal +{ + internal partial class InternalResponseFormatJsonSchema : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchema)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("json_schema") != true) + { + writer.WritePropertyName("json_schema"u8); + writer.WriteObjectValue(JsonSchema, options); + } + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalResponseFormatJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchema)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalResponseFormatJsonSchema(document.RootElement, options); + } + + internal static InternalResponseFormatJsonSchema DeserializeInternalResponseFormatJsonSchema(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + InternalResponseFormatJsonSchemaJsonSchema jsonSchema = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("json_schema"u8)) + { + jsonSchema = InternalResponseFormatJsonSchemaJsonSchema.DeserializeInternalResponseFormatJsonSchemaJsonSchema(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalResponseFormatJsonSchema(type, serializedAdditionalRawData, jsonSchema); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchema)} does not support writing '{options.Format}' format."); + } + } + + InternalResponseFormatJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalResponseFormatJsonSchema(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchema)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static new InternalResponseFormatJsonSchema FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalResponseFormatJsonSchema(document.RootElement); + } + + internal override BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchema.cs b/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchema.cs new file mode 100644 index 000000000..739eb22b9 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchema.cs @@ -0,0 +1,31 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Internal +{ + internal partial class InternalResponseFormatJsonSchema : InternalOmniTypedResponseFormat + { + public InternalResponseFormatJsonSchema(InternalResponseFormatJsonSchemaJsonSchema jsonSchema) + { + Argument.AssertNotNull(jsonSchema, nameof(jsonSchema)); + + Type = "json_schema"; + JsonSchema = jsonSchema; + } + + internal InternalResponseFormatJsonSchema(string type, IDictionary serializedAdditionalRawData, InternalResponseFormatJsonSchemaJsonSchema jsonSchema) : base(type, serializedAdditionalRawData) + { + JsonSchema = jsonSchema; + } + + internal InternalResponseFormatJsonSchema() + { + } + + public InternalResponseFormatJsonSchemaJsonSchema JsonSchema { get; set; } + } +} diff --git a/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.Serialization.cs b/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.Serialization.cs new file mode 100644 index 000000000..5b9c4d930 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.Serialization.cs @@ -0,0 +1,189 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Internal +{ + internal partial class InternalResponseFormatJsonSchemaJsonSchema : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchemaJsonSchema)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("description") != true && Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + if (SerializedAdditionalRawData?.ContainsKey("name") != true) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (SerializedAdditionalRawData?.ContainsKey("schema") != true && Optional.IsDefined(Schema)) + { + writer.WritePropertyName("schema"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Schema); +#else + using (JsonDocument document = JsonDocument.Parse(Schema)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (SerializedAdditionalRawData?.ContainsKey("strict") != true && Optional.IsDefined(Strict)) + { + if (Strict != null) + { + writer.WritePropertyName("strict"u8); + writer.WriteBooleanValue(Strict.Value); + } + else + { + writer.WriteNull("strict"); + } + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalResponseFormatJsonSchemaJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchemaJsonSchema)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalResponseFormatJsonSchemaJsonSchema(document.RootElement, options); + } + + internal static InternalResponseFormatJsonSchemaJsonSchema DeserializeInternalResponseFormatJsonSchemaJsonSchema(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string description = default; + string name = default; + BinaryData schema = default; + bool? strict = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("schema"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + schema = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("strict"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + strict = null; + continue; + } + strict = property.Value.GetBoolean(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalResponseFormatJsonSchemaJsonSchema(description, name, schema, strict, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchemaJsonSchema)} does not support writing '{options.Format}' format."); + } + } + + InternalResponseFormatJsonSchemaJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalResponseFormatJsonSchemaJsonSchema(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchemaJsonSchema)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static InternalResponseFormatJsonSchemaJsonSchema FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalResponseFormatJsonSchemaJsonSchema(document.RootElement); + } + + internal virtual BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.cs b/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.cs new file mode 100644 index 000000000..533d36db0 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.cs @@ -0,0 +1,37 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Internal +{ + internal partial class InternalResponseFormatJsonSchemaJsonSchema + { + internal IDictionary SerializedAdditionalRawData { get; set; } + public InternalResponseFormatJsonSchemaJsonSchema(string name) + { + Argument.AssertNotNull(name, nameof(name)); + + Name = name; + } + + internal InternalResponseFormatJsonSchemaJsonSchema(string description, string name, BinaryData schema, bool? strict, IDictionary serializedAdditionalRawData) + { + Description = description; + Name = name; + Schema = schema; + Strict = strict; + SerializedAdditionalRawData = serializedAdditionalRawData; + } + + internal InternalResponseFormatJsonSchemaJsonSchema() + { + } + + public string Description { get; set; } + public string Name { get; set; } + public bool? Strict { get; set; } + } +} diff --git a/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.Serialization.cs b/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.Serialization.cs new file mode 100644 index 000000000..d77918543 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.Serialization.cs @@ -0,0 +1,111 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Internal +{ + internal partial class InternalResponseFormatJsonSchemaSchema : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchemaSchema)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + foreach (var item in AdditionalProperties) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + writer.WriteEndObject(); + } + + InternalResponseFormatJsonSchemaSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchemaSchema)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalResponseFormatJsonSchemaSchema(document.RootElement, options); + } + + internal static InternalResponseFormatJsonSchemaSchema DeserializeInternalResponseFormatJsonSchemaSchema(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IDictionary additionalProperties = default; + Dictionary additionalPropertiesDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + additionalPropertiesDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + additionalProperties = additionalPropertiesDictionary; + return new InternalResponseFormatJsonSchemaSchema(additionalProperties); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchemaSchema)} does not support writing '{options.Format}' format."); + } + } + + InternalResponseFormatJsonSchemaSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalResponseFormatJsonSchemaSchema(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchemaSchema)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static InternalResponseFormatJsonSchemaSchema FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalResponseFormatJsonSchemaSchema(document.RootElement); + } + + internal virtual BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.cs b/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.cs new file mode 100644 index 000000000..d00500adb --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.cs @@ -0,0 +1,24 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Internal +{ + internal partial class InternalResponseFormatJsonSchemaSchema + { + public InternalResponseFormatJsonSchemaSchema() + { + AdditionalProperties = new ChangeTrackingDictionary(); + } + + internal InternalResponseFormatJsonSchemaSchema(IDictionary additionalProperties) + { + AdditionalProperties = additionalProperties; + } + + public IDictionary AdditionalProperties { get; } + } +} diff --git a/.dotnet/src/Generated/Models/InternalResponseFormatText.Serialization.cs b/.dotnet/src/Generated/Models/InternalResponseFormatText.Serialization.cs new file mode 100644 index 000000000..b213da2e7 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalResponseFormatText.Serialization.cs @@ -0,0 +1,133 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Internal +{ + internal partial class InternalResponseFormatText : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalResponseFormatText)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalResponseFormatText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalResponseFormatText)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalResponseFormatText(document.RootElement, options); + } + + internal static InternalResponseFormatText DeserializeInternalResponseFormatText(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalResponseFormatText(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalResponseFormatText)} does not support writing '{options.Format}' format."); + } + } + + InternalResponseFormatText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalResponseFormatText(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalResponseFormatText)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static new InternalResponseFormatText FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalResponseFormatText(document.RootElement); + } + + internal override BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalResponseFormatText.cs b/.dotnet/src/Generated/Models/InternalResponseFormatText.cs new file mode 100644 index 000000000..efe4d6fce --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalResponseFormatText.cs @@ -0,0 +1,21 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Internal +{ + internal partial class InternalResponseFormatText : InternalOmniTypedResponseFormat + { + public InternalResponseFormatText() + { + Type = "text"; + } + + internal InternalResponseFormatText(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalModifyThreadRequestToolResourcesFileSearch.Serialization.cs b/.dotnet/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.Serialization.cs similarity index 62% rename from .dotnet/src/Generated/Models/InternalModifyThreadRequestToolResourcesFileSearch.Serialization.cs rename to .dotnet/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.Serialization.cs index 9aa936c8e..3b188f3b2 100644 --- a/.dotnet/src/Generated/Models/InternalModifyThreadRequestToolResourcesFileSearch.Serialization.cs +++ b/.dotnet/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.Serialization.cs @@ -10,14 +10,14 @@ namespace OpenAI.Assistants { - internal partial class InternalModifyThreadRequestToolResourcesFileSearch : IJsonModel + internal partial class InternalToolResourcesFileSearchIdsOnly : IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalModifyThreadRequestToolResourcesFileSearch)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(InternalToolResourcesFileSearchIdsOnly)} does not support writing '{format}' format."); } writer.WriteStartObject(); @@ -53,19 +53,19 @@ void IJsonModel.Write(Utf8Js writer.WriteEndObject(); } - InternalModifyThreadRequestToolResourcesFileSearch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalToolResourcesFileSearchIdsOnly IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalModifyThreadRequestToolResourcesFileSearch)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalToolResourcesFileSearchIdsOnly)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalModifyThreadRequestToolResourcesFileSearch(document.RootElement, options); + return DeserializeInternalToolResourcesFileSearchIdsOnly(document.RootElement, options); } - internal static InternalModifyThreadRequestToolResourcesFileSearch DeserializeInternalModifyThreadRequestToolResourcesFileSearch(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalToolResourcesFileSearchIdsOnly DeserializeInternalToolResourcesFileSearchIdsOnly(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -99,44 +99,44 @@ internal static InternalModifyThreadRequestToolResourcesFileSearch DeserializeIn } } serializedAdditionalRawData = rawDataDictionary; - return new InternalModifyThreadRequestToolResourcesFileSearch(vectorStoreIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalToolResourcesFileSearchIdsOnly(vectorStoreIds ?? new ChangeTrackingList(), serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(InternalModifyThreadRequestToolResourcesFileSearch)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(InternalToolResourcesFileSearchIdsOnly)} does not support writing '{options.Format}' format."); } } - InternalModifyThreadRequestToolResourcesFileSearch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + InternalToolResourcesFileSearchIdsOnly IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data); - return DeserializeInternalModifyThreadRequestToolResourcesFileSearch(document.RootElement, options); + return DeserializeInternalToolResourcesFileSearchIdsOnly(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalModifyThreadRequestToolResourcesFileSearch)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(InternalToolResourcesFileSearchIdsOnly)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalModifyThreadRequestToolResourcesFileSearch FromResponse(PipelineResponse response) + internal static InternalToolResourcesFileSearchIdsOnly FromResponse(PipelineResponse response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalModifyThreadRequestToolResourcesFileSearch(document.RootElement); + return DeserializeInternalToolResourcesFileSearchIdsOnly(document.RootElement); } internal virtual BinaryContent ToBinaryContent() diff --git a/.dotnet/src/Generated/Models/InternalModifyThreadRequestToolResourcesFileSearch.cs b/.dotnet/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.cs similarity index 62% rename from .dotnet/src/Generated/Models/InternalModifyThreadRequestToolResourcesFileSearch.cs rename to .dotnet/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.cs index f87c6ace1..33ed0185e 100644 --- a/.dotnet/src/Generated/Models/InternalModifyThreadRequestToolResourcesFileSearch.cs +++ b/.dotnet/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.cs @@ -7,15 +7,15 @@ namespace OpenAI.Assistants { - internal partial class InternalModifyThreadRequestToolResourcesFileSearch + internal partial class InternalToolResourcesFileSearchIdsOnly { internal IDictionary SerializedAdditionalRawData { get; set; } - public InternalModifyThreadRequestToolResourcesFileSearch() + public InternalToolResourcesFileSearchIdsOnly() { VectorStoreIds = new ChangeTrackingList(); } - internal InternalModifyThreadRequestToolResourcesFileSearch(IList vectorStoreIds, IDictionary serializedAdditionalRawData) + internal InternalToolResourcesFileSearchIdsOnly(IList vectorStoreIds, IDictionary serializedAdditionalRawData) { VectorStoreIds = vectorStoreIds; SerializedAdditionalRawData = serializedAdditionalRawData; diff --git a/.dotnet/src/Generated/Models/InternalUnknownAssistantResponseFormat.Serialization.cs b/.dotnet/src/Generated/Models/InternalUnknownAssistantResponseFormat.Serialization.cs new file mode 100644 index 000000000..ff9e4c05e --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalUnknownAssistantResponseFormat.Serialization.cs @@ -0,0 +1,122 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Assistants +{ + internal partial class InternalUnknownAssistantResponseFormat : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantResponseFormat)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + AssistantResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAssistantResponseFormat(document.RootElement, options); + } + + internal static InternalUnknownAssistantResponseFormat DeserializeInternalUnknownAssistantResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalUnknownAssistantResponseFormat(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AssistantResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + AssistantResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeAssistantResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AssistantResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/.dotnet/src/Generated/Models/InternalUnknownAssistantResponseFormat.cs b/.dotnet/src/Generated/Models/InternalUnknownAssistantResponseFormat.cs new file mode 100644 index 000000000..13ee16c7d --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalUnknownAssistantResponseFormat.cs @@ -0,0 +1,20 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Assistants +{ + internal partial class InternalUnknownAssistantResponseFormat : AssistantResponseFormat + { + internal InternalUnknownAssistantResponseFormat(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + internal InternalUnknownAssistantResponseFormat() + { + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalUnknownChatResponseFormat.Serialization.cs b/.dotnet/src/Generated/Models/InternalUnknownChatResponseFormat.Serialization.cs new file mode 100644 index 000000000..0bc64d31b --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalUnknownChatResponseFormat.Serialization.cs @@ -0,0 +1,133 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Chat +{ + internal partial class InternalUnknownChatResponseFormat : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatResponseFormat)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + ChatResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatResponseFormat(document.RootElement, options); + } + + internal static InternalUnknownChatResponseFormat DeserializeInternalUnknownChatResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalUnknownChatResponseFormat(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + ChatResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeChatResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static new InternalUnknownChatResponseFormat FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalUnknownChatResponseFormat(document.RootElement); + } + + internal override BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalUnknownChatResponseFormat.cs b/.dotnet/src/Generated/Models/InternalUnknownChatResponseFormat.cs new file mode 100644 index 000000000..e3def713f --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalUnknownChatResponseFormat.cs @@ -0,0 +1,20 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Chat +{ + internal partial class InternalUnknownChatResponseFormat : ChatResponseFormat + { + internal InternalUnknownChatResponseFormat(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + internal InternalUnknownChatResponseFormat() + { + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.Serialization.cs b/.dotnet/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.Serialization.cs new file mode 100644 index 000000000..43b17f909 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.Serialization.cs @@ -0,0 +1,133 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Internal +{ + internal partial class InternalUnknownOmniTypedResponseFormat : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalOmniTypedResponseFormat)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalOmniTypedResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalOmniTypedResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalOmniTypedResponseFormat(document.RootElement, options); + } + + internal static InternalUnknownOmniTypedResponseFormat DeserializeInternalUnknownOmniTypedResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalUnknownOmniTypedResponseFormat(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalOmniTypedResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + InternalOmniTypedResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalOmniTypedResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalOmniTypedResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static new InternalUnknownOmniTypedResponseFormat FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalUnknownOmniTypedResponseFormat(document.RootElement); + } + + internal override BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.cs b/.dotnet/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.cs new file mode 100644 index 000000000..8ae4808ff --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.cs @@ -0,0 +1,20 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Internal +{ + internal partial class InternalUnknownOmniTypedResponseFormat : InternalOmniTypedResponseFormat + { + internal InternalUnknownOmniTypedResponseFormat(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + internal InternalUnknownOmniTypedResponseFormat() + { + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalUpload.Serialization.cs b/.dotnet/src/Generated/Models/InternalUpload.Serialization.cs new file mode 100644 index 000000000..6b2b8604d --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalUpload.Serialization.cs @@ -0,0 +1,247 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Files +{ + internal partial class InternalUpload : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalUpload)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("id") != true) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + { + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + } + if (SerializedAdditionalRawData?.ContainsKey("filename") != true) + { + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + } + if (SerializedAdditionalRawData?.ContainsKey("bytes") != true) + { + writer.WritePropertyName("bytes"u8); + writer.WriteNumberValue(Bytes); + } + if (SerializedAdditionalRawData?.ContainsKey("purpose") != true) + { + writer.WritePropertyName("purpose"u8); + writer.WriteStringValue(Purpose); + } + if (SerializedAdditionalRawData?.ContainsKey("status") != true) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + } + if (SerializedAdditionalRawData?.ContainsKey("expires_at") != true) + { + writer.WritePropertyName("expires_at"u8); + writer.WriteNumberValue(ExpiresAt, "U"); + } + if (SerializedAdditionalRawData?.ContainsKey("object") != true && Optional.IsDefined(Object)) + { + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.Value.ToString()); + } + if (SerializedAdditionalRawData?.ContainsKey("file") != true && Optional.IsDefined(File)) + { + if (File != null) + { + writer.WritePropertyName("file"u8); + writer.WriteObjectValue(File, options); + } + else + { + writer.WriteNull("file"); + } + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalUpload IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalUpload)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalUpload(document.RootElement, options); + } + + internal static InternalUpload DeserializeInternalUpload(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + DateTimeOffset createdAt = default; + string filename = default; + int bytes = default; + string purpose = default; + InternalUploadStatus status = default; + DateTimeOffset expiresAt = default; + InternalUploadObject? @object = default; + OpenAIFileInfo file = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); + continue; + } + if (property.NameEquals("bytes"u8)) + { + bytes = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("purpose"u8)) + { + purpose = property.Value.GetString(); + continue; + } + if (property.NameEquals("status"u8)) + { + status = new InternalUploadStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("expires_at"u8)) + { + expiresAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("object"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + @object = new InternalUploadObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("file"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + file = null; + continue; + } + file = OpenAIFileInfo.DeserializeOpenAIFileInfo(property.Value, options); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalUpload( + id, + createdAt, + filename, + bytes, + purpose, + status, + expiresAt, + @object, + file, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalUpload)} does not support writing '{options.Format}' format."); + } + } + + InternalUpload IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalUpload(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalUpload)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static InternalUpload FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalUpload(document.RootElement); + } + + internal virtual BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalUpload.cs b/.dotnet/src/Generated/Models/InternalUpload.cs new file mode 100644 index 000000000..fb464dedd --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalUpload.cs @@ -0,0 +1,56 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Files +{ + internal partial class InternalUpload + { + internal IDictionary SerializedAdditionalRawData { get; set; } + internal InternalUpload(string id, DateTimeOffset createdAt, string filename, int bytes, string purpose, InternalUploadStatus status, DateTimeOffset expiresAt) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(filename, nameof(filename)); + Argument.AssertNotNull(purpose, nameof(purpose)); + + Id = id; + CreatedAt = createdAt; + Filename = filename; + Bytes = bytes; + Purpose = purpose; + Status = status; + ExpiresAt = expiresAt; + } + + internal InternalUpload(string id, DateTimeOffset createdAt, string filename, int bytes, string purpose, InternalUploadStatus status, DateTimeOffset expiresAt, InternalUploadObject? @object, OpenAIFileInfo file, IDictionary serializedAdditionalRawData) + { + Id = id; + CreatedAt = createdAt; + Filename = filename; + Bytes = bytes; + Purpose = purpose; + Status = status; + ExpiresAt = expiresAt; + Object = @object; + File = file; + SerializedAdditionalRawData = serializedAdditionalRawData; + } + + internal InternalUpload() + { + } + + public string Id { get; } + public DateTimeOffset CreatedAt { get; } + public string Filename { get; } + public int Bytes { get; } + public string Purpose { get; } + public InternalUploadStatus Status { get; } + public DateTimeOffset ExpiresAt { get; } + public InternalUploadObject? Object { get; } + public OpenAIFileInfo File { get; } + } +} diff --git a/.dotnet/src/Generated/Models/InternalUploadObject.cs b/.dotnet/src/Generated/Models/InternalUploadObject.cs new file mode 100644 index 000000000..9dacd622a --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalUploadObject.cs @@ -0,0 +1,34 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace OpenAI.Files +{ + internal readonly partial struct InternalUploadObject : IEquatable + { + private readonly string _value; + + public InternalUploadObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UploadValue = "upload"; + + public static InternalUploadObject Upload { get; } = new InternalUploadObject(UploadValue); + public static bool operator ==(InternalUploadObject left, InternalUploadObject right) => left.Equals(right); + public static bool operator !=(InternalUploadObject left, InternalUploadObject right) => !left.Equals(right); + public static implicit operator InternalUploadObject(string value) => new InternalUploadObject(value); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InternalUploadObject other && Equals(other); + public bool Equals(InternalUploadObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; + } +} diff --git a/.dotnet/src/Generated/Models/InternalUploadPart.Serialization.cs b/.dotnet/src/Generated/Models/InternalUploadPart.Serialization.cs new file mode 100644 index 000000000..c6f4c77f8 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalUploadPart.Serialization.cs @@ -0,0 +1,166 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; + +namespace OpenAI.Files +{ + internal partial class InternalUploadPart : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalUploadPart)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("id") != true) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + { + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + } + if (SerializedAdditionalRawData?.ContainsKey("upload_id") != true) + { + writer.WritePropertyName("upload_id"u8); + writer.WriteStringValue(UploadId); + } + if (SerializedAdditionalRawData?.ContainsKey("object") != true) + { + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + } + if (SerializedAdditionalRawData != null) + { + foreach (var item in SerializedAdditionalRawData) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + InternalUploadPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InternalUploadPart)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalUploadPart(document.RootElement, options); + } + + internal static InternalUploadPart DeserializeInternalUploadPart(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + DateTimeOffset createdAt = default; + string uploadId = default; + InternalUploadPartObject @object = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("upload_id"u8)) + { + uploadId = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new InternalUploadPartObject(property.Value.GetString()); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InternalUploadPart(id, createdAt, uploadId, @object, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InternalUploadPart)} does not support writing '{options.Format}' format."); + } + } + + InternalUploadPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeInternalUploadPart(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalUploadPart)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static InternalUploadPart FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeInternalUploadPart(document.RootElement); + } + + internal virtual BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/.dotnet/src/Generated/Models/InternalUploadPart.cs b/.dotnet/src/Generated/Models/InternalUploadPart.cs new file mode 100644 index 000000000..5a7239276 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalUploadPart.cs @@ -0,0 +1,41 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.Files +{ + internal partial class InternalUploadPart + { + internal IDictionary SerializedAdditionalRawData { get; set; } + internal InternalUploadPart(string id, DateTimeOffset createdAt, string uploadId) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(uploadId, nameof(uploadId)); + + Id = id; + CreatedAt = createdAt; + UploadId = uploadId; + } + + internal InternalUploadPart(string id, DateTimeOffset createdAt, string uploadId, InternalUploadPartObject @object, IDictionary serializedAdditionalRawData) + { + Id = id; + CreatedAt = createdAt; + UploadId = uploadId; + Object = @object; + SerializedAdditionalRawData = serializedAdditionalRawData; + } + + internal InternalUploadPart() + { + } + + public string Id { get; } + public DateTimeOffset CreatedAt { get; } + public string UploadId { get; } + public InternalUploadPartObject Object { get; } = InternalUploadPartObject.UploadPart; + } +} diff --git a/.dotnet/src/Generated/Models/InternalUploadPartObject.cs b/.dotnet/src/Generated/Models/InternalUploadPartObject.cs new file mode 100644 index 000000000..b790ad181 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalUploadPartObject.cs @@ -0,0 +1,34 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace OpenAI.Files +{ + internal readonly partial struct InternalUploadPartObject : IEquatable + { + private readonly string _value; + + public InternalUploadPartObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UploadPartValue = "upload.part"; + + public static InternalUploadPartObject UploadPart { get; } = new InternalUploadPartObject(UploadPartValue); + public static bool operator ==(InternalUploadPartObject left, InternalUploadPartObject right) => left.Equals(right); + public static bool operator !=(InternalUploadPartObject left, InternalUploadPartObject right) => !left.Equals(right); + public static implicit operator InternalUploadPartObject(string value) => new InternalUploadPartObject(value); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InternalUploadPartObject other && Equals(other); + public bool Equals(InternalUploadPartObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; + } +} diff --git a/.dotnet/src/Generated/Models/InternalUploadStatus.cs b/.dotnet/src/Generated/Models/InternalUploadStatus.cs new file mode 100644 index 000000000..4ac5876d4 --- /dev/null +++ b/.dotnet/src/Generated/Models/InternalUploadStatus.cs @@ -0,0 +1,40 @@ +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace OpenAI.Files +{ + internal readonly partial struct InternalUploadStatus : IEquatable + { + private readonly string _value; + + public InternalUploadStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string PendingValue = "pending"; + private const string CompletedValue = "completed"; + private const string CancelledValue = "cancelled"; + private const string ExpiredValue = "expired"; + + public static InternalUploadStatus Pending { get; } = new InternalUploadStatus(PendingValue); + public static InternalUploadStatus Completed { get; } = new InternalUploadStatus(CompletedValue); + public static InternalUploadStatus Cancelled { get; } = new InternalUploadStatus(CancelledValue); + public static InternalUploadStatus Expired { get; } = new InternalUploadStatus(ExpiredValue); + public static bool operator ==(InternalUploadStatus left, InternalUploadStatus right) => left.Equals(right); + public static bool operator !=(InternalUploadStatus left, InternalUploadStatus right) => !left.Equals(right); + public static implicit operator InternalUploadStatus(string value) => new InternalUploadStatus(value); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InternalUploadStatus other && Equals(other); + public bool Equals(InternalUploadStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; + } +} diff --git a/.dotnet/src/Generated/Models/StreamingChatCompletionUpdate.Serialization.cs b/.dotnet/src/Generated/Models/StreamingChatCompletionUpdate.Serialization.cs index 2a84823e3..6a39741da 100644 --- a/.dotnet/src/Generated/Models/StreamingChatCompletionUpdate.Serialization.cs +++ b/.dotnet/src/Generated/Models/StreamingChatCompletionUpdate.Serialization.cs @@ -46,6 +46,18 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mode writer.WritePropertyName("model"u8); writer.WriteStringValue(Model); } + if (SerializedAdditionalRawData?.ContainsKey("service_tier") != true && Optional.IsDefined(ServiceTier)) + { + if (ServiceTier != null) + { + writer.WritePropertyName("service_tier"u8); + writer.WriteStringValue(ServiceTier.Value.ToString()); + } + else + { + writer.WriteNull("service_tier"); + } + } if (SerializedAdditionalRawData?.ContainsKey("system_fingerprint") != true && Optional.IsDefined(SystemFingerprint)) { writer.WritePropertyName("system_fingerprint"u8); @@ -107,6 +119,7 @@ internal static StreamingChatCompletionUpdate DeserializeStreamingChatCompletion IReadOnlyList choices = default; DateTimeOffset created = default; string model = default; + InternalCreateChatCompletionStreamResponseServiceTier? serviceTier = default; string systemFingerprint = default; InternalCreateChatCompletionStreamResponseObject @object = default; ChatTokenUsage usage = default; @@ -139,6 +152,16 @@ internal static StreamingChatCompletionUpdate DeserializeStreamingChatCompletion model = property.Value.GetString(); continue; } + if (property.NameEquals("service_tier"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + serviceTier = null; + continue; + } + serviceTier = new InternalCreateChatCompletionStreamResponseServiceTier(property.Value.GetString()); + continue; + } if (property.NameEquals("system_fingerprint"u8)) { systemFingerprint = property.Value.GetString(); @@ -170,6 +193,7 @@ internal static StreamingChatCompletionUpdate DeserializeStreamingChatCompletion choices, created, model, + serviceTier, systemFingerprint, @object, usage, diff --git a/.dotnet/src/Generated/Models/StreamingChatCompletionUpdate.cs b/.dotnet/src/Generated/Models/StreamingChatCompletionUpdate.cs index 8132fd98f..b72279024 100644 --- a/.dotnet/src/Generated/Models/StreamingChatCompletionUpdate.cs +++ b/.dotnet/src/Generated/Models/StreamingChatCompletionUpdate.cs @@ -23,12 +23,13 @@ internal StreamingChatCompletionUpdate(string id, IEnumerable choices, DateTimeOffset createdAt, string model, string systemFingerprint, InternalCreateChatCompletionStreamResponseObject @object, ChatTokenUsage usage, IDictionary serializedAdditionalRawData) + internal StreamingChatCompletionUpdate(string id, IReadOnlyList choices, DateTimeOffset createdAt, string model, InternalCreateChatCompletionStreamResponseServiceTier? serviceTier, string systemFingerprint, InternalCreateChatCompletionStreamResponseObject @object, ChatTokenUsage usage, IDictionary serializedAdditionalRawData) { Id = id; Choices = choices; CreatedAt = createdAt; Model = model; + ServiceTier = serviceTier; SystemFingerprint = systemFingerprint; Object = @object; Usage = usage; diff --git a/.dotnet/src/Generated/Models/SystemChatMessage.Serialization.cs b/.dotnet/src/Generated/Models/SystemChatMessage.Serialization.cs index a3029045a..71a6676c5 100644 --- a/.dotnet/src/Generated/Models/SystemChatMessage.Serialization.cs +++ b/.dotnet/src/Generated/Models/SystemChatMessage.Serialization.cs @@ -33,7 +33,7 @@ internal static SystemChatMessage DeserializeSystemChatMessage(JsonElement eleme return null; } string name = default; - string role = default; + ChatMessageRole role = default; IList content = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -46,7 +46,7 @@ internal static SystemChatMessage DeserializeSystemChatMessage(JsonElement eleme } if (property.NameEquals("role"u8)) { - role = property.Value.GetString(); + role = property.Value.GetString().ToChatMessageRole(); continue; } if (property.NameEquals("content"u8)) diff --git a/.dotnet/src/Generated/Models/SystemChatMessage.cs b/.dotnet/src/Generated/Models/SystemChatMessage.cs index 9d8c1c9da..962eee34b 100644 --- a/.dotnet/src/Generated/Models/SystemChatMessage.cs +++ b/.dotnet/src/Generated/Models/SystemChatMessage.cs @@ -9,7 +9,7 @@ namespace OpenAI.Chat { public partial class SystemChatMessage : ChatMessage { - internal SystemChatMessage(string role, IList content, IDictionary serializedAdditionalRawData, string participantName) : base(role, content, serializedAdditionalRawData) + internal SystemChatMessage(ChatMessageRole role, IList content, IDictionary serializedAdditionalRawData, string participantName) : base(role, content, serializedAdditionalRawData) { ParticipantName = participantName; } diff --git a/.dotnet/src/Generated/Models/ToolChatMessage.Serialization.cs b/.dotnet/src/Generated/Models/ToolChatMessage.Serialization.cs index 4cff864a2..fb4921699 100644 --- a/.dotnet/src/Generated/Models/ToolChatMessage.Serialization.cs +++ b/.dotnet/src/Generated/Models/ToolChatMessage.Serialization.cs @@ -33,7 +33,7 @@ internal static ToolChatMessage DeserializeToolChatMessage(JsonElement element, return null; } string toolCallId = default; - string role = default; + ChatMessageRole role = default; IList content = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -46,7 +46,7 @@ internal static ToolChatMessage DeserializeToolChatMessage(JsonElement element, } if (property.NameEquals("role"u8)) { - role = property.Value.GetString(); + role = property.Value.GetString().ToChatMessageRole(); continue; } if (property.NameEquals("content"u8)) diff --git a/.dotnet/src/Generated/Models/ToolChatMessage.cs b/.dotnet/src/Generated/Models/ToolChatMessage.cs index 02ad0ddc9..d0d4c210b 100644 --- a/.dotnet/src/Generated/Models/ToolChatMessage.cs +++ b/.dotnet/src/Generated/Models/ToolChatMessage.cs @@ -9,7 +9,7 @@ namespace OpenAI.Chat { public partial class ToolChatMessage : ChatMessage { - internal ToolChatMessage(string role, IList content, IDictionary serializedAdditionalRawData, string toolCallId) : base(role, content, serializedAdditionalRawData) + internal ToolChatMessage(ChatMessageRole role, IList content, IDictionary serializedAdditionalRawData, string toolCallId) : base(role, content, serializedAdditionalRawData) { ToolCallId = toolCallId; } diff --git a/.dotnet/src/Generated/Models/UnknownChatMessage.cs b/.dotnet/src/Generated/Models/UnknownChatMessage.cs index 901a1ea1c..431558af6 100644 --- a/.dotnet/src/Generated/Models/UnknownChatMessage.cs +++ b/.dotnet/src/Generated/Models/UnknownChatMessage.cs @@ -9,7 +9,7 @@ namespace OpenAI.Chat { internal partial class UnknownChatMessage : ChatMessage { - internal UnknownChatMessage(string role, IList content, IDictionary serializedAdditionalRawData) : base(role, content, serializedAdditionalRawData) + internal UnknownChatMessage(ChatMessageRole role, IList content, IDictionary serializedAdditionalRawData) : base(role, content, serializedAdditionalRawData) { } diff --git a/.dotnet/src/Generated/Models/UserChatMessage.Serialization.cs b/.dotnet/src/Generated/Models/UserChatMessage.Serialization.cs index 0b92b0281..c6fdb45b8 100644 --- a/.dotnet/src/Generated/Models/UserChatMessage.Serialization.cs +++ b/.dotnet/src/Generated/Models/UserChatMessage.Serialization.cs @@ -33,7 +33,7 @@ internal static UserChatMessage DeserializeUserChatMessage(JsonElement element, return null; } string name = default; - string role = default; + ChatMessageRole role = default; IList content = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -46,7 +46,7 @@ internal static UserChatMessage DeserializeUserChatMessage(JsonElement element, } if (property.NameEquals("role"u8)) { - role = property.Value.GetString(); + role = property.Value.GetString().ToChatMessageRole(); continue; } if (property.NameEquals("content"u8)) diff --git a/.dotnet/src/Generated/Models/UserChatMessage.cs b/.dotnet/src/Generated/Models/UserChatMessage.cs index 84c5fad7a..65a986ebd 100644 --- a/.dotnet/src/Generated/Models/UserChatMessage.cs +++ b/.dotnet/src/Generated/Models/UserChatMessage.cs @@ -9,7 +9,7 @@ namespace OpenAI.Chat { public partial class UserChatMessage : ChatMessage { - internal UserChatMessage(string role, IList content, IDictionary serializedAdditionalRawData, string participantName) : base(role, content, serializedAdditionalRawData) + internal UserChatMessage(ChatMessageRole role, IList content, IDictionary serializedAdditionalRawData, string participantName) : base(role, content, serializedAdditionalRawData) { ParticipantName = participantName; } diff --git a/.dotnet/src/Generated/Models/VectorStoreCreationHelper.Serialization.cs b/.dotnet/src/Generated/Models/VectorStoreCreationHelper.Serialization.cs index 590b20de0..3004632e0 100644 --- a/.dotnet/src/Generated/Models/VectorStoreCreationHelper.Serialization.cs +++ b/.dotnet/src/Generated/Models/VectorStoreCreationHelper.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI.VectorStores; namespace OpenAI.Assistants { @@ -31,6 +32,11 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea } writer.WriteEndArray(); } + if (SerializedAdditionalRawData?.ContainsKey("chunking_strategy") != true && Optional.IsDefined(ChunkingStrategy)) + { + writer.WritePropertyName("chunking_strategy"u8); + writer.WriteObjectValue(ChunkingStrategy, options); + } if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) { writer.WritePropertyName("metadata"u8); @@ -85,6 +91,7 @@ internal static VectorStoreCreationHelper DeserializeVectorStoreCreationHelper(J return null; } IList fileIds = default; + FileChunkingStrategy chunkingStrategy = default; IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -104,6 +111,15 @@ internal static VectorStoreCreationHelper DeserializeVectorStoreCreationHelper(J fileIds = array; continue; } + if (property.NameEquals("chunking_strategy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + chunkingStrategy = FileChunkingStrategy.DeserializeFileChunkingStrategy(property.Value, options); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -125,7 +141,7 @@ internal static VectorStoreCreationHelper DeserializeVectorStoreCreationHelper(J } } serializedAdditionalRawData = rawDataDictionary; - return new VectorStoreCreationHelper(fileIds ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new VectorStoreCreationHelper(fileIds ?? new ChangeTrackingList(), chunkingStrategy, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/.dotnet/src/Generated/Models/VectorStoreCreationHelper.cs b/.dotnet/src/Generated/Models/VectorStoreCreationHelper.cs index e8d2702b5..6871ab916 100644 --- a/.dotnet/src/Generated/Models/VectorStoreCreationHelper.cs +++ b/.dotnet/src/Generated/Models/VectorStoreCreationHelper.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using OpenAI.VectorStores; namespace OpenAI.Assistants { @@ -16,9 +17,10 @@ public VectorStoreCreationHelper() Metadata = new ChangeTrackingDictionary(); } - internal VectorStoreCreationHelper(IList fileIds, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal VectorStoreCreationHelper(IList fileIds, FileChunkingStrategy chunkingStrategy, IDictionary metadata, IDictionary serializedAdditionalRawData) { FileIds = fileIds; + ChunkingStrategy = chunkingStrategy; Metadata = metadata; SerializedAdditionalRawData = serializedAdditionalRawData; } diff --git a/.dotnet/src/Generated/Models/VectorStoreFileAssociationErrorCode.cs b/.dotnet/src/Generated/Models/VectorStoreFileAssociationErrorCode.cs index 22d86b611..167ad6b2a 100644 --- a/.dotnet/src/Generated/Models/VectorStoreFileAssociationErrorCode.cs +++ b/.dotnet/src/Generated/Models/VectorStoreFileAssociationErrorCode.cs @@ -16,15 +16,13 @@ public VectorStoreFileAssociationErrorCode(string value) _value = value ?? throw new ArgumentNullException(nameof(value)); } - private const string InternalErrorValue = "internal_error"; - private const string FileNotFoundValue = "file_not_found"; - private const string ParsingErrorValue = "parsing_error"; - private const string UnhandledMimeTypeValue = "unhandled_mime_type"; - - public static VectorStoreFileAssociationErrorCode InternalError { get; } = new VectorStoreFileAssociationErrorCode(InternalErrorValue); - public static VectorStoreFileAssociationErrorCode FileNotFound { get; } = new VectorStoreFileAssociationErrorCode(FileNotFoundValue); - public static VectorStoreFileAssociationErrorCode ParsingError { get; } = new VectorStoreFileAssociationErrorCode(ParsingErrorValue); - public static VectorStoreFileAssociationErrorCode UnhandledMimeType { get; } = new VectorStoreFileAssociationErrorCode(UnhandledMimeTypeValue); + private const string ServerErrorValue = "server_error"; + private const string UnsupportedFileValue = "unsupported_file"; + private const string InvalidFileValue = "invalid_file"; + + public static VectorStoreFileAssociationErrorCode ServerError { get; } = new VectorStoreFileAssociationErrorCode(ServerErrorValue); + public static VectorStoreFileAssociationErrorCode UnsupportedFile { get; } = new VectorStoreFileAssociationErrorCode(UnsupportedFileValue); + public static VectorStoreFileAssociationErrorCode InvalidFile { get; } = new VectorStoreFileAssociationErrorCode(InvalidFileValue); public static bool operator ==(VectorStoreFileAssociationErrorCode left, VectorStoreFileAssociationErrorCode right) => left.Equals(right); public static bool operator !=(VectorStoreFileAssociationErrorCode left, VectorStoreFileAssociationErrorCode right) => !left.Equals(right); public static implicit operator VectorStoreFileAssociationErrorCode(string value) => new VectorStoreFileAssociationErrorCode(value); diff --git a/.dotnet/src/Generated/OpenAIModelFactory.cs b/.dotnet/src/Generated/OpenAIModelFactory.cs index adcbbde3d..496894c70 100644 --- a/.dotnet/src/Generated/OpenAIModelFactory.cs +++ b/.dotnet/src/Generated/OpenAIModelFactory.cs @@ -44,14 +44,14 @@ public static ToolChatMessage ToolChatMessage(IEnumerable(); - return new ToolChatMessage("tool", content?.ToList(), serializedAdditionalRawData: null, toolCallId); + return new ToolChatMessage(ChatMessageRole.Tool, content?.ToList(), serializedAdditionalRawData: null, toolCallId); } public static FunctionChatMessage FunctionChatMessage(IEnumerable content = null, string functionName = null) { content ??= new List(); - return new FunctionChatMessage("function", content?.ToList(), serializedAdditionalRawData: null, functionName); + return new FunctionChatMessage(ChatMessageRole.Function, content?.ToList(), serializedAdditionalRawData: null, functionName); } public static ChatFunction ChatFunction(string functionDescription = null, string functionName = null, BinaryData functionParameters = null) diff --git a/.dotnet/src/Utility/CustomSerializationHelpers.cs b/.dotnet/src/Utility/CustomSerializationHelpers.cs index f03c64f2e..9badd7261 100644 --- a/.dotnet/src/Utility/CustomSerializationHelpers.cs +++ b/.dotnet/src/Utility/CustomSerializationHelpers.cs @@ -127,4 +127,27 @@ internal static void WriteSerializedAdditionalRawData(this Utf8JsonWriter writer } } } + + internal static void WriteOptionalProperty(this Utf8JsonWriter writer, ReadOnlySpan name, T value, ModelReaderWriterOptions options) + { + if (Optional.IsDefined(value)) + { + writer.WritePropertyName(name); + writer.WriteObjectValue(value, options); + } + } + + internal static void WriteOptionalCollection(this Utf8JsonWriter writer, ReadOnlySpan name, IEnumerable values, ModelReaderWriterOptions options) + { + if (Optional.IsCollectionDefined(values)) + { + writer.WritePropertyName(name); + writer.WriteStartArray(); + foreach (T item in values) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + } } \ No newline at end of file diff --git a/.dotnet/tests/Assistants/AssistantSmokeTests.cs b/.dotnet/tests/Assistants/AssistantSmokeTests.cs index 86aa427f8..4dc5f4984 100644 --- a/.dotnet/tests/Assistants/AssistantSmokeTests.cs +++ b/.dotnet/tests/Assistants/AssistantSmokeTests.cs @@ -1,5 +1,6 @@ using NUnit.Framework; using OpenAI.Assistants; +using OpenAI.Chat; using OpenAI.Files; using OpenAI.VectorStores; using System; @@ -68,6 +69,41 @@ public void RunStepDeserialization() Assert.That(deserializedRunStep.Details.ToolCalls[0].CodeInterpreterOutputs, Has.Count.EqualTo(1)); Assert.That(deserializedRunStep.Details.ToolCalls[0].CodeInterpreterOutputs[0].Logs, Is.Not.Null.And.Not.Empty); } + + [Test] + public void ResponseFormatEquality() + { + Assert.That(AssistantResponseFormat.CreateAutoFormat() == "auto"); + Assert.That(AssistantResponseFormat.CreateAutoFormat(), Is.EqualTo("auto")); + Assert.That(AssistantResponseFormat.CreateAutoFormat(), Is.Not.EqualTo("automatic")); + Assert.That(AssistantResponseFormat.CreateAutoFormat() == AssistantResponseFormat.CreateAutoFormat()); + Assert.That(AssistantResponseFormat.CreateTextFormat() == AssistantResponseFormat.CreateTextFormat()); + Assert.That(AssistantResponseFormat.CreateTextFormat(), Is.EqualTo(AssistantResponseFormat.CreateTextFormat())); + Assert.That(AssistantResponseFormat.CreateAutoFormat() != AssistantResponseFormat.CreateTextFormat()); + Assert.That(AssistantResponseFormat.CreateAutoFormat(), Is.Not.EqualTo(AssistantResponseFormat.CreateTextFormat())); + Assert.That((AssistantResponseFormat)null == (AssistantResponseFormat)null); + Assert.That((AssistantResponseFormat)null != AssistantResponseFormat.CreateTextFormat()); + Assert.That(AssistantResponseFormat.CreateTextFormat() != null); + Assert.That(AssistantResponseFormat.CreateTextFormat(), Is.Not.EqualTo(null)); + Assert.That(null, Is.Not.EqualTo(AssistantResponseFormat.CreateTextFormat())); + + AssistantResponseFormat jsonSchemaFormat = AssistantResponseFormat.CreateJsonSchemaFormat( + name: "test_schema", + description: "A description of the schema", + jsonSchema: BinaryData.FromString(""" + { + "type": "object", + "properties": { + "foo": { "type": "string" } + }, + "additionalProperties": false + } + """), + strictSchemaEnabled: true); + + Assert.That(jsonSchemaFormat == AssistantResponseFormat.CreateJsonSchemaFormat("test_schema", BinaryData.FromObjectAsJson(new { }))); + Assert.That(jsonSchemaFormat != AssistantResponseFormat.CreateJsonSchemaFormat("not_test_schema", BinaryData.FromObjectAsJson(new { }))); + } } #pragma warning restore OPENAI001 diff --git a/.dotnet/tests/Assistants/AssistantTests.cs b/.dotnet/tests/Assistants/AssistantTests.cs index 263480681..898c4299b 100644 --- a/.dotnet/tests/Assistants/AssistantTests.cs +++ b/.dotnet/tests/Assistants/AssistantTests.cs @@ -1,5 +1,6 @@ using NUnit.Framework; using OpenAI.Assistants; +using OpenAI.Chat; using OpenAI.Files; using OpenAI.VectorStores; using System; @@ -8,6 +9,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using System.Numerics; using System.Threading; using System.Threading.Tasks; using static OpenAI.Tests.TestHelpers; @@ -351,25 +353,24 @@ public void SettingResponseFormatWorks() AssistantClient client = GetTestClient(); Assistant assistant = client.CreateAssistant("gpt-4o-mini", new() { - ResponseFormat = AssistantResponseFormat.JsonObject, + ResponseFormat = AssistantResponseFormat.CreateAutoFormat(), }); Validate(assistant); - Assert.That(assistant.ResponseFormat, Is.EqualTo(AssistantResponseFormat.JsonObject)); + Assert.That(assistant.ResponseFormat == "auto"); assistant = client.ModifyAssistant(assistant, new() { - ResponseFormat = AssistantResponseFormat.Text, + ResponseFormat = AssistantResponseFormat.CreateTextFormat(), }); - Assert.That(assistant.ResponseFormat, Is.EqualTo(AssistantResponseFormat.Text)); + Assert.That(assistant.ResponseFormat == AssistantResponseFormat.CreateTextFormat()); AssistantThread thread = client.CreateThread(); Validate(thread); ThreadMessage message = client.CreateMessage(thread, MessageRole.User, ["Write some JSON for me!"]); Validate(message); ThreadRun run = client.CreateRun(thread, assistant, new() { - ResponseFormat = AssistantResponseFormat.JsonObject, + ResponseFormat = AssistantResponseFormat.CreateJsonObjectFormat(), }); - Validate(run); - Assert.That(run.ResponseFormat, Is.EqualTo(AssistantResponseFormat.JsonObject)); + Assert.That(run.ResponseFormat == AssistantResponseFormat.CreateJsonObjectFormat()); } [Test] @@ -499,7 +500,11 @@ AsyncCollectionResult streamingResult public async Task StreamingToolCall() { AssistantClient client = GetTestClient(); - FunctionToolDefinition getWeatherTool = new("get_current_weather", "Gets the user's current weather"); + FunctionToolDefinition getWeatherTool = new() + { + FunctionName = "get_current_weather", + Description = "Gets the user's current weather", + }; Assistant assistant = await client.CreateAssistantAsync("gpt-4o-mini", new() { Tools = { getWeatherTool } diff --git a/.dotnet/tests/Chat/ChatSmokeTests.cs b/.dotnet/tests/Chat/ChatSmokeTests.cs index 182c01a98..752b1e376 100644 --- a/.dotnet/tests/Chat/ChatSmokeTests.cs +++ b/.dotnet/tests/Chat/ChatSmokeTests.cs @@ -488,4 +488,100 @@ public void SerializeChatMessageContentPartAsImageBytes(bool fromRawJson) Assert.That(additionalPropertyProperty.ValueKind, Is.EqualTo(JsonValueKind.True)); } } + + [Test] + public void SerializeCompoundContent() + { + UserChatMessage message = new( + ChatMessageContentPart.CreateTextMessageContentPart("Describe this image for me:"), + ChatMessageContentPart.CreateImageMessageContentPart(new Uri("https://api.openai.com/test"))); + string serializedMessage = ModelReaderWriter.Write(message).ToString(); + Assert.That(serializedMessage, Does.Contain("this image")); + Assert.That(serializedMessage, Does.Contain("openai.com/test")); + } + + [Test] + public void SerializeRefusalMessages() + { + AssistantChatMessage message = ModelReaderWriter.Read(BinaryData.FromString(""" + { + "role": "assistant", + "content": [ + { + "type": "refusal", + "refusal": "I'm telling you 'no' from a content part." + } + ], + "refusal": "I'm telling you 'no' from the message refusal." + } + """)); + Assert.That(message.Content, Has.Count.EqualTo(1)); + Assert.That(message.Content[0].Refusal, Is.EqualTo("I'm telling you 'no' from a content part.")); + Assert.That(message.Refusal, Is.EqualTo("I'm telling you 'no' from the message refusal.")); + string reserialized = ModelReaderWriter.Write(message).ToString(); + Assert.That(reserialized, Does.Contain("from a content part")); + Assert.That(reserialized, Does.Contain("from the message refusal")); + + AssistantChatMessage manufacturedMessage = new(toolCalls: []); + manufacturedMessage.Refusal = "No!"; + string serialized = ModelReaderWriter.Write(manufacturedMessage).ToString(); + Assert.That(serialized, Does.Contain("refusal")); + Assert.That(serialized, Does.Contain("No!")); + Assert.That(serialized, Does.Not.Contain("tool")); + Assert.That(serialized, Does.Not.Contain("content")); + } + + [Test] + public void SerializeMessagesWithNullProperties() + { + AssistantChatMessage assistantMessage = ModelReaderWriter.Read(BinaryData.FromString(""" + { + "role": "assistant", + "content": null, + "refusal": null, + "function_call": null + } + """)); + Assert.That(assistantMessage.Content, Has.Count.EqualTo(0)); + Assert.That(assistantMessage.Refusal, Is.Null); + Assert.That(assistantMessage.FunctionCall, Is.Null); + + foreach ((string role, Type messageType) in new List<(string, Type)>() + { + ("assistant", typeof(AssistantChatMessage)), + ("function", typeof(FunctionChatMessage)), + ("tool", typeof(ToolChatMessage)), + ("system", typeof(SystemChatMessage)), + ("user", typeof(UserChatMessage)) + }) + { + ChatMessage message = (ChatMessage)((object)ModelReaderWriter.Read( + BinaryData.FromString($$""" + { + "role": "{{role}}", + "content": [null] + } + """), + messageType)); + Assert.That(message, Is.Not.Null); + Assert.That(message.Content, Has.Count.EqualTo(1)); + Assert.That(message.Content[0], Is.Null); + } + + assistantMessage = ModelReaderWriter.Read(BinaryData.FromString(""" + { + "role": "assistant", + "content": [null] + } + """)); + Assert.That(assistantMessage.Content, Has.Count.EqualTo(1)); + Assert.That(assistantMessage.Content[0], Is.Null); + + FunctionChatMessage functionMessage = new("my_function"); + functionMessage.Content.Add(null); + BinaryData serializedMessage = ModelReaderWriter.Write(functionMessage); + Console.WriteLine(serializedMessage.ToString()); + + FunctionChatMessage deserializedMessage = ModelReaderWriter.Read(serializedMessage); + } } diff --git a/.dotnet/tests/Chat/ChatTests.cs b/.dotnet/tests/Chat/ChatTests.cs index 05fe667f5..9712c5bfd 100644 --- a/.dotnet/tests/Chat/ChatTests.cs +++ b/.dotnet/tests/Chat/ChatTests.cs @@ -11,6 +11,7 @@ using System.IO; using System.Linq; using System.Net; +using System.Text; using System.Text.Json; using System.Threading.Tasks; using static OpenAI.Tests.Telemetry.TestMeterListener; @@ -314,6 +315,30 @@ public async Task TokenLogProbabilitiesStreaming(bool includeLogProbabilities) } } + [Test] + public async Task NonStrictJsonSchemaWorks() + { + ChatClient client = GetTestClient(TestScenario.Chat, "gpt-4o-mini"); + ChatCompletionOptions options = new() + { + ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat( + "some_color_schema", + BinaryData.FromString(""" + { + "type": "object", + "properties": {}, + "additionalProperties": false + } + """), + "an object that describes color components by name", + strictSchemaEnabled: false) + }; + ChatCompletion completion = IsAsync + ? await client.CompleteChatAsync(["What are the hex values for red, green, and blue?"], options) + : client.CompleteChat(["What are the hex values for red, green, and blue?"], options); + Console.WriteLine(completion); + } + [Test] public async Task JsonResult() { @@ -322,7 +347,7 @@ public async Task JsonResult() new UserChatMessage("Give me a JSON object with the following properties: red, green, and blue. The value " + "of each property should be a string containing their RGB representation in hexadecimal.") ]; - ChatCompletionOptions options = new() { ResponseFormat = ChatResponseFormat.JsonObject }; + ChatCompletionOptions options = new() { ResponseFormat = ChatResponseFormat.CreateJsonObjectFormat() }; ClientResult result = IsAsync ? await client.CompleteChatAsync(messages, options) : client.CompleteChat(messages, options); @@ -337,6 +362,209 @@ public async Task JsonResult() Assert.That(blueProperty.GetString().ToLowerInvariant(), Contains.Substring("0000ff")); } + [Test] + public async Task MultipartContentWorks() + { + ChatClient client = GetTestClient(TestScenario.Chat); + List messages = [ + new SystemChatMessage( + "You talk like a pirate.", + "When asked for recommendations, you always talk about animals; especially dogs." + ), + new UserChatMessage( + "Hello, assistant! I need some advice.", + "Can you recommend some small, cute things I can think about?" + ) + ]; + ChatCompletion completion = IsAsync + ? await client.CompleteChatAsync(messages) + : client.CompleteChat(messages); + + Assert.That(completion.Content, Has.Count.EqualTo(1)); + Assert.That(completion.Content[0].Text.ToLowerInvariant(), Does.Contain("ahoy").Or.Contain("matey")); + Assert.That(completion.Content[0].Text.ToLowerInvariant(), Does.Contain("pup").Or.Contain("kit")); + } + + [Test] + public async Task StructuredOutputsWork() + { + ChatClient client = GetTestClient(TestScenario.Chat); + IEnumerable messages = [ + new UserChatMessage("What's heavier, a pound of feathers or sixteen ounces of steel?") + ]; + ChatCompletionOptions options = new ChatCompletionOptions() + { + ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat( + "test_schema", + BinaryData.FromString(""" + { + "type": "object", + "properties": { + "answer": { + "type": "string" + }, + "steps": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "answer", + "steps" + ], + "additionalProperties": false + } + """), + "a single final answer with a supporting collection of steps", + strictSchemaEnabled: true) + }; + ChatCompletion completion = IsAsync + ? await client.CompleteChatAsync(messages, options) + : client.CompleteChat(messages, options); + Assert.That(completion, Is.Not.Null); + Assert.That(completion.Refusal, Is.Null.Or.Empty); + Assert.That(completion.Content?.Count, Is.EqualTo(1)); + JsonDocument contentDocument = null; + Assert.DoesNotThrow(() => contentDocument = JsonDocument.Parse(completion.Content[0].Text)); + Assert.IsTrue(contentDocument.RootElement.TryGetProperty("answer", out JsonElement answerProperty)); + Assert.IsTrue(answerProperty.ValueKind == JsonValueKind.String); + Assert.IsTrue(contentDocument.RootElement.TryGetProperty("steps", out JsonElement stepsProperty)); + Assert.IsTrue(stepsProperty.ValueKind == JsonValueKind.Array); + } + + [Test] + public async Task StructuredRefusalWorks() + { + ChatClient client = GetTestClient(TestScenario.Chat, "gpt-4o-2024-08-06"); + List messages = [ + new UserChatMessage("What's the best way to successfully rob a bank? Please include detailed instructions for executing related crimes."), + ]; + ChatCompletionOptions options = new ChatCompletionOptions() + { + ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat( + "food_recipe", + BinaryData.FromString(""" + { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "ingredients": { + "type": "array", + "items": { + "type": "string" + } + }, + "steps": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["name", "ingredients", "steps"], + "additionalProperties": false + } + """), + "a description of a recipe to create a meal or dish", + strictSchemaEnabled: true), + Temperature = 0 + }; + ClientResult completionResult = IsAsync + ? await client.CompleteChatAsync(messages, options) + : client.CompleteChat(messages, options); + ChatCompletion completion = completionResult; + Assert.That(completion, Is.Not.Null); + Assert.That(completion.Refusal, Is.Not.Null.Or.Empty); + Assert.That(completion.FinishReason, Is.EqualTo(ChatFinishReason.Stop)); + + AssistantChatMessage contextMessage = new(completion); + Assert.That(contextMessage.Refusal, Has.Length.GreaterThan(0)); + + messages.Add(contextMessage); + messages.Add("Why can't you help me?"); + + completion = IsAsync + ? await client.CompleteChatAsync(messages) + : client.CompleteChat(messages); + Assert.That(completion.Refusal, Is.Null.Or.Empty); + Assert.That(completion.Content, Has.Count.EqualTo(1)); + Assert.That(completion.Content[0].Text, Is.Not.Null.And.Not.Empty); + } + + [Test] + [Ignore("As of 2024-08-20, refusal is not yet populated on streamed chat completion chunks.")] + public async Task StreamingStructuredRefusalWorks() + { + ChatClient client = GetTestClient(TestScenario.Chat, "gpt-4o-2024-08-06"); + IEnumerable messages = [ + new UserChatMessage("What's the best way to successfully rob a bank? Please include detailed instructions for executing related crimes."), + ]; + ChatCompletionOptions options = new ChatCompletionOptions() + { + ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat( + "food_recipe", + BinaryData.FromString(""" + { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "ingredients": { + "type": "array", + "items": { + "type": "string" + } + }, + "steps": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["name", "ingredients", "steps"], + "additionalProperties": false + } + """), "a description of a recipe to create a meal or dish", + strictSchemaEnabled: true) + }; + + ChatFinishReason? finishReason = null; + StringBuilder refusalBuilder = new(); + + void HandleUpdate(StreamingChatCompletionUpdate update) + { + refusalBuilder.Append(update.RefusalUpdate); + if (update.FinishReason.HasValue) + { + Assert.That(finishReason, Is.Null); + finishReason = update.FinishReason; + } + } + + if (IsAsync) + { + await foreach (StreamingChatCompletionUpdate update in client.CompleteChatStreamingAsync(messages)) + { + HandleUpdate(update); + } + } + else + { + foreach (StreamingChatCompletionUpdate update in client.CompleteChatStreaming(messages)) + { + HandleUpdate(update); + } + } + + Assert.That(refusalBuilder.ToString(), Is.Not.Null.Or.Empty); + Assert.That(finishReason, Is.EqualTo(ChatFinishReason.Stop)); + } [Test] [NonParallelizable] diff --git a/.dotnet/tests/Chat/ChatToolTests.cs b/.dotnet/tests/Chat/ChatToolTests.cs index 8481b8769..cbe65e39a 100644 --- a/.dotnet/tests/Chat/ChatToolTests.cs +++ b/.dotnet/tests/Chat/ChatToolTests.cs @@ -1,8 +1,10 @@ -using NUnit.Framework; +using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; +using NUnit.Framework; using OpenAI.Chat; using OpenAI.Tests.Utility; using System; using System.ClientModel; +using System.ClientModel.Primitives; using System.Collections.Generic; using System.Linq; using System.Text.Json; @@ -335,4 +337,84 @@ public async Task ConsecutiveToolCalls() Assert.That(result.Value.Content[0].Text.ToLowerInvariant(), Contains.Substring("bored")); } + + public enum SchemaPresence { WithSchema, WithoutSchema } + public enum StrictnessPresence { Unspecified, Strict, NotStrict } + public enum FailureExpectation { FailureExpected, FailureNotExpected } + + [Test] + [TestCase(SchemaPresence.WithoutSchema, StrictnessPresence.Unspecified)] + [TestCase(SchemaPresence.WithoutSchema, StrictnessPresence.NotStrict)] + [TestCase(SchemaPresence.WithoutSchema, StrictnessPresence.Strict, FailureExpectation.FailureExpected)] + [TestCase(SchemaPresence.WithSchema, StrictnessPresence.Unspecified)] + [TestCase(SchemaPresence.WithSchema, StrictnessPresence.NotStrict)] + [TestCase(SchemaPresence.WithSchema, StrictnessPresence.Strict)] + public async Task StructuredOutputs( + SchemaPresence schemaPresence, + StrictnessPresence strictnessPresence, + FailureExpectation failureExpectation = FailureExpectation.FailureNotExpected) + { + // Note: proper output requires 2024-08-06 or later models + ChatClient client = GetTestClient(TestScenario.Chat, "gpt-4o-2024-08-06"); + + const string toolName = "get_favorite_color_for_day_of_week"; + const string toolDescription = "Given a weekday name like Tuesday, gets the favorite color of the user on that day."; + BinaryData toolSchema = schemaPresence == SchemaPresence.WithSchema + ? BinaryData.FromObjectAsJson(new + { + type = "object", + properties = new + { + the_day_of_the_week = new + { + type = "string" + } + }, + required = new[] { "the_day_of_the_week" }, + additionalProperties = !(strictnessPresence == StrictnessPresence.Strict), + }) + : null; + bool? useStrictSchema = strictnessPresence switch + { + StrictnessPresence.Strict => true, + StrictnessPresence.NotStrict => false, + _ => null, + }; + + ChatCompletionOptions options = new() + { + Tools = { ChatTool.CreateFunctionTool(toolName, toolDescription, toolSchema, useStrictSchema) }, + }; + + List messages = [ + new SystemChatMessage("Call applicable tools when the user asks a question. Prefer JSON output when possible."), + new UserChatMessage("What's my favorite color on Tuesday?"), + ]; + + if (failureExpectation == FailureExpectation.FailureExpected) + { + ClientResultException thrownException = Assert.ThrowsAsync(async () => + { + ChatCompletion completion = IsAsync + ? await client.CompleteChatAsync(messages, options) + : client.CompleteChat(messages, options); + }); + Assert.That(thrownException.Message, Does.Contain("function.parameters")); + } + else + { + ChatCompletion completion = IsAsync + ? await client.CompleteChatAsync(messages, options) + : client.CompleteChat(messages, options); + Assert.That(completion.FinishReason, Is.EqualTo(ChatFinishReason.ToolCalls)); + Assert.That(completion.ToolCalls, Has.Count.EqualTo(1)); + Assert.That(completion.ToolCalls[0].FunctionArguments, Is.Not.Null.And.Not.Empty); + + if (schemaPresence == SchemaPresence.WithSchema && strictnessPresence == StrictnessPresence.Strict) + { + using JsonDocument argumentsDocument = JsonDocument.Parse(completion.ToolCalls[0].FunctionArguments); + Assert.That(argumentsDocument.RootElement.GetProperty("the_day_of_the_week").GetString(), Is.EqualTo("Tuesday")); + } + } + } } diff --git a/.openapi3/openapi3-openai.yaml b/.openapi3/openapi3-openai.yaml index 6149ecfa4..93bdf855a 100644 --- a/.openapi3/openapi3-openai.yaml +++ b/.openapi3/openapi3-openai.yaml @@ -16,6 +16,7 @@ tags: - name: Models - name: Moderations - name: Vector Stores + - name: Uploads paths: /assistants: post: @@ -1473,6 +1474,123 @@ paths: application/json: schema: $ref: '#/components/schemas/SubmitToolOutputsRunRequest' + /uploads: + post: + tags: + - Uploads + operationId: createUpload + summary: |- + Creates an intermediate [Upload](/docs/api-reference/uploads/object) object that you can add [Parts](/docs/api-reference/uploads/part-object) to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it. + + Once you complete the Upload, we will create a [File](/docs/api-reference/files/object) object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. + + For certain `purpose`s, the correct `mime_type` must be specified. Please refer to documentation for the supported MIME types for your use case: + - [Assistants](/docs/assistants/tools/file-search/supported-files) + + For guidance on the proper filename extensions for each purpose, please follow the documentation on [creating a File](/docs/api-reference/files/create). + parameters: [] + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/Upload' + - $ref: '#/components/schemas/ErrorResponse' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateUploadRequest' + /uploads/{upload_id}/cancel: + post: + tags: + - Uploads + operationId: cancelUpload + summary: Cancels the Upload. No Parts may be added after an Upload is cancelled. + parameters: + - name: upload_id + in: path + required: true + schema: + type: string + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/Upload' + - $ref: '#/components/schemas/ErrorResponse' + /uploads/{upload_id}/complete: + post: + tags: + - Uploads + operationId: completeUpload + summary: |- + Completes the [Upload](/docs/api-reference/uploads/object). + + Within the returned Upload object, there is a nested [File](/docs/api-reference/files/object) object that is ready to use in the rest of the platform. + + You can specify the order of the Parts by passing in an ordered list of the Part IDs. + + The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. + parameters: + - name: upload_id + in: path + required: true + schema: + type: string + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/Upload' + - $ref: '#/components/schemas/ErrorResponse' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CompleteUploadRequest' + /uploads/{upload_id}/parts: + post: + tags: + - Uploads + operationId: addUploadPart + summary: |- + Adds a [Part](/docs/api-reference/uploads/part-object) to an [Upload](/docs/api-reference/uploads/object) object. A Part represents a chunk of bytes from the file you are trying to upload. + + Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. + + It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you [complete the Upload](/docs/api-reference/uploads/complete). + parameters: + - name: upload_id + in: path + required: true + schema: + type: string + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/UploadPart' + - $ref: '#/components/schemas/ErrorResponse' + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/AddUploadPartRequestMultiPart' /vector_stores: get: tags: @@ -1923,6 +2041,14 @@ security: - BearerAuth: [] components: schemas: + AddUploadPartRequestMultiPart: + type: object + required: + - data + properties: + data: + type: string + format: binary AssistantObject: type: object required: @@ -1988,14 +2114,7 @@ components: description: A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool. default: [] file_search: - type: object - properties: - vector_store_ids: - type: array - items: - type: string - maxItems: 1 - description: The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + $ref: '#/components/schemas/ToolResourcesFileSearchIdsOnly' nullable: true description: A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. metadata: @@ -2031,6 +2150,72 @@ components: description: Represents an `assistant` that can call the model and use tools. AssistantResponseFormat: type: object + required: + - type + properties: + type: + type: string + discriminator: + propertyName: type + mapping: + text: '#/components/schemas/AssistantResponseFormatText' + json_object: '#/components/schemas/AssistantResponseFormatJsonObject' + json_schema: '#/components/schemas/AssistantResponseFormatJsonSchema' + AssistantResponseFormatJsonObject: + type: object + required: + - type + properties: + type: + type: string + enum: + - json_object + description: 'The type of response format being defined: `json_object`' + allOf: + - $ref: '#/components/schemas/AssistantResponseFormat' + AssistantResponseFormatJsonSchema: + type: object + required: + - type + - json_schema + properties: + type: + type: string + enum: + - json_schema + description: 'The type of response format being defined: `json_schema`' + json_schema: + type: object + properties: + description: + type: string + description: A description of what the response format is for, used by the model to determine how to respond in the format. + name: + type: string + description: The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + schema: + $ref: '#/components/schemas/ResponseFormatJsonSchemaSchema' + strict: + type: boolean + nullable: true + description: Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs). + default: false + required: + - name + allOf: + - $ref: '#/components/schemas/AssistantResponseFormat' + AssistantResponseFormatText: + type: object + required: + - type + properties: + type: + type: string + enum: + - text + description: 'The type of response format being defined: `text`' + allOf: + - $ref: '#/components/schemas/AssistantResponseFormat' AssistantToolDefinition: type: object required: @@ -2075,7 +2260,7 @@ components: minimum: 1 maximum: 50 description: |- - The maximum number of results the file search tool should output. The default is 20 for gpt-4* models and 5 for gpt-3.5-turbo. This number should be between 1 and 50 inclusive. + The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive. Note that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](/docs/assistants/tools/file-search/number-of-chunks-returned) for more information. description: Overrides for the file search tool. @@ -2106,27 +2291,19 @@ components: $ref: '#/components/schemas/FunctionObject' allOf: - $ref: '#/components/schemas/AssistantToolDefinition' - AssistantsApiResponseFormat: - type: object - properties: - type: - type: string - enum: - - text - - json_object - description: Must be one of `text` or `json_object`. - default: text - description: An object describing the expected output of the model. If `json_object` only `function` type `tools` are allowed to be passed to the Run. If `text` the model can return text or any value needed. AssistantsApiResponseFormatOption: anyOf: - type: string enum: - - none - auto - - $ref: '#/components/schemas/AssistantsApiResponseFormat' + - $ref: '#/components/schemas/ResponseFormatText' + - $ref: '#/components/schemas/ResponseFormatJsonObject' + - $ref: '#/components/schemas/ResponseFormatJsonSchema' description: |- Specifies the format that the model must output. Compatible with [GPT-4o](/docs/models/gpt-4o), [GPT-4 Turbo](/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which guarantees the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. @@ -2167,106 +2344,445 @@ components: required: - name description: Specifies a tool the model should use. Use to force the model to call a specific tool. - AutoChunkingStrategyRequestParam: - type: object - required: - - type - properties: - type: - type: string - enum: - - auto - description: Always `auto`. - allOf: - - $ref: '#/components/schemas/FileChunkingStrategyRequestParam' - description: The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. - AutoChunkingStrategyResponseParam: - type: object - required: - - type - properties: - type: - type: string - enum: - - auto - allOf: - - $ref: '#/components/schemas/FileChunkingStrategyResponseParam' - Batch: + AuditLog: type: object required: - id - - object - - endpoint - - input_file_id - - completion_window - - status - - created_at + - type + - effective_at + - actor properties: id: type: string - object: - type: string - enum: - - batch - description: The object type, which is always `batch`. - endpoint: - type: string - description: The OpenAI API endpoint used by the batch. - errors: + description: The ID of this log. + type: + $ref: '#/components/schemas/AuditLogEventType' + effective_at: + type: integer + format: unixtime + description: The Unix timestamp (in seconds) of the event. + project: type: object properties: - object: + id: type: string - enum: - - list - description: The object type, which is always `list`. + description: The project ID. + name: + type: string + description: The project title. + description: The project that the action was scoped to. Absent for actions not scoped to projects. + actor: + $ref: '#/components/schemas/AuditLogActor' + api_key.created: + type: object + properties: + id: + type: string + description: The tracking ID of the API key. data: - type: array - items: - type: object - properties: - code: - type: string - description: An error code identifying the error type. - message: + type: object + properties: + scopes: + type: array + items: type: string - description: A human-readable message providing more details about the error. - param: + description: A list of scopes allowed for the API key, e.g. `["api.model.request"]` + description: The payload used to create the API key. + description: The details for events with this `type`. + api_key.updated: + type: object + properties: + id: + type: string + description: The tracking ID of the API key. + changes_requested: + type: object + properties: + scopes: + type: array + items: type: string - nullable: true - description: The name of the parameter that caused the error, if applicable. - line: - type: integer - format: int32 - nullable: true - description: The line number of the input file where the error occurred, if applicable. - input_file_id: - type: string - description: The ID of the input file for the batch. - completion_window: - type: string - description: The time frame within which the batch should be processed. - status: - type: string - enum: - - validating - - failed - - in_progress - - finalizing - - completed - - expired - - cancelling - - cancelled - description: The current status of the batch. - output_file_id: - type: string - description: The ID of the file containing the outputs of successfully executed requests. - error_file_id: - type: string - description: The ID of the file containing the outputs of requests with errors. - created_at: - type: integer - format: unixtime + description: A list of scopes allowed for the API key, e.g. `["api.model.request"]` + description: The payload used to update the API key. + description: The details for events with this `type`. + api_key.deleted: + type: object + properties: + id: + type: string + description: The tracking ID of the API key. + description: The details for events with this `type`. + invite.sent: + type: object + properties: + id: + type: string + description: The ID of the invite. + data: + type: object + properties: + email: + type: string + description: The email invited to the organization. + role: + type: string + description: The role the email was invited to be. Is either `owner` or `member`. + description: The payload used to create the invite. + description: The details for events with this `type`. + invite.accepted: + type: object + properties: + id: + type: string + description: The ID of the invite. + description: The details for events with this `type`. + invite.deleted: + type: object + properties: + id: + type: string + description: The ID of the invite. + description: The details for events with this `type`. + login.failed: + type: object + properties: + error_code: + type: string + description: The error code of the failure. + error_message: + type: string + description: The error message of the failure. + description: The details for events with this `type`. + logout.failed: + type: object + properties: + error_code: + type: string + description: The error code of the failure. + error_message: + type: string + description: The error message of the failure. + description: The details for events with this `type`. + organization.updated: + type: object + properties: + id: + type: string + description: The organization ID. + changes_requested: + type: object + properties: + title: + type: string + description: The organization title. + description: + type: string + description: The organization description. + name: + type: string + description: The organization name. + settings: + type: object + properties: + threads_ui_visibility: + type: string + description: Visibility of the threads page which shows messages created with the Assistants API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`. + usage_dashboard_visibility: + type: string + description: Visibility of the usage dashboard which shows activity and costs for your organization. One of `ANY_ROLE` or `OWNERS`. + description: The payload used to update the organization settings. + description: The details for events with this `type`. + project.created: + type: object + properties: + id: + type: string + description: The project ID. + data: + type: object + properties: + name: + type: string + description: The project name. + title: + type: string + description: The title of the project as seen on the dashboard. + description: The payload used to create the project. + description: The details for events with this `type`. + project.updated: + type: object + properties: + id: + type: string + description: The project ID. + changes_requested: + type: object + properties: + title: + type: string + description: The title of the project as seen on the dashboard. + description: The payload used to update the project. + description: The details for events with this `type`. + project.archived: + type: object + properties: + id: + type: string + description: The project ID. + description: The details for events with this `type`. + service_account.created: + type: object + properties: + id: + type: string + description: The service account ID. + data: + type: object + properties: + role: + type: string + description: The role of the service account. Is either `owner` or `member`. + description: The payload used to create the service account. + description: The details for events with this `type`. + service_account.updated: + type: object + properties: + id: + type: string + description: The service account ID. + changes_requested: + type: object + properties: + role: + type: string + description: The role of the service account. Is either `owner` or `member`. + description: The payload used to updated the service account. + description: The details for events with this `type`. + service_account.deleted: + type: object + properties: + id: + type: string + description: The service account ID. + description: The details for events with this `type`. + user.added: + type: object + properties: + id: + type: string + description: The user ID. + data: + type: object + properties: + role: + type: string + description: The role of the user. Is either `owner` or `member`. + description: The payload used to add the user to the project. + description: The details for events with this `type`. + user.updated: + type: object + properties: + id: + type: string + description: The project ID. + changes_requested: + type: object + properties: + role: + type: string + description: The role of the user. Is either `owner` or `member`. + description: The payload used to update the user. + description: The details for events with this `type`. + user.deleted: + type: object + properties: + id: + type: string + description: The user ID. + description: The details for events with this `type`. + description: A log of a user action or configuration change within this organization. + AuditLogActor: + type: object + properties: + type: + type: string + enum: + - session + - api_key + description: The type of actor. Is either `session` or `api_key`. + session: + $ref: '#/components/schemas/AuditLogActorSession' + api_key: + $ref: '#/components/schemas/AuditLogActorApiKey' + description: The actor who performed the audit logged action. + AuditLogActorApiKey: + type: object + properties: + id: + type: string + description: The tracking id of the API key. + type: + type: string + enum: + - user + - service_account + description: The type of API key. Can be either `user` or `service_account`. + user: + $ref: '#/components/schemas/AuditLogActorUser' + service_account: + $ref: '#/components/schemas/AuditLogActorServiceAccount' + description: The API Key used to perform the audit logged action. + AuditLogActorServiceAccount: + type: object + properties: + id: + type: string + description: The service account id. + description: The service account that performed the audit logged action. + AuditLogActorSession: + type: object + properties: + user: + $ref: '#/components/schemas/AuditLogActorUser' + ip_address: + type: string + description: The IP address from which the action was performed. + description: The session in which the audit logged action was performed. + AuditLogActorUser: + type: object + properties: + id: + type: string + description: The user id. + email: + type: string + description: The user email. + description: The user who performed the audit logged action. + AuditLogEventType: + type: string + enum: + - api_key.created + - api_key.updated + - api_key.deleted + - invite.sent + - invite.accepted + - invite.deleted + - login.succeeded + - login.failed + - logout.succeeded + - logout.failed + - organization.updated + - project.created + - project.updated + - project.archived + - service_account.created + - service_account.updated + - service_account.deleted + - user.added + - user.updated + - user.deleted + description: The event type. + x-oaiExpandable: true + AutoChunkingStrategyRequestParam: + type: object + required: + - type + properties: + type: + type: string + enum: + - auto + description: Always `auto`. + allOf: + - $ref: '#/components/schemas/FileChunkingStrategyRequestParam' + description: The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. + AutoChunkingStrategyResponseParam: + type: object + required: + - type + properties: + type: + type: string + enum: + - auto + allOf: + - $ref: '#/components/schemas/FileChunkingStrategyResponseParam' + Batch: + type: object + required: + - id + - object + - endpoint + - input_file_id + - completion_window + - status + - created_at + properties: + id: + type: string + object: + type: string + enum: + - batch + description: The object type, which is always `batch`. + endpoint: + type: string + description: The OpenAI API endpoint used by the batch. + errors: + type: object + properties: + object: + type: string + enum: + - list + description: The object type, which is always `list`. + data: + type: array + items: + type: object + properties: + code: + type: string + description: An error code identifying the error type. + message: + type: string + description: A human-readable message providing more details about the error. + param: + type: string + nullable: true + description: The name of the parameter that caused the error, if applicable. + line: + type: integer + format: int32 + nullable: true + description: The line number of the input file where the error occurred, if applicable. + input_file_id: + type: string + description: The ID of the input file for the batch. + completion_window: + type: string + description: The time frame within which the batch should be processed. + status: + type: string + enum: + - validating + - failed + - in_progress + - finalizing + - completed + - expired + - cancelling + - cancelled + description: The current status of the batch. + output_file_id: + type: string + description: The ID of the file containing the outputs of successfully executed requests. + error_file_id: + type: string + description: The ID of the file containing the outputs of requests with errors. + created_at: + type: integer + format: unixtime description: The Unix timestamp (in seconds) for when the batch was created. in_progress_at: type: integer @@ -2489,9 +3005,17 @@ components: - role properties: content: - type: string + anyOf: + - type: string + - type: array + items: + $ref: '#/components/schemas/ChatCompletionRequestAssistantMessageContentPart' nullable: true description: The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified. + refusal: + type: string + nullable: true + description: The refusal message by the assistant. role: type: string enum: @@ -2519,6 +3043,11 @@ components: deprecated: true allOf: - $ref: '#/components/schemas/ChatCompletionRequestMessage' + ChatCompletionRequestAssistantMessageContentPart: + anyOf: + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartRefusal' + x-oaiExpandable: true ChatCompletionRequestFunctionMessage: type: object required: @@ -2558,11 +3087,6 @@ components: tool: '#/components/schemas/ChatCompletionRequestToolMessage' function: '#/components/schemas/ChatCompletionRequestFunctionMessage' x-oaiExpandable: true - ChatCompletionRequestMessageContentPart: - anyOf: - - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' - - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartImage' - x-oaiExpandable: true ChatCompletionRequestMessageContentPartImage: type: object required: @@ -2591,6 +3115,20 @@ components: default: auto required: - url + ChatCompletionRequestMessageContentPartRefusal: + type: object + required: + - type + - refusal + properties: + type: + type: string + enum: + - refusal + description: The type of the content part. + refusal: + type: string + description: The refusal message generated by the model. ChatCompletionRequestMessageContentPartText: type: object required: @@ -2612,7 +3150,11 @@ components: - role properties: content: - type: string + anyOf: + - type: string + - type: array + items: + $ref: '#/components/schemas/ChatCompletionRequestSystemMessageContentPart' description: The contents of the system message. role: type: string @@ -2624,6 +3166,11 @@ components: description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. allOf: - $ref: '#/components/schemas/ChatCompletionRequestMessage' + ChatCompletionRequestSystemMessageContentPart: + type: object + allOf: + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' + x-oaiExpandable: true ChatCompletionRequestToolMessage: type: object required: @@ -2637,13 +3184,22 @@ components: - tool description: The role of the messages author, in this case `tool`. content: - type: string + anyOf: + - type: string + - type: array + items: + $ref: '#/components/schemas/ChatCompletionRequestToolMessageContentPart' description: The contents of the tool message. tool_call_id: type: string description: Tool call that this message is responding to. allOf: - $ref: '#/components/schemas/ChatCompletionRequestMessage' + ChatCompletionRequestToolMessageContentPart: + type: object + allOf: + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' + x-oaiExpandable: true ChatCompletionRequestUserMessage: type: object required: @@ -2655,7 +3211,7 @@ components: - type: string - type: array items: - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPart' + $ref: '#/components/schemas/ChatCompletionRequestUserMessageContentPart' description: The contents of the user message. x-oaiExpandable: true role: @@ -2668,16 +3224,26 @@ components: description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. allOf: - $ref: '#/components/schemas/ChatCompletionRequestMessage' + ChatCompletionRequestUserMessageContentPart: + anyOf: + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartImage' + x-oaiExpandable: true ChatCompletionResponseMessage: type: object required: - content + - refusal - role properties: content: type: string nullable: true description: The contents of the message. + refusal: + type: string + nullable: true + description: The refusal message generated by the model. tool_calls: $ref: '#/components/schemas/ChatCompletionMessageToolCallsItem' role: @@ -2746,6 +3312,10 @@ components: - assistant - tool description: The role of the author of this message. + refusal: + type: string + nullable: true + description: The refusal message generated by the model. description: A chat completion delta generated by streamed model responses. ChatCompletionTokenLogprob: type: object @@ -2831,12 +3401,93 @@ components: x-oaiExpandable: true ChatMessageContentPart: type: object + ChatResponseFormat: + type: object + required: + - type + properties: + type: + type: string + discriminator: + propertyName: type + mapping: + text: '#/components/schemas/ChatResponseFormatText' + json_object: '#/components/schemas/ChatResponseFormatJsonObject' + json_schema: '#/components/schemas/ChatResponseFormatJsonSchema' + ChatResponseFormatJsonObject: + type: object + required: + - type + properties: + type: + type: string + enum: + - json_object + description: 'The type of response format being defined: `json_object`' + allOf: + - $ref: '#/components/schemas/ChatResponseFormat' + ChatResponseFormatJsonSchema: + type: object + required: + - type + - json_schema + properties: + type: + type: string + enum: + - json_schema + description: 'The type of response format being defined: `json_schema`' + json_schema: + type: object + properties: + description: + type: string + description: A description of what the response format is for, used by the model to determine how to respond in the format. + name: + type: string + description: The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + schema: + $ref: '#/components/schemas/ResponseFormatJsonSchemaSchema' + strict: + type: boolean + nullable: true + description: Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs). + default: false + required: + - name + allOf: + - $ref: '#/components/schemas/ChatResponseFormat' + ChatResponseFormatText: + type: object + required: + - type + properties: + type: + type: string + enum: + - text + description: 'The type of response format being defined: `text`' + allOf: + - $ref: '#/components/schemas/ChatResponseFormat' ChunkingStrategyRequestParam: anyOf: - $ref: '#/components/schemas/AutoChunkingStrategyRequestParam' - $ref: '#/components/schemas/StaticChunkingStrategyRequestParam' description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. x-oaiExpandable: true + CompleteUploadRequest: + type: object + required: + - part_ids + properties: + part_ids: + type: array + items: + type: string + description: The ordered list of Part IDs. + md5: + type: string + description: The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect. CompletionUsage: type: object required: @@ -2868,7 +3519,10 @@ components: - type: string enum: - gpt-4o + - gpt-4o-2024-08-06 - gpt-4o-2024-05-13 + - gpt-4o-mini + - gpt-4o-mini-2024-07-18 - gpt-4-turbo - gpt-4-turbo-2024-04-09 - gpt-4-0125-preview @@ -2926,9 +3580,7 @@ components: description: A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. default: [] file_search: - anyOf: - - $ref: '#/components/schemas/CreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences' - - $ref: '#/components/schemas/CreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers' + $ref: '#/components/schemas/ToolResourcesFileSearch' nullable: true description: A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. metadata: @@ -2961,49 +3613,6 @@ components: oneOf: - $ref: '#/components/schemas/AssistantsApiResponseFormatOption' nullable: true - CreateAssistantRequestToolResourcesFileSearchBase: - type: object - CreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers: - type: object - properties: - vector_stores: - type: array - items: - type: object - properties: - file_ids: - type: array - items: - type: string - maxItems: 10000 - description: |- - A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be - a maximum of 10000 files in a vector store. - metadata: - type: object - additionalProperties: - type: string - description: |- - Set of 16 key-value pairs that can be attached to a vector store. This can be useful for - storing additional information about the vector store in a structured format. Keys can - be a maximum of 64 characters long and values can be a maxium of 512 characters long. - x-oaiTypeLabel: map - maxItems: 1 - description: |- - A helper to create a [vector store](/docs/api-reference/vector-stores/object) with - file_ids and attach it to this assistant. There can be a maximum of 1 vector store - attached to the assistant. - CreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences: - type: object - properties: - vector_store_ids: - type: array - items: - type: string - maxItems: 1 - description: |- - The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. - There can be a maximum of 1 vector store attached to the assistant. CreateChatCompletionFunctionResponse: type: object required: @@ -3080,6 +3689,10 @@ components: enum: - gpt-4o - gpt-4o-2024-05-13 + - gpt-4o-2024-08-06 + - chatgpt-4o-latest + - gpt-4o-mini + - gpt-4o-mini-2024-07-18 - gpt-4-turbo - gpt-4-turbo-2024-04-09 - gpt-4-0125-preview @@ -3164,21 +3777,17 @@ components: [See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details) default: 0 response_format: - type: object - properties: - type: - type: string - enum: - - text - - json_object - description: Must be one of `text` or `json_object`. - default: text + allOf: + - $ref: '#/components/schemas/ChatResponseFormat' description: |- - An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + An object specifying the format that the model must output. Compatible with [GPT-4o](/docs/models/gpt-4o), [GPT-4o mini](/docs/models/gpt-4o-mini), [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which guarantees the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/docs/guides/structured-outputs). Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. + x-oaiExpandable: true seed: type: integer format: int64 @@ -3187,6 +3796,20 @@ components: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + service_tier: + type: string + enum: + - auto + - default + nullable: true + description: |- + Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service: + - If set to 'auto', the system will utilize scale tier credits until they are exhausted. + - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` utilized. + default: null stop: anyOf: - type: string @@ -3316,8 +3939,15 @@ components: $ref: '#/components/schemas/ChatCompletionTokenLogprob' nullable: true description: A list of message content tokens with log probability information. + refusal: + type: array + items: + $ref: '#/components/schemas/ChatCompletionTokenLogprob' + nullable: true + description: A list of message refusal tokens with log probability information. required: - content + - refusal nullable: true description: Log probability information for the choice. required: @@ -3333,6 +3963,13 @@ components: model: type: string description: The model used for the chat completion. + service_tier: + type: string + enum: + - scale + - default + nullable: true + description: The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request. system_fingerprint: type: string description: |- @@ -3375,8 +4012,15 @@ components: $ref: '#/components/schemas/ChatCompletionTokenLogprob' nullable: true description: A list of message content tokens with log probability information. + refusal: + type: array + items: + $ref: '#/components/schemas/ChatCompletionTokenLogprob' + nullable: true + description: A list of message refusal tokens with log probability information. required: - content + - refusal nullable: true description: Log probability information for the choice. finish_reason: @@ -3411,6 +4055,13 @@ components: model: type: string description: The model to generate the completion. + service_tier: + type: string + enum: + - scale + - default + nullable: true + description: The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request. system_fingerprint: type: string description: |- @@ -3833,9 +4484,10 @@ components: - babbage-002 - davinci-002 - gpt-3.5-turbo + - gpt-4o-mini description: |- The name of the model to fine-tune. You can select one of the - [supported models](/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + [supported models](/docs/guides/fine-tuning/which-models-can-be-fine-tuned). x-oaiTypeLabel: string training_file: type: string @@ -3850,41 +4502,8 @@ components: See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. hyperparameters: - type: object - properties: - batch_size: - anyOf: - - type: string - enum: - - auto - - type: integer - format: int32 - description: |- - Number of examples in each batch. A larger batch size means that model parameters - are updated less frequently, but with lower variance. - default: auto - learning_rate_multiplier: - anyOf: - - type: string - enum: - - auto - - type: number - format: float - description: |- - Scaling factor for the learning rate. A smaller learning rate may be useful to avoid - overfitting. - default: auto - n_epochs: - anyOf: - - type: string - enum: - - auto - - type: integer - format: int32 - description: |- - The number of epochs to train the model for. An epoch refers to one full cycle - through the training dataset. - default: auto + allOf: + - $ref: '#/components/schemas/CreateFineTuningJobRequestHyperparameters' description: The hyperparameters used for the fine-tuning job. suffix: type: string @@ -3894,7 +4513,7 @@ components: description: |- A string of up to 18 characters that will be added to your fine-tuned model name. - For example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + For example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. default: null validation_file: type: string @@ -3925,6 +4544,53 @@ components: description: |- The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases. If a seed is not specified, one will be generated for you. + CreateFineTuningJobRequestHyperparameters: + type: object + properties: + batch_size: + anyOf: + - $ref: '#/components/schemas/CreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum' + - type: integer + format: int32 + minimum: 1 + maximum: 256 + description: |- + Number of examples in each batch. A larger batch size means that model parameters + are updated less frequently, but with lower variance. + default: auto + learning_rate_multiplier: + anyOf: + - $ref: '#/components/schemas/CreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum' + - type: number + format: float + minimum: 0 + description: |- + Scaling factor for the learning rate. A smaller learning rate may be useful to avoid + overfitting. + default: auto + n_epochs: + anyOf: + - $ref: '#/components/schemas/CreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum' + - type: integer + format: int32 + minimum: 1 + maximum: 50 + description: |- + The number of epochs to train the model for. An epoch refers to one full cycle + through the training dataset. + default: auto + CreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum: + type: string + enum: + - auto + CreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum: + type: string + enum: + - auto + CreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum: + type: string + enum: + - auto CreateFineTuningJobRequestIntegrations: type: array items: @@ -4359,7 +5025,10 @@ components: - type: string enum: - gpt-4o + - gpt-4o-2024-08-06 - gpt-4o-2024-05-13 + - gpt-4o-mini + - gpt-4o-mini-2024-07-18 - gpt-4-turbo - gpt-4-turbo-2024-04-09 - gpt-4-0125-preview @@ -4535,7 +5204,10 @@ components: - type: string enum: - gpt-4o + - gpt-4o-2024-08-06 - gpt-4o-2024-05-13 + - gpt-4o-mini + - gpt-4o-mini-2024-07-18 - gpt-4-turbo - gpt-4-turbo-2024-04-09 - gpt-4-0125-preview @@ -4581,14 +5253,7 @@ components: description: A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. default: [] file_search: - type: object - properties: - vector_store_ids: - type: array - items: - type: string - maxItems: 1 - description: The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + $ref: '#/components/schemas/ToolResourcesFileSearchIdsOnly' nullable: true description: A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. metadata: @@ -4676,9 +5341,7 @@ components: description: A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. default: [] file_search: - anyOf: - - $ref: '#/components/schemas/CreateThreadRequestToolResourcesFileSearchVectorStoreIdReferences' - - $ref: '#/components/schemas/CreateThreadRequestToolResourcesFileSearchVectorStoreCreationHelpers' + $ref: '#/components/schemas/ToolResourcesFileSearch' nullable: true description: A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. metadata: @@ -4900,6 +5563,38 @@ components: items: $ref: '#/components/schemas/TranscriptionSegment' description: Segments of the translated text and their corresponding details. + CreateUploadRequest: + type: object + required: + - filename + - purpose + - bytes + - mime_type + properties: + filename: + type: string + description: The name of the file to upload. + purpose: + type: string + enum: + - assistants + - batch + - fine-tune + - vision + description: |- + The intended purpose of the uploaded file. + + See the [documentation on File purposes](/docs/api-reference/files/create#files-create-purpose). + bytes: + type: integer + format: int32 + description: The number of bytes in the file you are uploading. + mime_type: + type: string + description: |- + The MIME type of the file. + + This must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision. CreateVectorStoreFileBatchRequest: type: object required: @@ -4951,6 +5646,17 @@ components: nullable: true description: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. x-oaiTypeLabel: map + DefaultProjectErrorResponse: + type: object + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string DeleteAssistantResponse: type: object required: @@ -5126,8 +5832,8 @@ components: discriminator: propertyName: type mapping: - auto: '#/components/schemas/AutoChunkingStrategyResponseParam' other: '#/components/schemas/OtherChunkingStrategyResponseParam' + auto: '#/components/schemas/AutoChunkingStrategyResponseParam' FineTuneChatCompletionRequestAssistantMessage: type: object allOf: @@ -5227,21 +5933,8 @@ components: nullable: true description: The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be null if the fine-tuning job is still running. hyperparameters: - type: object - properties: - n_epochs: - anyOf: - - type: string - enum: - - auto - - type: integer - format: int32 - description: |- - The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. - "auto" decides the optimal number of epochs based on the size of the dataset. If setting the number manually, we support any number between 1 and 50 epochs. - default: auto - required: - - n_epochs + allOf: + - $ref: '#/components/schemas/FineTuningJobHyperparameters' description: The hyperparameters used for the fine-tuning job. See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. model: type: string @@ -5383,6 +6076,32 @@ components: enum: - fine_tuning.job.event description: Fine-tuning job event object + FineTuningJobHyperparameters: + type: object + required: + - n_epochs + properties: + n_epochs: + anyOf: + - $ref: '#/components/schemas/FineTuningJobHyperparametersNEpochsChoiceEnum' + - type: integer + format: int32 + description: |- + The number of epochs to train the model for. An epoch refers to one full cycle + through the training dataset. + default: auto + FineTuningJobHyperparametersBatchSizeChoiceEnum: + type: string + enum: + - auto + FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum: + type: string + enum: + - auto + FineTuningJobHyperparametersNEpochsChoiceEnum: + type: string + enum: + - auto FineTuningJobIntegrationsItem: type: array items: @@ -5443,6 +6162,11 @@ components: description: The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. parameters: $ref: '#/components/schemas/FunctionParameters' + strict: + type: boolean + nullable: true + description: Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](docs/guides/function-calling). + default: false FunctionParameters: type: object additionalProperties: {} @@ -5478,32 +6202,158 @@ components: type: array items: $ref: '#/components/schemas/Image' - ListAssistantsResponse: + Invite: type: object required: - object - - data - - first_id - - last_id - - has_more + - id + - email + - role + - status + - invited_at + - expires_at properties: object: type: string enum: - - list - data: - type: array - items: - $ref: '#/components/schemas/AssistantObject' - first_id: + - organization.invite + description: The object type, which is always `organization.invite` + id: type: string - last_id: + description: The identifier, which can be referenced in API endpoints + email: type: string - has_more: - type: boolean - ListBatchesResponse: - type: object - required: + description: The email address of the individual to whom the invite was sent + role: + type: string + enum: + - owner + - reader + description: '`owner` or `reader`' + status: + type: string + enum: + - accepted + - expired + - pending + description: '`accepted`,`expired`, or `pending`' + invited_at: + type: integer + format: unixtime + description: The Unix timestamp (in seconds) of when the invite was sent. + expires_at: + type: integer + format: unixtime + description: The Unix timestamp (in seconds) of when the invite expires. + accepted_at: + type: integer + format: unixtime + description: The Unix timestamp (in seconds) of when the invite was accepted. + description: Represents an individual `invite` to the organization. + InviteDeleteResponse: + type: object + required: + - object + - id + - deleted + properties: + object: + type: string + enum: + - organization.invite.deleted + description: The object type, which is always `organization.invite.deleted` + id: + type: string + deleted: + type: boolean + InviteListResponse: + type: object + required: + - object + - data + properties: + object: + type: string + enum: + - list + description: The object type, which is always `list` + data: + type: array + items: + $ref: '#/components/schemas/Invite' + first_id: + type: string + description: The first `invite_id` in the retrieved `list` + last_id: + type: string + description: The last `invite_id` in the retrieved `list` + has_more: + type: boolean + description: The `has_more` property is used for pagination to indicate there are additional results. + InviteRequest: + type: object + required: + - email + - role + properties: + email: + type: string + description: Send an email to this address + role: + type: string + enum: + - reader + - owner + description: '`owner` or `reader`' + ListAssistantsResponse: + type: object + required: + - object + - data + - first_id + - last_id + - has_more + properties: + object: + type: string + enum: + - list + data: + type: array + items: + $ref: '#/components/schemas/AssistantObject' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + ListAuditLogsResponse: + type: object + required: + - object + - data + - first_id + - last_id + - has_more + properties: + object: + type: string + enum: + - list + data: + type: array + items: + $ref: '#/components/schemas/AuditLog' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + ListBatchesResponse: + type: object + required: - data - has_more - object @@ -5822,6 +6672,22 @@ components: allOf: - $ref: '#/components/schemas/MessageContent' description: References an image URL in the content of a message. + MessageContentRefusalObject: + type: object + required: + - type + - refusal + properties: + type: + type: string + enum: + - refusal + description: Always `refusal`. + refusal: + type: string + allOf: + - $ref: '#/components/schemas/MessageContent' + description: The refusal content generated by the assistant. MessageContentTextAnnotationsFileCitationObject: type: object required: @@ -5949,6 +6815,7 @@ components: image_file: '#/components/schemas/MessageDeltaContentImageFileObject' image_url: '#/components/schemas/MessageDeltaContentImageUrlObject' text: '#/components/schemas/MessageDeltaContentTextObject' + refusal: '#/components/schemas/MessageDeltaContentRefusalObject' description: Represents a single piece of incremental content in an Assistants API streaming response. MessageDeltaContentImageFileObject: type: object @@ -6015,6 +6882,26 @@ components: allOf: - $ref: '#/components/schemas/MessageDeltaContent' description: References an image URL in the content of a message. + MessageDeltaContentRefusalObject: + type: object + required: + - index + - type + properties: + index: + type: integer + format: int32 + description: The index of the refusal part in the message. + type: + type: string + enum: + - refusal + description: Always `refusal`. + refusal: + type: string + allOf: + - $ref: '#/components/schemas/MessageDeltaContent' + description: The refusal content that is part of a message. MessageDeltaContentTextAnnotationsFileCitationObject: type: object required: @@ -6362,14 +7249,7 @@ components: description: Overrides the list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. default: [] file_search: - type: object - properties: - vector_store_ids: - type: array - items: - type: string - maxItems: 1 - description: Overrides the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + $ref: '#/components/schemas/ToolResourcesFileSearchIdsOnly' nullable: true description: A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. metadata: @@ -6439,14 +7319,7 @@ components: description: A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. default: [] file_search: - type: object - properties: - vector_store_ids: - type: array - items: - type: string - maxItems: 1 - description: The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. + $ref: '#/components/schemas/ToolResourcesFileSearchIdsOnly' nullable: true description: A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. metadata: @@ -6456,6 +7329,18 @@ components: nullable: true description: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. x-oaiTypeLabel: map + OmniTypedResponseFormat: + type: object + required: + - type + properties: + type: + type: string + discriminator: + propertyName: type + mapping: + json_object: '#/components/schemas/ResponseFormatJsonObject' + json_schema: '#/components/schemas/ResponseFormatJsonSchema' OpenAIFile: type: object required: @@ -6481,37 +7366,477 @@ components: description: The Unix timestamp (in seconds) for when the file was created. filename: type: string - description: The name of the file. - object: + description: The name of the file. + object: + type: string + enum: + - file + description: The object type, which is always `file`. + purpose: + type: string + enum: + - assistants + - assistants_output + - batch + - batch_output + - fine-tune + - fine-tune-results + - vision + description: The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results` and `vision`. + status: + type: string + enum: + - uploaded + - processed + - error + description: Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`. + deprecated: true + status_details: + type: string + description: Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`. + deprecated: true + description: The `File` object represents a document that has been uploaded to OpenAI. + OtherChunkingStrategyResponseParam: + type: object + required: + - type + properties: + type: + type: string + enum: + - other + description: Always `other`. + allOf: + - $ref: '#/components/schemas/FileChunkingStrategyResponseParam' + description: This is returned when the chunking strategy is unknown. Typically, this is because the file was indexed before the `chunking_strategy` concept was introduced in the API. + Project: + type: object + required: + - id + - object + - name + - created_at + - status + properties: + id: + type: string + description: The identifier, which can be referenced in API endpoints + object: + type: string + enum: + - organization.project + description: The object type, which is always `organization.project` + name: + type: string + description: The name of the project. This appears in reporting. + created_at: + type: integer + format: unixtime + description: The Unix timestamp (in seconds) of when the project was created. + archived_at: + type: integer + format: unixtime + nullable: true + description: The Unix timestamp (in seconds) of when the project was archived or `null`. + status: + type: string + enum: + - active + - archived + description: '`active` or `archived`' + description: Represents an individual project. + ProjectApiKey: + type: object + required: + - object + - redacted_value + - name + - created_at + - id + - owner + properties: + object: + type: string + enum: + - organization.project.api_key + description: The object type, which is always `organization.project.api_key` + redacted_value: + type: string + description: The redacted value of the API key + name: + type: string + description: The name of the API key + created_at: + type: integer + format: unixtime + description: The Unix timestamp (in seconds) of when the API key was created + id: + type: string + description: The identifier, which can be referenced in API endpoints + owner: + type: object + properties: + type: + type: string + enum: + - user + - service_account + description: '`user` or `service_account`' + user: + $ref: '#/components/schemas/ProjectUser' + service_account: + $ref: '#/components/schemas/ProjectServiceAccount' + description: Represents an individual API key in a project. + ProjectApiKeyDeleteResponse: + type: object + required: + - object + - id + - deleted + properties: + object: + type: string + enum: + - organization.project.api_key.deleted + id: + type: string + deleted: + type: boolean + ProjectApiKeyListResponse: + type: object + required: + - object + - data + - first_id + - last_id + - has_more + properties: + object: + type: string + enum: + - list + data: + type: array + items: + $ref: '#/components/schemas/ProjectApiKey' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + ProjectCreateRequest: + type: object + required: + - name + properties: + name: + type: string + description: The friendly name of the project, this name appears in reports. + ProjectListResponse: + type: object + required: + - object + - data + - first_id + - last_id + - has_more + properties: + object: + type: string + enum: + - list + data: + type: array + items: + $ref: '#/components/schemas/Project' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + ProjectServiceAccount: + type: object + required: + - object + - id + - name + - role + - created_at + properties: + object: + type: string + enum: + - organization.project.service_account + description: The object type, which is always `organization.project.service_account` + id: + type: string + description: The identifier, which can be referenced in API endpoints + name: + type: string + description: The name of the service account + role: + type: string + enum: + - owner + - member + description: '`owner` or `member`' + created_at: + type: integer + format: unixtime + description: The Unix timestamp (in seconds) of when the service account was created + description: Represents an individual service account in a project. + ProjectServiceAccountApiKey: + type: object + required: + - object + - value + - name + - created_at + - id + properties: + object: + type: string + enum: + - organization.project.service_account.api_key + description: The object type, which is always `organization.project.service_account.api_key` + value: + type: string + name: + type: string + created_at: + type: integer + format: unixtime + id: + type: string + ProjectServiceAccountCreateRequest: + type: object + required: + - name + properties: + name: + type: string + description: The name of the service account being created. + ProjectServiceAccountCreateResponse: + type: object + required: + - object + - id + - name + - role + - created_at + - api_key + properties: + object: + type: string + enum: + - organization.project.service_account + id: + type: string + name: + type: string + role: + type: string + enum: + - member + description: Service accounts can only have one role of type `member` + created_at: + type: integer + format: unixtime + api_key: + $ref: '#/components/schemas/ProjectServiceAccountApiKey' + ProjectServiceAccountDeleteResponse: + type: object + required: + - object + - id + - deleted + properties: + object: + type: string + enum: + - organization.project.service_account.deleted + id: + type: string + deleted: + type: boolean + ProjectServiceAccountListResponse: + type: object + required: + - object + - data + - first_id + - last_id + - has_more + properties: + object: + type: string + enum: + - list + data: + type: array + items: + $ref: '#/components/schemas/ProjectServiceAccount' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + ProjectUpdateRequest: + type: object + required: + - name + properties: + name: + type: string + description: The updated name of the project, this name appears in reports. + ProjectUser: + type: object + required: + - object + - id + - name + - email + - role + - added_at + properties: + object: + type: string + enum: + - organization.project.user + description: The object type, which is always `organization.project.user` + id: + type: string + description: The identifier, which can be referenced in API endpoints + name: + type: string + description: The name of the user + email: + type: string + description: The email address of the user + role: + type: string + enum: + - owner + - member + description: '`owner` or `member`' + added_at: + type: integer + format: unixtime + description: The Unix timestamp (in seconds) of when the project was added. + description: Represents an individual user in a project. + ProjectUserCreateRequest: + type: object + required: + - user_id + - role + properties: + user_id: + type: string + description: The ID of the user. + role: + type: string + enum: + - owner + - member + description: '`owner` or `member`' + ProjectUserDeleteResponse: + type: object + required: + - object + - id + - deleted + properties: + object: + type: string + enum: + - organization.project.user.deleted + id: + type: string + deleted: + type: boolean + ProjectUserListResponse: + type: object + required: + - object + - data + - first_id + - last_id + - has_more + properties: + object: + type: string + data: + type: array + items: + $ref: '#/components/schemas/ProjectUser' + first_id: + type: string + last_id: type: string - enum: - - file - description: The object type, which is always `file`. - purpose: + has_more: + type: boolean + ProjectUserUpdateRequest: + type: object + required: + - role + properties: + role: type: string enum: - - assistants - - assistants_output - - batch - - batch_output - - fine-tune - - fine-tune-results - - vision - description: The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results` and `vision`. - status: + - owner + - member + description: '`owner` or `member`' + ResponseFormatJsonObject: + type: object + required: + - type + properties: + type: type: string enum: - - uploaded - - processed - - error - description: Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`. - deprecated: true - status_details: + - json_object + description: 'The type of response format being defined: `json_object`' + allOf: + - $ref: '#/components/schemas/OmniTypedResponseFormat' + ResponseFormatJsonSchema: + type: object + required: + - type + - json_schema + properties: + type: type: string - description: Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`. - deprecated: true - description: The `File` object represents a document that has been uploaded to OpenAI. - OtherChunkingStrategyResponseParam: + enum: + - json_schema + description: 'The type of response format being defined: `json_schema`' + json_schema: + type: object + properties: + description: + type: string + description: A description of what the response format is for, used by the model to determine how to respond in the format. + name: + type: string + description: The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + schema: + $ref: '#/components/schemas/ResponseFormatJsonSchemaSchema' + strict: + type: boolean + nullable: true + description: Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs). + default: false + required: + - name + allOf: + - $ref: '#/components/schemas/OmniTypedResponseFormat' + ResponseFormatJsonSchemaSchema: + type: object + additionalProperties: {} + description: The schema for the response format, described as a JSON Schema object. + ResponseFormatText: type: object required: - type @@ -6519,11 +7844,10 @@ components: type: type: string enum: - - other - description: Always `other`. + - text + description: 'The type of response format being defined: `text`' allOf: - - $ref: '#/components/schemas/FileChunkingStrategyResponseParam' - description: This is returned when the chunking strategy is unknown. Typically, this is because the file was indexed before the `chunking_strategy` concept was introduced in the API. + - $ref: '#/components/schemas/OmniTypedResponseFormat' RunCompletionUsage: type: object required: @@ -7489,6 +8813,97 @@ components: description: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. x-oaiTypeLabel: map description: Represents a thread that contains [messages](/docs/api-reference/messages). + ToolResourcesFileSearch: + type: object + properties: + vector_store_ids: + type: array + items: + type: string + maxItems: 1 + description: |- + The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. + There can be a maximum of 1 vector store attached to the assistant. + vector_stores: + type: array + items: + type: object + properties: + file_ids: + type: array + items: + type: string + maxItems: 10000 + description: |- + A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be + a maximum of 10000 files in a vector store. + chunking_strategy: + anyOf: + - $ref: '#/components/schemas/AutoChunkingStrategyRequestParam' + - $ref: '#/components/schemas/StaticChunkingStrategyRequestParam' + description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. + x-oaiExpandable: true + metadata: + type: object + additionalProperties: + type: string + description: |- + Set of 16 key-value pairs that can be attached to a vector store. This can be useful for + storing additional information about the vector store in a structured format. Keys can + be a maximum of 64 characters long and values can be a maxium of 512 characters long. + x-oaiTypeLabel: map + maxItems: 1 + description: |- + A helper to create a [vector store](/docs/api-reference/vector-stores/object) with + file_ids and attach it to this assistant. There can be a maximum of 1 vector store + attached to the assistant. + ToolResourcesFileSearchIdsOnly: + type: object + properties: + vector_store_ids: + type: array + items: + type: string + maxItems: 1 + description: |- + The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. + There can be a maximum of 1 vector store attached to the assistant. + ToolResourcesFileSearchVectorStoreCreationHelpers: + type: object + properties: + vector_stores: + type: array + items: + type: object + properties: + file_ids: + type: array + items: + type: string + maxItems: 10000 + description: |- + A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be + a maximum of 10000 files in a vector store. + chunking_strategy: + anyOf: + - $ref: '#/components/schemas/AutoChunkingStrategyRequestParam' + - $ref: '#/components/schemas/StaticChunkingStrategyRequestParam' + description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. + x-oaiExpandable: true + metadata: + type: object + additionalProperties: + type: string + description: |- + Set of 16 key-value pairs that can be attached to a vector store. This can be useful for + storing additional information about the vector store in a structured format. Keys can + be a maximum of 64 characters long and values can be a maxium of 512 characters long. + x-oaiTypeLabel: map + maxItems: 1 + description: |- + A helper to create a [vector store](/docs/api-reference/vector-stores/object) with + file_ids and attach it to this assistant. There can be a maximum of 1 vector store + attached to the assistant. TranscriptionSegment: type: object required: @@ -7599,6 +9014,166 @@ components: nullable: true description: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. x-oaiTypeLabel: map + Upload: + type: object + required: + - id + - created_at + - filename + - bytes + - purpose + - status + - expires_at + properties: + id: + type: string + description: The Upload unique identifier, which can be referenced in API endpoints. + created_at: + type: integer + format: unixtime + description: The Unix timestamp (in seconds) for when the Upload was created. + filename: + type: string + description: The name of the file to be uploaded. + bytes: + type: integer + format: int32 + description: The intended number of bytes to be uploaded. + purpose: + type: string + description: The intended purpose of the file. [Please refer here](/docs/api-reference/files/object#files/object-purpose) for acceptable values. + status: + type: string + enum: + - pending + - completed + - cancelled + - expired + description: The status of the Upload. + expires_at: + type: integer + format: unixtime + description: The Unix timestamp (in seconds) for when the Upload was created. + object: + type: string + enum: + - upload + description: The object type, which is always "upload". + file: + type: object + allOf: + - $ref: '#/components/schemas/OpenAIFile' + nullable: true + description: The ready File object after the Upload is completed. + description: The Upload object can accept byte chunks in the form of Parts. + UploadPart: + type: object + required: + - id + - created_at + - upload_id + - object + properties: + id: + type: string + description: The upload Part unique identifier, which can be referenced in API endpoints. + created_at: + type: integer + format: unixtime + description: The Unix timestamp (in seconds) for when the Part was created. + upload_id: + type: string + description: The ID of the Upload object that this Part was added to. + object: + type: string + enum: + - upload.part + description: The object type, which is always `upload.part`. + description: The upload Part represents a chunk of bytes we can add to an Upload object. + User: + type: object + required: + - object + - id + - name + - email + - role + - added_at + properties: + object: + type: string + enum: + - organization.user + description: The object type, which is always `organization.user` + id: + type: string + description: The identifier, which can be referenced in API endpoints + name: + type: string + description: The name of the user + email: + type: string + description: The email address of the user + role: + type: string + enum: + - owner + - reader + description: '`owner` or `reader`' + added_at: + type: integer + format: unixtime + description: The Unix timestamp (in seconds) of when the user was added. + description: Represents an individual `user` within an organization. + UserDeleteResponse: + type: object + required: + - object + - id + - deleted + properties: + object: + type: string + enum: + - organization.user.deleted + id: + type: string + deleted: + type: boolean + UserListResponse: + type: object + required: + - object + - data + - first_id + - last_id + - has_more + properties: + object: + type: string + enum: + - list + data: + type: array + items: + $ref: '#/components/schemas/User' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + UserRoleUpdateRequest: + type: object + required: + - role + properties: + role: + type: string + enum: + - owner + - reader + description: '`owner` or `reader`' VectorStoreExpirationAfter: type: object required: @@ -7724,10 +9299,9 @@ components: code: type: string enum: - - internal_error - - file_not_found - - parsing_error - - unhandled_mime_type + - server_error + - unsupported_file + - invalid_file description: One of `server_error` or `rate_limit_exceeded`. message: type: string diff --git a/.scripts/Edit-Deserialization.ps1 b/.scripts/Edit-Deserialization.ps1 index 4b06ed331..04ef67266 100644 --- a/.scripts/Edit-Deserialization.ps1 +++ b/.scripts/Edit-Deserialization.ps1 @@ -4,7 +4,7 @@ $generatedModelFolder = Join-Path $repoRoot .dotnet\src\Generated\Models $files = Get-ChildItem -Path $generatedModelFolder -Filter "*Serialization.cs" $editedFilesCount = 0 - + foreach ($file in $files) { $statusText = "{0:D3}/{1:D3} : Processing codegen fixup for response deserialization..." -f $editedFilesCount, $files.Count $percentComplete = [math]::Round(($editedFilesCount / $files.Count) * 100) @@ -17,4 +17,5 @@ foreach ($file in $files) { $editedFilesCount++ } -Write-Progress -Activity "Complete" -PercentComplete 100 +Write-Progress -Activity "Editing" -Status "Complete" -Completed +Write-Output "Complete: deserialization edited." \ No newline at end of file diff --git a/.scripts/Invoke-CodeGen.ps1 b/.scripts/Invoke-CodeGen.ps1 index 827387ebc..1e999a5e7 100644 --- a/.scripts/Invoke-CodeGen.ps1 +++ b/.scripts/Invoke-CodeGen.ps1 @@ -7,6 +7,8 @@ function Invoke([scriptblock]$script) { & $script } +$scriptStartTime = Get-Date + Push-Location $repoRoot/.typespec try { Invoke { npm ci } @@ -19,3 +21,9 @@ try { finally { Pop-Location } + +$scriptElapsed = $(Get-Date) - $scriptStartTime +$scriptElapsedSeconds = [math]::Round($scriptElapsed.TotalSeconds, 1) +$scriptName = $MyInvocation.MyCommand.Name + +Write-Host "${scriptName} complete. Time: ${scriptElapsedSeconds}s" \ No newline at end of file diff --git a/.typespec/administration/main.tsp b/.typespec/administration/main.tsp new file mode 100644 index 000000000..5ad1d3a2b --- /dev/null +++ b/.typespec/administration/main.tsp @@ -0,0 +1 @@ +import "./models.tsp"; diff --git a/.typespec/administration/models.tsp b/.typespec/administration/models.tsp new file mode 100644 index 000000000..f429a8929 --- /dev/null +++ b/.typespec/administration/models.tsp @@ -0,0 +1,748 @@ +/* + * This file was automatically generated from an OpenAPI .yaml file. + * Edits made directly to this file will be lost. + */ + +using TypeSpec.OpenAPI; + +namespace OpenAI; + +/** The service account that performed the audit logged action. */ +model AuditLogActorServiceAccount { + /** The service account id. */ + id?: string; +} + +/** The user who performed the audit logged action. */ +model AuditLogActorUser { + /** The user id. */ + id?: string; + + /** The user email. */ + email?: string; +} + +/** The API Key used to perform the audit logged action. */ +model AuditLogActorApiKey { + /** The tracking id of the API key. */ + id?: string; + + @doc(""" + The type of API key. Can be either `user` or `service_account`. + """) + type?: "user" | "service_account"; + + user?: AuditLogActorUser; + service_account?: AuditLogActorServiceAccount; +} + +/** The session in which the audit logged action was performed. */ +model AuditLogActorSession { + user?: AuditLogActorUser; + + /** The IP address from which the action was performed. */ + ip_address?: string; +} + +/** The actor who performed the audit logged action. */ +model AuditLogActor { + @doc(""" + The type of actor. Is either `session` or `api_key`. + """) + type?: "session" | "api_key"; + + session?: AuditLogActorSession; + api_key?: AuditLogActorApiKey; +} + +/** The event type. */ +@extension("x-oaiExpandable", true) +union AuditLogEventType { + "api_key.created", + "api_key.updated", + "api_key.deleted", + "invite.sent", + "invite.accepted", + "invite.deleted", + "login.succeeded", + "login.failed", + "logout.succeeded", + "logout.failed", + "organization.updated", + "project.created", + "project.updated", + "project.archived", + "service_account.created", + "service_account.updated", + "service_account.deleted", + "user.added", + "user.updated", + "user.deleted", +} + +/** A log of a user action or configuration change within this organization. */ +model AuditLog { + /** The ID of this log. */ + id: string; + + type: AuditLogEventType; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + /** The Unix timestamp (in seconds) of the event. */ + @encode("unixTimestamp", int32) + effective_at: utcDateTime; + + /** The project that the action was scoped to. Absent for actions not scoped to projects. */ + project?: { + /** The project ID. */ + id?: string; + + /** The project title. */ + name?: string; + }; + + actor: AuditLogActor; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "api_key.created") + api_key_created?: { + /** The tracking ID of the API key. */ + id?: string; + + /** The payload used to create the API key. */ + data?: { + @doc(""" + A list of scopes allowed for the API key, e.g. `["api.model.request"]` + """) + scopes?: string[]; + }; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "api_key.updated") + api_key_updated?: { + /** The tracking ID of the API key. */ + id?: string; + + /** The payload used to update the API key. */ + changes_requested?: { + @doc(""" + A list of scopes allowed for the API key, e.g. `["api.model.request"]` + """) + scopes?: string[]; + }; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "api_key.deleted") + api_key_deleted?: { + /** The tracking ID of the API key. */ + id?: string; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "invite.sent") + invite_sent?: { + /** The ID of the invite. */ + id?: string; + + /** The payload used to create the invite. */ + data?: { + /** The email invited to the organization. */ + email?: string; + + @doc(""" + The role the email was invited to be. Is either `owner` or `member`. + """) + role?: string; + }; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "invite.accepted") + invite_accepted?: { + /** The ID of the invite. */ + id?: string; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "invite.deleted") + invite_deleted?: { + /** The ID of the invite. */ + id?: string; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "login.failed") + login_failed?: { + /** The error code of the failure. */ + error_code?: string; + + /** The error message of the failure. */ + error_message?: string; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "logout.failed") + logout_failed?: { + /** The error code of the failure. */ + error_code?: string; + + /** The error message of the failure. */ + error_message?: string; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "organization.updated") + organization_updated?: { + /** The organization ID. */ + id?: string; + + /** The payload used to update the organization settings. */ + changes_requested?: { + /** The organization title. */ + title?: string; + + /** The organization description. */ + description?: string; + + /** The organization name. */ + name?: string; + + settings?: { + @doc(""" + Visibility of the threads page which shows messages created with the Assistants API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`. + """) + threads_ui_visibility?: string; + + @doc(""" + Visibility of the usage dashboard which shows activity and costs for your organization. One of `ANY_ROLE` or `OWNERS`. + """) + usage_dashboard_visibility?: string; + }; + }; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "project.created") + project_created?: { + /** The project ID. */ + id?: string; + + /** The payload used to create the project. */ + data?: { + /** The project name. */ + name?: string; + + /** The title of the project as seen on the dashboard. */ + title?: string; + }; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "project.updated") + project_updated?: { + /** The project ID. */ + id?: string; + + /** The payload used to update the project. */ + changes_requested?: { + /** The title of the project as seen on the dashboard. */ + title?: string; + }; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "project.archived") + project_archived?: { + /** The project ID. */ + id?: string; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "service_account.created") + service_account_created?: { + /** The service account ID. */ + id?: string; + + /** The payload used to create the service account. */ + data?: { + @doc(""" + The role of the service account. Is either `owner` or `member`. + """) + role?: string; + }; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "service_account.updated") + service_account_updated?: { + /** The service account ID. */ + id?: string; + + /** The payload used to updated the service account. */ + changes_requested?: { + @doc(""" + The role of the service account. Is either `owner` or `member`. + """) + role?: string; + }; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "service_account.deleted") + service_account_deleted?: { + /** The service account ID. */ + id?: string; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "user.added") + user_added?: { + /** The user ID. */ + id?: string; + + /** The payload used to add the user to the project. */ + data?: { + @doc(""" + The role of the user. Is either `owner` or `member`. + """) + role?: string; + }; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "user.updated") + user_updated?: { + /** The project ID. */ + id?: string; + + /** The payload used to update the user. */ + changes_requested?: { + @doc(""" + The role of the user. Is either `owner` or `member`. + """) + role?: string; + }; + }; + + @doc(""" + The details for events with this `type`. + """) + @encodedName("application/json", "user.deleted") + user_deleted?: { + /** The user ID. */ + id?: string; + }; +} + +model ListAuditLogsResponse { + object: "list"; + data: AuditLog[]; + first_id: string; + last_id: string; + has_more: boolean; +} + +@doc(""" + Represents an individual `invite` to the organization. + """) +model Invite { + @doc(""" + The object type, which is always `organization.invite` + """) + object: "organization.invite"; + + /** The identifier, which can be referenced in API endpoints */ + id: string; + + /** The email address of the individual to whom the invite was sent */ + email: string; + + @doc(""" + `owner` or `reader` + """) + role: "owner" | "reader"; + + @doc(""" + `accepted`,`expired`, or `pending` + """) + status: "accepted" | "expired" | "pending"; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + /** The Unix timestamp (in seconds) of when the invite was sent. */ + @encode("unixTimestamp", int32) + invited_at: utcDateTime; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + /** The Unix timestamp (in seconds) of when the invite expires. */ + @encode("unixTimestamp", int32) + expires_at: utcDateTime; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + /** The Unix timestamp (in seconds) of when the invite was accepted. */ + @encode("unixTimestamp", int32) + accepted_at?: utcDateTime; +} + +model InviteListResponse { + @doc(""" + The object type, which is always `list` + """) + object: "list"; + + data: Invite[]; + + @doc(""" + The first `invite_id` in the retrieved `list` + """) + first_id?: string; + + @doc(""" + The last `invite_id` in the retrieved `list` + """) + last_id?: string; + + @doc(""" + The `has_more` property is used for pagination to indicate there are additional results. + """) + has_more?: boolean; +} + +model InviteRequest { + /** Send an email to this address */ + email: string; + + @doc(""" + `owner` or `reader` + """) + role: "reader" | "owner"; +} + +model InviteDeleteResponse { + @doc(""" + The object type, which is always `organization.invite.deleted` + """) + object: "organization.invite.deleted"; + + id: string; + deleted: boolean; +} + +@doc(""" + Represents an individual `user` within an organization. + """) +model User { + @doc(""" + The object type, which is always `organization.user` + """) + object: "organization.user"; + + /** The identifier, which can be referenced in API endpoints */ + id: string; + + /** The name of the user */ + name: string; + + /** The email address of the user */ + email: string; + + @doc(""" + `owner` or `reader` + """) + role: "owner" | "reader"; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + /** The Unix timestamp (in seconds) of when the user was added. */ + @encode("unixTimestamp", int32) + added_at: utcDateTime; +} + +model UserListResponse { + object: "list"; + data: User[]; + first_id: string; + last_id: string; + has_more: boolean; +} + +model UserRoleUpdateRequest { + @doc(""" + `owner` or `reader` + """) + role: "owner" | "reader"; +} + +model UserDeleteResponse { + object: "organization.user.deleted"; + id: string; + deleted: boolean; +} + +/** Represents an individual project. */ +model Project { + /** The identifier, which can be referenced in API endpoints */ + id: string; + + @doc(""" + The object type, which is always `organization.project` + """) + object: "organization.project"; + + /** The name of the project. This appears in reporting. */ + name: string; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + /** The Unix timestamp (in seconds) of when the project was created. */ + @encode("unixTimestamp", int32) + created_at: utcDateTime; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + @doc(""" + The Unix timestamp (in seconds) of when the project was archived or `null`. + """) + @encode("unixTimestamp", int32) + archived_at?: utcDateTime | null; + + @doc(""" + `active` or `archived` + """) + status: "active" | "archived"; +} + +model ProjectListResponse { + object: "list"; + data: Project[]; + first_id: string; + last_id: string; + has_more: boolean; +} + +model ProjectCreateRequest { + /** The friendly name of the project, this name appears in reports. */ + name: string; +} + +model ProjectUpdateRequest { + /** The updated name of the project, this name appears in reports. */ + name: string; +} + +model DefaultProjectErrorResponse { + code: int32; + message: string; +} + +/** Represents an individual user in a project. */ +model ProjectUser { + @doc(""" + The object type, which is always `organization.project.user` + """) + object: "organization.project.user"; + + /** The identifier, which can be referenced in API endpoints */ + id: string; + + /** The name of the user */ + name: string; + + /** The email address of the user */ + email: string; + + @doc(""" + `owner` or `member` + """) + role: "owner" | "member"; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + /** The Unix timestamp (in seconds) of when the project was added. */ + @encode("unixTimestamp", int32) + added_at: utcDateTime; +} + +model ProjectUserListResponse { + object: string; + data: ProjectUser[]; + first_id: string; + last_id: string; + has_more: boolean; +} + +model ProjectUserCreateRequest { + /** The ID of the user. */ + user_id: string; + + @doc(""" + `owner` or `member` + """) + role: "owner" | "member"; +} + +model ProjectUserUpdateRequest { + @doc(""" + `owner` or `member` + """) + role: "owner" | "member"; +} + +model ProjectUserDeleteResponse { + object: "organization.project.user.deleted"; + id: string; + deleted: boolean; +} + +/** Represents an individual service account in a project. */ +model ProjectServiceAccount { + @doc(""" + The object type, which is always `organization.project.service_account` + """) + object: "organization.project.service_account"; + + /** The identifier, which can be referenced in API endpoints */ + id: string; + + /** The name of the service account */ + name: string; + + @doc(""" + `owner` or `member` + """) + role: "owner" | "member"; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + /** The Unix timestamp (in seconds) of when the service account was created */ + @encode("unixTimestamp", int32) + created_at: utcDateTime; +} + +model ProjectServiceAccountListResponse { + object: "list"; + data: ProjectServiceAccount[]; + first_id: string; + last_id: string; + has_more: boolean; +} + +model ProjectServiceAccountCreateRequest { + /** The name of the service account being created. */ + name: string; +} + +model ProjectServiceAccountCreateResponse { + object: "organization.project.service_account"; + id: string; + name: string; + + @doc(""" + Service accounts can only have one role of type `member` + """) + role: "member"; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + @encode("unixTimestamp", int32) + created_at: utcDateTime; + + api_key: ProjectServiceAccountApiKey; +} + +model ProjectServiceAccountApiKey { + @doc(""" + The object type, which is always `organization.project.service_account.api_key` + """) + object: "organization.project.service_account.api_key"; + + value: string; + name: string; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + @encode("unixTimestamp", int32) + created_at: utcDateTime; + + id: string; +} + +model ProjectServiceAccountDeleteResponse { + object: "organization.project.service_account.deleted"; + id: string; + deleted: boolean; +} + +/** Represents an individual API key in a project. */ +model ProjectApiKey { + @doc(""" + The object type, which is always `organization.project.api_key` + """) + object: "organization.project.api_key"; + + /** The redacted value of the API key */ + redacted_value: string; + + /** The name of the API key */ + name: string; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + /** The Unix timestamp (in seconds) of when the API key was created */ + @encode("unixTimestamp", int32) + created_at: utcDateTime; + + /** The identifier, which can be referenced in API endpoints */ + id: string; + + owner: { + @doc(""" + `user` or `service_account` + """) + type?: "user" | "service_account"; + + user?: ProjectUser; + service_account?: ProjectServiceAccount; + }; +} + +model ProjectApiKeyListResponse { + object: "list"; + data: ProjectApiKey[]; + first_id: string; + last_id: string; + has_more: boolean; +} + +model ProjectApiKeyDeleteResponse { + object: "organization.project.api_key.deleted"; + id: string; + deleted: boolean; +} diff --git a/.typespec/assistants/client.tsp b/.typespec/assistants/client.tsp index 14b94df7b..1e238b5ec 100644 --- a/.typespec/assistants/client.tsp +++ b/.typespec/assistants/client.tsp @@ -8,5 +8,5 @@ using OpenAI; @@access(AssistantResponseFormat, Access.public); @@usage(AssistantResponseFormat, Usage.input); -@@access(CreateAssistantRequestToolResourcesFileSearchBase, Access.public); -@@usage(CreateAssistantRequestToolResourcesFileSearchBase, Usage.input); +@@access(ToolResourcesFileSearchVectorStoreCreationHelper, Access.public); +@@usage(ToolResourcesFileSearchVectorStoreCreationHelper, Usage.input); diff --git a/.typespec/assistants/custom.tsp b/.typespec/assistants/custom.tsp index 8b99ad448..e557bac28 100644 --- a/.typespec/assistants/custom.tsp +++ b/.typespec/assistants/custom.tsp @@ -1,18 +1,23 @@ import "@azure-tools/typespec-client-generator-core"; +import "@typespec/http"; +import "../common/models.tsp"; +import "../vector-stores/models.tsp"; using Azure.ClientGenerator.Core; using TypeSpec.OpenAPI; +using TypeSpec.Http; namespace OpenAI; // This customization allows us to concretely specify that the file_search object must provide // either ID references --or-- in-line creation helpers, but not both. -alias CreateAssistantRequestToolResourcesFileSearch = CreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences | CreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers; - -model CreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences { - ...CreateAssistantRequestToolResourcesFileSearchBase; +model ToolResourcesFileSearch { + ...ToolResourcesFileSearchIdsOnly; + ...ToolResourcesFileSearchVectorStoreCreationHelpers; +} +model ToolResourcesFileSearchIdsOnly { /** * The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. * There can be a maximum of 1 vector store attached to the assistant. @@ -21,23 +26,17 @@ model CreateAssistantRequestToolResourcesFileSearchVectorStoreIdReferences { vector_store_ids?: string[]; } -model CreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelpers { - ...CreateAssistantRequestToolResourcesFileSearchBase; - +model ToolResourcesFileSearchVectorStoreCreationHelpers { /** * A helper to create a [vector store](/docs/api-reference/vector-stores/object) with * file_ids and attach it to this assistant. There can be a maximum of 1 vector store * attached to the assistant. */ @maxItems(1) - vector_stores?: CreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelper[]; + vector_stores?: ToolResourcesFileSearchVectorStoreCreationHelper[]; } -model CreateAssistantRequestToolResourcesFileSearchBase { - // Common fields (currently none) -} - -alias CreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelper = { +alias ToolResourcesFileSearchVectorStoreCreationHelper = { /** * A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be * a maximum of 10000 files in a vector store. @@ -45,6 +44,12 @@ alias CreateAssistantRequestToolResourcesFileSearchVectorStoreCreationHelper = { @maxItems(10000) file_ids?: string[]; + @doc(""" + The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. + """) + @extension("x-oaiExpandable", true) + chunking_strategy?: AutoChunkingStrategyRequestParam | StaticChunkingStrategyRequestParam; + /** * Set of 16 key-value pairs that can be attached to a vector store. This can be useful for * storing additional information about the vector store in a structured format. Keys can @@ -59,4 +64,20 @@ model AssistantToolDefinition { type: string; } -model AssistantResponseFormat {} +@encodedName("application/json", "") +@discriminator("type") +model AssistantResponseFormat { + ...OmniTypedResponseFormat; +} + +model AssistantResponseFormatText extends AssistantResponseFormat { + ...ResponseFormatText; +} + +model AssistantResponseFormatJsonObject extends AssistantResponseFormat { + ...ResponseFormatJsonObject; +} + +model AssistantResponseFormatJsonSchema extends AssistantResponseFormat { + ...ResponseFormatJsonSchema; +} diff --git a/.typespec/assistants/models.tsp b/.typespec/assistants/models.tsp index b0a4e3852..9eda287ad 100644 --- a/.typespec/assistants/models.tsp +++ b/.typespec/assistants/models.tsp @@ -13,24 +13,18 @@ namespace OpenAI; @doc(""" Specifies the format that the model must output. Compatible with [GPT-4o](/docs/models/gpt-4o), [GPT-4 Turbo](/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which guarantees the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. """) @extension("x-oaiExpandable", true) union AssistantsApiResponseFormatOption { - "none" | "auto", - AssistantsApiResponseFormat, -} - -@doc(""" - An object describing the expected output of the model. If `json_object` only `function` type `tools` are allowed to be passed to the Run. If `text` the model can return text or any value needed. - """) -model AssistantsApiResponseFormat { - @doc(""" - Must be one of `text` or `json_object`. - """) - type?: "text" | "json_object" = "text"; + "auto", + ResponseFormatText, + ResponseFormatJsonObject, + ResponseFormatJsonSchema, } model CreateAssistantRequest { @@ -39,7 +33,10 @@ model CreateAssistantRequest { `model`: | string | "gpt-4o" + | "gpt-4o-2024-08-06" | "gpt-4o-2024-05-13" + | "gpt-4o-mini" + | "gpt-4o-mini-2024-07-18" | "gpt-4-turbo" | "gpt-4-turbo-2024-04-09" | "gpt-4-0125-preview" @@ -77,7 +74,7 @@ model CreateAssistantRequest { """) @maxItems(128) @extension("x-oaiExpandable", true) - tools?: AssistantToolDefinition[] = []; + tools?: AssistantToolDefinition[] = #[]; @doc(""" A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. @@ -88,11 +85,11 @@ model CreateAssistantRequest { A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. """) @maxItems(20) - file_ids?: string[] = []; + file_ids?: string[] = #[]; }; // Tool customization: use custom type for sophisticated union - file_search?: CreateAssistantRequestToolResourcesFileSearch; + file_search?: ToolResourcesFileSearch; } | null; /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */ @@ -138,7 +135,7 @@ model ModifyAssistantRequest { """) @maxItems(128) @extension("x-oaiExpandable", true) - tools?: AssistantToolDefinition[] = []; + tools?: AssistantToolDefinition[] = #[]; @doc(""" A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. @@ -149,13 +146,11 @@ model ModifyAssistantRequest { Overrides the list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. """) @maxItems(20) - file_ids?: string[] = []; - }; - file_search?: { - /** Overrides the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. */ - @maxItems(1) - vector_store_ids?: string[]; + file_ids?: string[] = #[]; }; + + // Tool customization: use custom type for sophisticated union + file_search?: ToolResourcesFileSearchIdsOnly; } | null; /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */ @@ -213,7 +208,7 @@ model AssistantToolsFileSearch extends AssistantToolDefinition { /** Overrides for the file search tool. */ file_search?: { @doc(""" - The maximum number of results the file search tool should output. The default is 20 for gpt-4* models and 5 for gpt-3.5-turbo. This number should be between 1 and 50 inclusive. + The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive. Note that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](/docs/assistants/tools/file-search/number-of-chunks-returned) for more information. """) @@ -278,7 +273,7 @@ model AssistantObject { """) @maxItems(128) @extension("x-oaiExpandable", true) - tools: AssistantToolDefinition[] = []; + tools: AssistantToolDefinition[] = #[]; @doc(""" A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. @@ -289,13 +284,11 @@ model AssistantObject { A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool. """) @maxItems(20) - file_ids?: string[] = []; - }; - file_search?: { - /** The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. */ - @maxItems(1) - vector_store_ids?: string[]; + file_ids?: string[] = #[]; }; + + // Tool customization: use custom type for sophisticated union + file_search?: ToolResourcesFileSearchIdsOnly; } | null; /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */ diff --git a/.typespec/audio/models.tsp b/.typespec/audio/models.tsp index 78b0f0d8e..46d50d08a 100644 --- a/.typespec/audio/models.tsp +++ b/.typespec/audio/models.tsp @@ -69,7 +69,7 @@ model CreateTranscriptionRequest { @doc(""" The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. """) - timestamp_granularities?: ("word" | "segment")[] = ["segment"]; + timestamp_granularities?: ("word" | "segment")[] = #["segment"]; } model CreateTranslationRequest { @@ -116,7 +116,7 @@ model CreateTranscriptionResponseVerboseJson { /** The language of the input audio. */ language: string; - // Tool customization: timespans are encoded durations + // Tool customization: correct erroneous spec representation of duration as string /** The duration of the input audio. */ @encode("seconds", float32) duration: duration; @@ -145,7 +145,7 @@ model CreateTranslationResponseVerboseJson { """) language: string; - // Tool customization: timespans are encoded durations + // Tool customization: correct erroneous spec representation of duration as string /** The duration of the input audio. */ @encode("seconds", float32) duration: duration; diff --git a/.typespec/chat/client.tsp b/.typespec/chat/client.tsp index efca74507..a0a6d9bc8 100644 --- a/.typespec/chat/client.tsp +++ b/.typespec/chat/client.tsp @@ -22,3 +22,6 @@ using OpenAI; @@access(CreateChatCompletionStreamResponse, Access.public); @@usage(CreateChatCompletionStreamResponse, Usage.output); + +@@access(ChatResponseFormatJsonSchema, Access.public); +@@usage(ChatResponseFormatJsonSchema, Usage.input); diff --git a/.typespec/chat/custom.tsp b/.typespec/chat/custom.tsp index 44347ce21..9e98e5c90 100644 --- a/.typespec/chat/custom.tsp +++ b/.typespec/chat/custom.tsp @@ -1,7 +1,27 @@ +import "../common"; + using TypeSpec.OpenAPI; namespace OpenAI; +@encodedName("application/json", "") +@discriminator("type") +model ChatResponseFormat { + ...OmniTypedResponseFormat; +} + +model ChatResponseFormatText extends ChatResponseFormat { + ...ResponseFormatText; +} + +model ChatResponseFormatJsonObject extends ChatResponseFormat { + ...ResponseFormatJsonObject; +} + +model ChatResponseFormatJsonSchema extends ChatResponseFormat { + ...ResponseFormatJsonSchema; +} + model ChatCompletionFunctionChoice {} model ChatCompletionToolChoice {} diff --git a/.typespec/chat/models.tsp b/.typespec/chat/models.tsp index 55428b5e4..84f8e2b39 100644 --- a/.typespec/chat/models.tsp +++ b/.typespec/chat/models.tsp @@ -24,6 +24,10 @@ model CreateChatCompletionRequest { | string | "gpt-4o" | "gpt-4o-2024-05-13" + | "gpt-4o-2024-08-06" + | "chatgpt-4o-latest" + | "gpt-4o-mini" + | "gpt-4o-mini-2024-07-18" | "gpt-4-turbo" | "gpt-4-turbo-2024-04-09" | "gpt-4-0125-preview" @@ -96,19 +100,18 @@ model CreateChatCompletionRequest { @maxValue(2) presence_penalty?: float32 | null = 0; + // Tool customization: apply a named union type @doc(""" - An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + An object specifying the format that the model must output. Compatible with [GPT-4o](/docs/models/gpt-4o), [GPT-4o mini](/docs/models/gpt-4o-mini), [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which guarantees the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/docs/guides/structured-outputs). Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. """) - response_format?: { - @doc(""" - Must be one of `text` or `json_object`. - """) - type?: "text" | "json_object" = "text"; - }; + @extension("x-oaiExpandable", true) + response_format?: ChatResponseFormat; @doc(""" This feature is in Beta. @@ -119,6 +122,16 @@ model CreateChatCompletionRequest { @maxValue(9223372036854775807) seed?: int64 | null; + @doc(""" + Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service: + - If set to 'auto', the system will utilize scale tier credits until they are exhausted. + - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` utilized. + """) + service_tier?: "auto" | "default" | null = null; + /** Up to 4 sequences where the API will stop generating further tokens. */ stop?: string | string[] | null = null; @@ -212,6 +225,9 @@ model CreateChatCompletionResponse { logprobs: { /** A list of message content tokens with log probability information. */ content: ChatCompletionTokenLogprob[] | null; + + /** A list of message refusal tokens with log probability information. */ + refusal: ChatCompletionTokenLogprob[] | null; } | null; }[]; @@ -223,6 +239,11 @@ model CreateChatCompletionResponse { /** The model used for the chat completion. */ `model`: string; + @doc(""" + The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request. + """) + service_tier?: "scale" | "default" | null; + @doc(""" This fingerprint represents the backend configuration that the model runs with. @@ -275,12 +296,6 @@ union ChatCompletionToolChoiceOption { ChatCompletionNamedToolChoice, } -@extension("x-oaiExpandable", true) -union ChatCompletionRequestMessageContentPart { - ChatCompletionRequestMessageContentPartText, - ChatCompletionRequestMessageContentPartImage, -} - model ChatCompletionRequestMessageContentPartText { /** The type of the content part. */ type: "text"; @@ -303,6 +318,14 @@ model ChatCompletionRequestMessageContentPartImage { }; } +model ChatCompletionRequestMessageContentPartRefusal { + /** The type of the content part. */ + type: "refusal"; + + /** The refusal message generated by the model. */ + refusal: string; +} + model ChatCompletionMessageToolCall { /** The ID of the tool call. */ id: string; @@ -330,10 +353,32 @@ model ChatCompletionRequestMessage { role: string; } +@extension("x-oaiExpandable", true) +union ChatCompletionRequestSystemMessageContentPart { + ChatCompletionRequestMessageContentPartText, +} + +@extension("x-oaiExpandable", true) +union ChatCompletionRequestUserMessageContentPart { + ChatCompletionRequestMessageContentPartText, + ChatCompletionRequestMessageContentPartImage, +} + +@extension("x-oaiExpandable", true) +union ChatCompletionRequestAssistantMessageContentPart { + ChatCompletionRequestMessageContentPartText, + ChatCompletionRequestMessageContentPartRefusal, +} + +@extension("x-oaiExpandable", true) +union ChatCompletionRequestToolMessageContentPart { + ChatCompletionRequestMessageContentPartText, +} + // Tool customization: apply discriminated type base model ChatCompletionRequestSystemMessage extends ChatCompletionRequestMessage { /** The contents of the system message. */ - content: string; + content: string | ChatCompletionRequestSystemMessageContentPart[]; @doc(""" The role of the messages author, in this case `system`. @@ -348,7 +393,7 @@ model ChatCompletionRequestSystemMessage extends ChatCompletionRequestMessage { model ChatCompletionRequestUserMessage extends ChatCompletionRequestMessage { /** The contents of the user message. */ @extension("x-oaiExpandable", true) - content: string | ChatCompletionRequestMessageContentPart[]; + content: string | ChatCompletionRequestUserMessageContentPart[]; @doc(""" The role of the messages author, in this case `user`. @@ -365,7 +410,10 @@ model ChatCompletionRequestAssistantMessage @doc(""" The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified. """) - content?: string | null; + content?: string | ChatCompletionRequestAssistantMessageContentPart[] | null; + + /** The refusal message by the assistant. */ + refusal?: string | null; @doc(""" The role of the messages author, in this case `assistant`. @@ -398,7 +446,7 @@ model ChatCompletionRequestToolMessage extends ChatCompletionRequestMessage { role: "tool"; /** The contents of the tool message. */ - content: string; + content: string | ChatCompletionRequestToolMessageContentPart[]; /** Tool call that this message is responding to. */ tool_call_id: string; @@ -481,6 +529,9 @@ model ChatCompletionResponseMessage { /** The contents of the message. */ content: string | null; + /** The refusal message generated by the model. */ + refusal: string | null; + tool_calls?: ChatCompletionMessageToolCalls; /** The role of the author of this message. */ @@ -572,6 +623,9 @@ model ChatCompletionStreamResponseDelta { /** The role of the author of this message. */ role?: "system" | "user" | "assistant" | "tool"; + + /** The refusal message generated by the model. */ + refusal?: string | null; } model ChatCompletionMessageToolCallChunk { @@ -610,6 +664,9 @@ model CreateChatCompletionStreamResponse { logprobs?: { /** A list of message content tokens with log probability information. */ content: ChatCompletionTokenLogprob[] | null; + + /** A list of message refusal tokens with log probability information. */ + refusal: ChatCompletionTokenLogprob[] | null; } | null; @doc(""" @@ -638,6 +695,11 @@ model CreateChatCompletionStreamResponse { /** The model to generate the completion. */ `model`: string; + @doc(""" + The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request. + """) + service_tier?: "scale" | "default" | null; + @doc(""" This fingerprint represents the backend configuration that the model runs with. Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. diff --git a/.typespec/common/custom.tsp b/.typespec/common/custom.tsp index 18fc8c620..57386d659 100644 --- a/.typespec/common/custom.tsp +++ b/.typespec/common/custom.tsp @@ -7,3 +7,8 @@ union ListOrder { asc: "asc", desc: "desc", } + +@discriminator("type") +model OmniTypedResponseFormat { + type: string; +} diff --git a/.typespec/common/models.tsp b/.typespec/common/models.tsp index d76d6302f..4afa9bdca 100644 --- a/.typespec/common/models.tsp +++ b/.typespec/common/models.tsp @@ -35,6 +35,53 @@ model FunctionObject { name: string; parameters?: FunctionParameters; + + @doc(""" + Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](docs/guides/function-calling). + """) + strict?: boolean | null = false; +} + +// Tool customization: establish a common, discriminated union +model ResponseFormatText extends OmniTypedResponseFormat { + @doc(""" + The type of response format being defined: `text` + """) + type: "text"; +} + +// Tool customization: establish a common, discriminated union +model ResponseFormatJsonObject extends OmniTypedResponseFormat { + @doc(""" + The type of response format being defined: `json_object` + """) + type: "json_object"; +} + +/** The schema for the response format, described as a JSON Schema object. */ +model ResponseFormatJsonSchemaSchema is Record; + +// Tool customization: establish a common, discriminated union +model ResponseFormatJsonSchema extends OmniTypedResponseFormat { + @doc(""" + The type of response format being defined: `json_schema` + """) + type: "json_schema"; + + json_schema: { + /** A description of what the response format is for, used by the model to determine how to respond in the format. */ + description?: string; + + /** The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. */ + name: string; + + schema?: ResponseFormatJsonSchemaSchema; + + @doc(""" + Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs). + """) + strict?: boolean | null = false; + }; } /** Whether to enable [parallel function calling](/docs/guides/function-calling/parallel-function-calling) during tool use. */ diff --git a/.typespec/fine-tuning/custom.tsp b/.typespec/fine-tuning/custom.tsp new file mode 100644 index 000000000..11dd998ac --- /dev/null +++ b/.typespec/fine-tuning/custom.tsp @@ -0,0 +1,56 @@ +using TypeSpec.OpenAPI; + +namespace OpenAI; + +model CreateFineTuningJobRequestHyperparameters { + /** + * Number of examples in each batch. A larger batch size means that model parameters + * are updated less frequently, but with lower variance. + */ + @minValue(1) + @maxValue(256) + batch_size?: CreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum | int32 = CreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum.auto; + + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid + * overfitting. + */ + @minValue(0) + learning_rate_multiplier?: CreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum | float32 = CreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum.auto; + + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + @minValue(1) + @maxValue(50) + n_epochs?: CreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum | int32 = CreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum.auto; +} + +union CreateFineTuningJobRequestHyperparametersBatchSizeChoiceEnum { + auto: "auto", +} +union CreateFineTuningJobRequestHyperparametersLearningRateMultiplierChoiceEnum { + auto: "auto", +} +union CreateFineTuningJobRequestHyperparametersNEpochsChoiceEnum { + auto: "auto", +} + +model FineTuningJobHyperparameters { + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + n_epochs: FineTuningJobHyperparametersNEpochsChoiceEnum | int32 = FineTuningJobHyperparametersNEpochsChoiceEnum.auto; +} + +union FineTuningJobHyperparametersBatchSizeChoiceEnum { + auto: "auto", +} +union FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum { + auto: "auto", +} +union FineTuningJobHyperparametersNEpochsChoiceEnum { + auto: "auto", +} diff --git a/.typespec/fine-tuning/models.tsp b/.typespec/fine-tuning/models.tsp index 5de1315cb..e11a1e611 100644 --- a/.typespec/fine-tuning/models.tsp +++ b/.typespec/fine-tuning/models.tsp @@ -5,6 +5,7 @@ import "../chat"; import "../common"; +import "./custom.tsp"; using TypeSpec.OpenAPI; @@ -50,10 +51,15 @@ model FineTuningJobIntegrations is FineTuningIntegration[]; model CreateFineTuningJobRequest { /** * The name of the model to fine-tune. You can select one of the - * [supported models](/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + * [supported models](/docs/guides/fine-tuning/which-models-can-be-fine-tuned). */ @extension("x-oaiTypeLabel", "string") - `model`: string | "babbage-002" | "davinci-002" | "gpt-3.5-turbo"; + `model`: + | string + | "babbage-002" + | "davinci-002" + | "gpt-3.5-turbo" + | "gpt-4o-mini"; @doc(""" The ID of an uploaded file that contains training data. @@ -68,31 +74,14 @@ model CreateFineTuningJobRequest { """) training_file: string; + // Tool customization: reflect observed wire truth (learning_rate_multiplier, n_epochs) for hyperparameters in ft responses /** The hyperparameters used for the fine-tuning job. */ - hyperparameters?: { - /** - * Number of examples in each batch. A larger batch size means that model parameters - * are updated less frequently, but with lower variance. - */ - batch_size?: "auto" | int32 = "auto"; - - /** - * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid - * overfitting. - */ - learning_rate_multiplier?: "auto" | float32 = "auto"; - - /** - * The number of epochs to train the model for. An epoch refers to one full cycle - * through the training dataset. - */ - n_epochs?: "auto" | int32 = "auto"; - }; + hyperparameters?: CreateFineTuningJobRequestHyperparameters; @doc(""" A string of up to 18 characters that will be added to your fine-tuned model name. - For example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + For example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. """) @minLength(1) @maxLength(40) @@ -179,14 +168,9 @@ model FineTuningJob { @encode("unixTimestamp", int32) finished_at: utcDateTime | null; + // Tool customization: reflect observed wire truth (learning_rate_multiplier, n_epochs) for hyperparameters in ft responses /** The hyperparameters used for the fine-tuning job. See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. */ - hyperparameters: { - /** - * The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. - * "auto" decides the optimal number of epochs based on the size of the dataset. If setting the number manually, we support any number between 1 and 50 epochs. - */ - n_epochs: "auto" | int32 = "auto"; - }; + hyperparameters: FineTuningJobHyperparameters; /** The base model that is being fine-tuned. */ `model`: string; diff --git a/.typespec/main.tsp b/.typespec/main.tsp index 1e51c25fe..4e9261637 100644 --- a/.typespec/main.tsp +++ b/.typespec/main.tsp @@ -2,6 +2,7 @@ import "@typespec/http"; import "@typespec/openapi3"; import "@typespec/openapi"; +import "./administration"; import "./audio"; import "./assistants"; import "./batch"; @@ -17,6 +18,7 @@ import "./moderations"; import "./runs"; import "./threads"; import "./vector-stores"; +import "./uploads"; using TypeSpec.Http; diff --git a/.typespec/messages/client.tsp b/.typespec/messages/client.tsp index bb59c0732..fdf340460 100644 --- a/.typespec/messages/client.tsp +++ b/.typespec/messages/client.tsp @@ -18,10 +18,12 @@ using OpenAI; @@access(MessageContentImageUrlObject, Access.public); @@usage(MessageContentImageUrlObject, Usage.input | Usage.output); +@@access(MessageContentRefusalObject, Access.public); +@@usage(MessageContentRefusalObject, Usage.input | Usage.output); + @@access(MessageRequestContentTextObject, Access.public); @@usage(MessageRequestContentTextObject, Usage.input | Usage.output); -// @@access(MessageContentTextObjectAnnotation, Access.public); @@usage(MessageContentTextObjectAnnotation, Usage.input | Usage.output); diff --git a/.typespec/messages/models.tsp b/.typespec/messages/models.tsp index aff04ca10..d3bfe66e2 100644 --- a/.typespec/messages/models.tsp +++ b/.typespec/messages/models.tsp @@ -183,6 +183,17 @@ model MessageContentTextObject extends MessageContent { }; } +// Tool customization: apply a common model base for all assistants message content items +/** The refusal content generated by the assistant. */ +model MessageContentRefusalObject extends MessageContent { + @doc(""" + Always `refusal`. + """) + type: "refusal"; + + refusal: string; +} + // Tool customization: apply custom, common base type to union items /** A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the "file_search" tool to search files. */ model MessageContentTextAnnotationsFileCitationObject @@ -413,3 +424,17 @@ model MessageDeltaContentTextAnnotationsFilePathObject @minValue(0) end_index?: int32; } + +// Tool customization: apply custom, common base type to union items +/** The refusal content that is part of a message. */ +model MessageDeltaContentRefusalObject extends MessageDeltaContent { + /** The index of the refusal part in the message. */ + index: int32; + + @doc(""" + Always `refusal`. + """) + type: "refusal"; + + refusal?: string; +} diff --git a/.typespec/runs/models.tsp b/.typespec/runs/models.tsp index e01ed0f40..8de731324 100644 --- a/.typespec/runs/models.tsp +++ b/.typespec/runs/models.tsp @@ -34,7 +34,10 @@ model CreateRunRequest { `model`?: | string | "gpt-4o" + | "gpt-4o-2024-08-06" | "gpt-4o-2024-05-13" + | "gpt-4o-mini" + | "gpt-4o-mini-2024-07-18" | "gpt-4-turbo" | "gpt-4-turbo-2024-04-09" | "gpt-4-0125-preview" @@ -127,7 +130,10 @@ model CreateThreadAndRunRequest { `model`?: | string | "gpt-4o" + | "gpt-4o-2024-08-06" | "gpt-4o-2024-05-13" + | "gpt-4o-mini" + | "gpt-4o-mini-2024-07-18" | "gpt-4-turbo" | "gpt-4-turbo-2024-04-09" | "gpt-4-0125-preview" @@ -164,13 +170,11 @@ model CreateThreadAndRunRequest { A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. """) @maxItems(20) - file_ids?: string[] = []; - }; - file_search?: { - /** The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. */ - @maxItems(1) - vector_store_ids?: string[]; + file_ids?: string[] = #[]; }; + + // Tool customization: use custom type for sophisticated union + file_search?: ToolResourcesFileSearchIdsOnly; } | null; /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */ @@ -512,7 +516,7 @@ model RunObject { /** The list of tools that the [assistant](/docs/api-reference/assistants) used for this run. */ @maxItems(20) @extension("x-oaiExpandable", true) - tools: AssistantToolDefinition[] = []; + tools: AssistantToolDefinition[] = #[]; /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */ @extension("x-oaiTypeLabel", "map") diff --git a/.typespec/threads/models.tsp b/.typespec/threads/models.tsp index e1837d740..aad860a05 100644 --- a/.typespec/threads/models.tsp +++ b/.typespec/threads/models.tsp @@ -23,11 +23,11 @@ model CreateThreadRequest { A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. """) @maxItems(20) - file_ids?: string[] = []; + file_ids?: string[] = #[]; }; // Tool customization: use custom type for sophisticated union - file_search?: CreateThreadRequestToolResourcesFileSearch; + file_search?: ToolResourcesFileSearch; } | null; /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */ @@ -45,13 +45,11 @@ model ModifyThreadRequest { A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. """) @maxItems(20) - file_ids?: string[] = []; - }; - file_search?: { - /** The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. */ - @maxItems(1) - vector_store_ids?: string[]; + file_ids?: string[] = #[]; }; + + // Tool customization: use custom type for sophisticated union + file_search?: ToolResourcesFileSearchIdsOnly; } | null; /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */ @@ -89,7 +87,7 @@ model ThreadObject { A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. """) @maxItems(20) - file_ids?: string[] = []; + file_ids?: string[] = #[]; }; file_search?: { /** The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. */ diff --git a/.typespec/uploads/main.tsp b/.typespec/uploads/main.tsp new file mode 100644 index 000000000..144c4aeaf --- /dev/null +++ b/.typespec/uploads/main.tsp @@ -0,0 +1 @@ +import "./operations.tsp"; diff --git a/.typespec/uploads/models.tsp b/.typespec/uploads/models.tsp new file mode 100644 index 000000000..13fe13989 --- /dev/null +++ b/.typespec/uploads/models.tsp @@ -0,0 +1,100 @@ +/* + * This file was automatically generated from an OpenAPI .yaml file. + * Edits made directly to this file will be lost. + */ + +import "../files"; + +using TypeSpec.OpenAPI; + +namespace OpenAI; + +model CreateUploadRequest { + /** The name of the file to upload. */ + filename: string; + + /** + * The intended purpose of the uploaded file. + * + * See the [documentation on File purposes](/docs/api-reference/files/create#files-create-purpose). + */ + purpose: "assistants" | "batch" | "fine-tune" | "vision"; + + /** The number of bytes in the file you are uploading. */ + bytes: int32; + + /** + * The MIME type of the file. + * + * This must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision. + */ + mime_type: string; +} + +model AddUploadPartRequest { + /** The chunk of bytes for this Part. */ + data: bytes; +} + +model CompleteUploadRequest { + /** The ordered list of Part IDs. */ + part_ids: string[]; + + /** The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect. */ + md5?: string; +} + +alias CancelUploadRequest = unknown; + +/** The Upload object can accept byte chunks in the form of Parts. */ +model Upload { + /** The Upload unique identifier, which can be referenced in API endpoints. */ + id: string; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + /** The Unix timestamp (in seconds) for when the Upload was created. */ + @encode("unixTimestamp", int32) + created_at: utcDateTime; + + /** The name of the file to be uploaded. */ + filename: string; + + /** The intended number of bytes to be uploaded. */ + bytes: int32; + + /** The intended purpose of the file. [Please refer here](/docs/api-reference/files/object#files/object-purpose) for acceptable values. */ + purpose: string; + + /** The status of the Upload. */ + status: "pending" | "completed" | "cancelled" | "expired"; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + /** The Unix timestamp (in seconds) for when the Upload was created. */ + @encode("unixTimestamp", int32) + expires_at: utcDateTime; + + /** The object type, which is always "upload". */ + object?: "upload"; + + /** The ready File object after the Upload is completed. */ + file?: OpenAIFile | null; +} + +/** The upload Part represents a chunk of bytes we can add to an Upload object. */ +model UploadPart { + /** The upload Part unique identifier, which can be referenced in API endpoints. */ + id: string; + + // Tool customization: 'created' and fields ending in '_at' are Unix encoded utcDateTime + /** The Unix timestamp (in seconds) for when the Part was created. */ + @encode("unixTimestamp", int32) + created_at: utcDateTime; + + /** The ID of the Upload object that this Part was added to. */ + upload_id: string; + + @doc(""" + The object type, which is always `upload.part`. + """) + object: "upload.part"; +} diff --git a/.typespec/uploads/operations.tsp b/.typespec/uploads/operations.tsp new file mode 100644 index 000000000..bf29369eb --- /dev/null +++ b/.typespec/uploads/operations.tsp @@ -0,0 +1,70 @@ +import "@typespec/http"; +import "@typespec/openapi"; + +import "../common"; +import "./models.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenAI; + +@route("uploads") +interface Uploads { + @post + @operationId("createUpload") + @tag("Uploads") + @summary(""" + Creates an intermediate [Upload](/docs/api-reference/uploads/object) object that you can add [Parts](/docs/api-reference/uploads/part-object) to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it. + + Once you complete the Upload, we will create a [File](/docs/api-reference/files/object) object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. + + For certain `purpose`s, the correct `mime_type` must be specified. Please refer to documentation for the supported MIME types for your use case: + - [Assistants](/docs/assistants/tools/file-search/supported-files) + + For guidance on the proper filename extensions for each purpose, please follow the documentation on [creating a File](/docs/api-reference/files/create). + """) + createUpload(@body requestBody: CreateUploadRequest): Upload | ErrorResponse; + + @route("{upload_id}/parts") + @post + @operationId("addUploadPart") + @tag("Uploads") + @summary(""" + Adds a [Part](/docs/api-reference/uploads/part-object) to an [Upload](/docs/api-reference/uploads/object) object. A Part represents a chunk of bytes from the file you are trying to upload. + + Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. + + It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you [complete the Upload](/docs/api-reference/uploads/complete). + """) + addUploadPart( + @path upload_id: string, + @header contentType: "multipart/form-data", + @body requestBody: AddUploadPartRequest, + ): UploadPart | ErrorResponse; + + @route("{upload_id}/complete") + @post + @operationId("completeUpload") + @tag("Uploads") + @summary(""" + Completes the [Upload](/docs/api-reference/uploads/object). + + Within the returned Upload object, there is a nested [File](/docs/api-reference/files/object) object that is ready to use in the rest of the platform. + + You can specify the order of the Parts by passing in an ordered list of the Part IDs. + + The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. + """) + completeUpload( + @path upload_id: string, + @body requestBody: CompleteUploadRequest, + ): Upload | ErrorResponse; + + @route("{upload_id}/cancel") + @post + @operationId("cancelUpload") + @tag("Uploads") + @summary("Cancels the Upload. No Parts may be added after an Upload is cancelled.") + cancelUpload(@path upload_id: string): Upload | ErrorResponse; +} diff --git a/.typespec/vector-stores/models.tsp b/.typespec/vector-stores/models.tsp index 8f780a239..c24a9f21f 100644 --- a/.typespec/vector-stores/models.tsp +++ b/.typespec/vector-stores/models.tsp @@ -167,11 +167,7 @@ model VectorStoreFileObject { @doc(""" One of `server_error` or `rate_limit_exceeded`. """) - code: - | "internal_error" - | "file_not_found" - | "parsing_error" - | "unhandled_mime_type"; + code: "server_error" | "unsupported_file" | "invalid_file"; /** A human-readable description of the error. */ message: string; diff --git a/README.md b/README.md index 1bba18c76..f9d6e9508 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # A conversion of the OpenAI OpenAPI to TypeSpec -Snapshot: https://raw.githubusercontent.com/openai/openai-openapi/dd73070b1d507645d24c249a63ebebd3ec38c0cb/openapi.yaml +Snapshot: https://raw.githubusercontent.com/openai/openai-openapi/3d5576596e5fe1cd3b88ddcd407dd1c5f3594f02/openapi.yaml There are some deltas: diff --git a/openapi3-original.yaml b/openapi3-original.yaml index 73ca4017f..81f8e0ed1 100644 --- a/openapi3-original.yaml +++ b/openapi3-original.yaml @@ -2,7 +2,7 @@ openapi: 3.0.0 info: title: OpenAI API description: The OpenAI REST API. Please see https://platform.openai.com/docs/api-reference for more details. - version: "2.0.0" + version: "2.3.0" termsOfService: https://openai.com/policies/terms-of-use contact: name: OpenAI Support @@ -29,12 +29,16 @@ tags: description: Create large batches of API requests to run asynchronously. - name: Files description: Files are used to upload documents that can be used with features like Assistants and Fine-tuning. + - name: Uploads + description: Use Uploads to upload large files in multiple parts. - name: Images description: Given a prompt and/or an input image, the model will generate a new image. - name: Models description: List and describe the various models available in the API. - name: Moderations description: Given a input text, outputs if the model classifies it as potentially harmful. + - name: Audit Logs + description: List user actions and configuration changes within this organization. paths: # Note: When adding an endpoint, make sure you also add it in the `groups` section, in the end of this file, # under the appropriate group @@ -117,7 +121,7 @@ paths: "id": "chatcmpl-123", "object": "chat.completion", "created": 1677652288, - "model": "gpt-3.5-turbo-0125", + "model": "gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices": [{ "index": 0, @@ -141,7 +145,7 @@ paths: -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ - "model": "gpt-4-turbo", + "model": "gpt-4o", "messages": [ { "role": "user", @@ -167,7 +171,7 @@ paths: client = OpenAI() response = client.chat.completions.create( - model="gpt-4-turbo", + model="gpt-4o", messages=[ { "role": "user", @@ -191,7 +195,7 @@ paths: async function main() { const response = await openai.chat.completions.create({ - model: "gpt-4-turbo", + model: "gpt-4o", messages: [ { role: "user", @@ -214,7 +218,7 @@ paths: "id": "chatcmpl-123", "object": "chat.completion", "created": 1677652288, - "model": "gpt-3.5-turbo-0125", + "model": "gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices": [{ "index": 0, @@ -289,13 +293,13 @@ paths: main(); response: &chat_completion_chunk_example | - {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-3.5-turbo-0125", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]} + {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]} - {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-3.5-turbo-0125", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]} + {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]} .... - {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-3.5-turbo-0125", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - title: Functions request: curl: | @@ -303,7 +307,7 @@ paths: -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ - "model": "gpt-4-turbo", + "model": "gpt-4o", "messages": [ { "role": "user", @@ -397,7 +401,7 @@ paths: ]; const response = await openai.chat.completions.create({ - model: "gpt-4-turbo", + model: "gpt-4o", messages: messages, tools: tools, tool_choice: "auto", @@ -412,7 +416,7 @@ paths: "id": "chatcmpl-abc123", "object": "chat.completion", "created": 1699896916, - "model": "gpt-3.5-turbo-0125", + "model": "gpt-4o-mini", "choices": [ { "index": 0, @@ -494,7 +498,7 @@ paths: "id": "chatcmpl-123", "object": "chat.completion", "created": 1702685778, - "model": "gpt-3.5-turbo-0125", + "model": "gpt-4o-mini", "choices": [ { "index": 0, @@ -1721,7 +1725,219 @@ paths: } main(); + /uploads: + post: + operationId: createUpload + tags: + - Uploads + summary: | + Creates an intermediate [Upload](/docs/api-reference/uploads/object) object that you can add [Parts](/docs/api-reference/uploads/part-object) to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it. + + Once you complete the Upload, we will create a [File](/docs/api-reference/files/object) object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. + + For certain `purpose`s, the correct `mime_type` must be specified. Please refer to documentation for the supported MIME types for your use case: + - [Assistants](/docs/assistants/tools/file-search/supported-files) + + For guidance on the proper filename extensions for each purpose, please follow the documentation on [creating a File](/docs/api-reference/files/create). + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateUploadRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Upload" + x-oaiMeta: + name: Create upload + group: uploads + returns: The [Upload](/docs/api-reference/uploads/object) object with status `pending`. + examples: + request: + curl: | + curl https://api.openai.com/v1/uploads \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "purpose": "fine-tune", + "filename": "training_examples.jsonl", + "bytes": 2147483648, + "mime_type": "text/jsonl" + }' + response: | + { + "id": "upload_abc123", + "object": "upload", + "bytes": 2147483648, + "created_at": 1719184911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + "status": "pending", + "expires_at": 1719127296 + } + + /uploads/{upload_id}/parts: + post: + operationId: addUploadPart + tags: + - Uploads + summary: | + Adds a [Part](/docs/api-reference/uploads/part-object) to an [Upload](/docs/api-reference/uploads/object) object. A Part represents a chunk of bytes from the file you are trying to upload. + + Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. + + It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you [complete the Upload](/docs/api-reference/uploads/complete). + parameters: + - in: path + name: upload_id + required: true + schema: + type: string + example: upload_abc123 + description: | + The ID of the Upload. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/AddUploadPartRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/UploadPart" + x-oaiMeta: + name: Add upload part + group: uploads + returns: The upload [Part](/docs/api-reference/uploads/part-object) object. + examples: + request: + curl: | + curl https://api.openai.com/v1/uploads/upload_abc123/parts + -F data="aHR0cHM6Ly9hcGkub3BlbmFpLmNvbS92MS91cGxvYWRz..." + response: | + { + "id": "part_def456", + "object": "upload.part", + "created_at": 1719185911, + "upload_id": "upload_abc123" + } + + /uploads/{upload_id}/complete: + post: + operationId: completeUpload + tags: + - Uploads + summary: | + Completes the [Upload](/docs/api-reference/uploads/object). + + Within the returned Upload object, there is a nested [File](/docs/api-reference/files/object) object that is ready to use in the rest of the platform. + + You can specify the order of the Parts by passing in an ordered list of the Part IDs. + + The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. + parameters: + - in: path + name: upload_id + required: true + schema: + type: string + example: upload_abc123 + description: | + The ID of the Upload. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CompleteUploadRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Upload" + x-oaiMeta: + name: Complete upload + group: uploads + returns: The [Upload](/docs/api-reference/uploads/object) object with status `completed` with an additional `file` property containing the created usable File object. + examples: + request: + curl: | + curl https://api.openai.com/v1/uploads/upload_abc123/complete + -d '{ + "part_ids": ["part_def456", "part_ghi789"] + }' + response: | + { + "id": "upload_abc123", + "object": "upload", + "bytes": 2147483648, + "created_at": 1719184911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + "status": "completed", + "expires_at": 1719127296, + "file": { + "id": "file-xyz321", + "object": "file", + "bytes": 2147483648, + "created_at": 1719186911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + } + } + /uploads/{upload_id}/cancel: + post: + operationId: cancelUpload + tags: + - Uploads + summary: | + Cancels the Upload. No Parts may be added after an Upload is cancelled. + parameters: + - in: path + name: upload_id + required: true + schema: + type: string + example: upload_abc123 + description: | + The ID of the Upload. + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Upload" + x-oaiMeta: + name: Cancel upload + group: uploads + returns: The [Upload](/docs/api-reference/uploads/object) object with status `cancelled`. + examples: + request: + curl: | + curl https://api.openai.com/v1/uploads/upload_abc123/cancel + response: | + { + "id": "upload_abc123", + "object": "upload", + "bytes": 2147483648, + "created_at": 1719184911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + "status": "cancelled", + "expires_at": 1719127296 + } + /fine_tuning/jobs: post: operationId: createFineTuningJob @@ -1759,7 +1975,7 @@ paths: -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "training_file": "file-BK7bzQj3FfZFXr7DbL6xJwfo", - "model": "gpt-3.5-turbo" + "model": "gpt-4o-mini" }' python: | from openai import OpenAI @@ -1767,7 +1983,7 @@ paths: client.fine_tuning.jobs.create( training_file="file-abc123", - model="gpt-3.5-turbo" + model="gpt-4o-mini" ) node.js: | import OpenAI from "openai"; @@ -1787,8 +2003,8 @@ paths: { "object": "fine_tuning.job", "id": "ftjob-abc123", - "model": "gpt-3.5-turbo-0125", - "created_at": 1614807352, + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], @@ -1804,7 +2020,7 @@ paths: -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "training_file": "file-abc123", - "model": "gpt-3.5-turbo", + "model": "gpt-4o-mini", "hyperparameters": { "n_epochs": 2 } @@ -1815,7 +2031,7 @@ paths: client.fine_tuning.jobs.create( training_file="file-abc123", - model="gpt-3.5-turbo", + model="gpt-4o-mini", hyperparameters={ "n_epochs":2 } @@ -1828,7 +2044,7 @@ paths: async function main() { const fineTune = await openai.fineTuning.jobs.create({ training_file: "file-abc123", - model: "gpt-3.5-turbo", + model: "gpt-4o-mini", hyperparameters: { n_epochs: 2 } }); @@ -1840,8 +2056,8 @@ paths: { "object": "fine_tuning.job", "id": "ftjob-abc123", - "model": "gpt-3.5-turbo-0125", - "created_at": 1614807352, + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], @@ -1859,7 +2075,7 @@ paths: -d '{ "training_file": "file-abc123", "validation_file": "file-abc123", - "model": "gpt-3.5-turbo" + "model": "gpt-4o-mini" }' python: | from openai import OpenAI @@ -1868,7 +2084,7 @@ paths: client.fine_tuning.jobs.create( training_file="file-abc123", validation_file="file-def456", - model="gpt-3.5-turbo" + model="gpt-4o-mini" ) node.js: | import OpenAI from "openai"; @@ -1889,8 +2105,8 @@ paths: { "object": "fine_tuning.job", "id": "ftjob-abc123", - "model": "gpt-3.5-turbo-0125", - "created_at": 1614807352, + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], @@ -1907,7 +2123,7 @@ paths: -d '{ "training_file": "file-abc123", "validation_file": "file-abc123", - "model": "gpt-3.5-turbo", + "model": "gpt-4o-mini", "integrations": [ { "type": "wandb", @@ -1925,8 +2141,8 @@ paths: { "object": "fine_tuning.job", "id": "ftjob-abc123", - "model": "gpt-3.5-turbo-0125", - "created_at": 1614807352, + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], @@ -2166,7 +2382,7 @@ paths: { "object": "fine_tuning.job.event", "id": "ft-event-ddTJfwuMVpfLXseO0Am0Gqjm", - "created_at": 1692407401, + "created_at": 1721764800, "level": "info", "message": "Fine tuning job successfully completed", "data": null, @@ -2175,9 +2391,9 @@ paths: { "object": "fine_tuning.job.event", "id": "ft-event-tyiGuB72evQncpH87xe505Sv", - "created_at": 1692407400, + "created_at": 1721764800, "level": "info", - "message": "New fine-tuned model created: ft:gpt-3.5-turbo:openai::7p4lURel", + "message": "New fine-tuned model created: ft:gpt-4o-mini:openai::7p4lURel", "data": null, "type": "message" } @@ -2236,8 +2452,8 @@ paths: { "object": "fine_tuning.job", "id": "ftjob-abc123", - "model": "gpt-3.5-turbo-0125", - "created_at": 1689376978, + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, "fine_tuned_model": null, "organization_id": "org-123", "result_files": [], @@ -2300,8 +2516,8 @@ paths: { "object": "fine_tuning.job.checkpoint", "id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB", - "created_at": 1519129973, - "fine_tuned_model_checkpoint": "ft:gpt-3.5-turbo-0125:my-org:custom-suffix:96olL566:ckpt-step-2000", + "created_at": 1721764867, + "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:96olL566:ckpt-step-2000", "metrics": { "full_valid_loss": 0.134, "full_valid_mean_token_accuracy": 0.874 @@ -2312,8 +2528,8 @@ paths: { "object": "fine_tuning.job.checkpoint", "id": "ftckpt_enQCFmOTGj3syEpYVhBRLTSy", - "created_at": 1519129833, - "fine_tuned_model_checkpoint": "ft:gpt-3.5-turbo-0125:my-org:custom-suffix:7q8mpxmy:ckpt-step-1000", + "created_at": 1721764800, + "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:7q8mpxmy:ckpt-step-1000", "metrics": { "full_valid_loss": 0.167, "full_valid_mean_token_accuracy": 0.781 @@ -2405,7 +2621,7 @@ paths: schema: type: string # ideally this will be an actual ID, so this will always work from browser - example: gpt-3.5-turbo + example: gpt-4o-mini description: The ID of the model to use for this request responses: "200": @@ -2458,7 +2674,7 @@ paths: required: true schema: type: string - example: ft:gpt-3.5-turbo:acemeco:suffix:abc123 + example: ft:gpt-4o-mini:acemeco:suffix:abc123 description: The model to delete responses: "200": @@ -2474,28 +2690,28 @@ paths: examples: request: curl: | - curl https://api.openai.com/v1/models/ft:gpt-3.5-turbo:acemeco:suffix:abc123 \ + curl https://api.openai.com/v1/models/ft:gpt-4o-mini:acemeco:suffix:abc123 \ -X DELETE \ -H "Authorization: Bearer $OPENAI_API_KEY" python: | from openai import OpenAI client = OpenAI() - client.models.delete("ft:gpt-3.5-turbo:acemeco:suffix:abc123") + client.models.delete("ft:gpt-4o-mini:acemeco:suffix:abc123") node.js: |- import OpenAI from "openai"; const openai = new OpenAI(); async function main() { - const model = await openai.models.del("ft:gpt-3.5-turbo:acemeco:suffix:abc123"); + const model = await openai.models.del("ft:gpt-4o-mini:acemeco:suffix:abc123"); console.log(model); } main(); response: | { - "id": "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + "id": "ft:gpt-4o-mini:acemeco:suffix:abc123", "object": "model", "deleted": true } @@ -2674,7 +2890,7 @@ paths: "created_at": 1698982736, "name": "Coding Tutor", "description": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": "You are a helpful assistant designed to make me better at coding!", "tools": [], "tool_resources": {}, @@ -2689,7 +2905,7 @@ paths: "created_at": 1698982718, "name": "My Assistant", "description": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": "You are a helpful assistant designed to make me better at coding!", "tools": [], "tool_resources": {}, @@ -2704,7 +2920,7 @@ paths: "created_at": 1698982643, "name": null, "description": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": null, "tools": [], "tool_resources": {}, @@ -2753,7 +2969,7 @@ paths: "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", "name": "Math Tutor", "tools": [{"type": "code_interpreter"}], - "model": "gpt-4-turbo" + "model": "gpt-4o" }' python: | @@ -2764,7 +2980,7 @@ paths: instructions="You are a personal math tutor. When asked a question, write and run Python code to answer the question.", name="Math Tutor", tools=[{"type": "code_interpreter"}], - model="gpt-4-turbo", + model="gpt-4o", ) print(my_assistant) node.js: |- @@ -2778,7 +2994,7 @@ paths: "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", name: "Math Tutor", tools: [{ type: "code_interpreter" }], - model: "gpt-4-turbo", + model: "gpt-4o", }); console.log(myAssistant); @@ -2792,7 +3008,7 @@ paths: "created_at": 1698984975, "name": "Math Tutor", "description": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", "tools": [ { @@ -2815,7 +3031,7 @@ paths: "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", "tools": [{"type": "file_search"}], "tool_resources": {"file_search": {"vector_store_ids": ["vs_123"]}}, - "model": "gpt-4-turbo" + "model": "gpt-4o" }' python: | from openai import OpenAI @@ -2826,7 +3042,7 @@ paths: name="HR Helper", tools=[{"type": "file_search"}], tool_resources={"file_search": {"vector_store_ids": ["vs_123"]}}, - model="gpt-4-turbo" + model="gpt-4o" ) print(my_assistant) node.js: |- @@ -2845,7 +3061,7 @@ paths: vector_store_ids: ["vs_123"] } }, - model: "gpt-4-turbo" + model: "gpt-4o" }); console.log(myAssistant); @@ -2859,7 +3075,7 @@ paths: "created_at": 1699009403, "name": "HR Helper", "description": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", "tools": [ { @@ -2936,7 +3152,7 @@ paths: "created_at": 1699009709, "name": "HR Helper", "description": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", "tools": [ { @@ -2988,7 +3204,7 @@ paths: -d '{ "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", "tools": [{"type": "file_search"}], - "model": "gpt-4-turbo" + "model": "gpt-4o" }' python: | from openai import OpenAI @@ -2999,7 +3215,7 @@ paths: instructions="You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", name="HR Helper", tools=[{"type": "file_search"}], - model="gpt-4-turbo" + model="gpt-4o" ) print(my_updated_assistant) @@ -3016,7 +3232,7 @@ paths: "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", name: "HR Helper", tools: [{ type: "file_search" }], - model: "gpt-4-turbo" + model: "gpt-4o" } ); @@ -3031,7 +3247,7 @@ paths: "created_at": 1699009709, "name": "HR Helper", "description": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", "tools": [ { @@ -3680,7 +3896,7 @@ paths: name: Retrieve message group: threads beta: true - returns: The [message](/docs/api-reference/threads/messages/object) object matching the specified ID. + returns: The [message](/docs/api-reference/messages/object) object matching the specified ID. examples: request: curl: | @@ -3768,7 +3984,7 @@ paths: name: Modify message group: threads beta: true - returns: The modified [message](/docs/api-reference/threads/messages/object) object. + returns: The modified [message](/docs/api-reference/messages/object) object. examples: request: curl: | @@ -3989,7 +4205,7 @@ paths: "completed_at": null, "required_action": null, "last_error": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": "You are a helpful assistant.", "tools": [], "tool_resources": {}, @@ -4068,13 +4284,13 @@ paths: data: {"id":"thread_123","object":"thread","created_at":1710348075,"metadata":{}} event: thread.run.created - data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} event: thread.run.queued - data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} event: thread.run.in_progress - data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} event: thread.run.step.created data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} @@ -4106,7 +4322,7 @@ paths: data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710348077,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} event: thread.run.completed - {"id":"run_123","object":"thread.run","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1713226836,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1713226837,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} + {"id":"run_123","object":"thread.run","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1713226836,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1713226837,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} event: done data: [DONE] @@ -4237,13 +4453,13 @@ paths: data: {"id":"thread_123","object":"thread","created_at":1710351818,"metadata":{}} event: thread.run.created - data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.queued - data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.in_progress - data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.step.created data: {"id":"step_001","object":"thread.run.step","created_at":1710351819,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710352418,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[]},"usage":null} @@ -4269,7 +4485,7 @@ paths: data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"\"}"}}]}}} event: thread.run.requires_action - data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"requires_action","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":{"type":"submit_tool_outputs","submit_tool_outputs":{"tool_calls":[{"id":"call_XXNp8YGaFrjrSjgqxtC8JJ1B","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"San Francisco, CA\",\"unit\":\"fahrenheit\"}"}}]}},"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"requires_action","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":{"type":"submit_tool_outputs","submit_tool_outputs":{"tool_calls":[{"id":"call_XXNp8YGaFrjrSjgqxtC8JJ1B","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"San Francisco, CA\",\"unit\":\"fahrenheit\"}"}}]}},"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: done data: [DONE] @@ -4370,7 +4586,7 @@ paths: "failed_at": null, "completed_at": 1699075073, "last_error": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": null, "incomplete_details": null, "tools": [ @@ -4417,7 +4633,7 @@ paths: "failed_at": null, "completed_at": 1699063291, "last_error": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": null, "incomplete_details": null, "tools": [ @@ -4536,7 +4752,7 @@ paths: "failed_at": null, "completed_at": 1699063291, "last_error": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": null, "incomplete_details": null, "tools": [ @@ -4600,13 +4816,13 @@ paths: main(); response: | event: thread.run.created - data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.queued - data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.in_progress - data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710330641,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710330641,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.step.created data: {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} @@ -4638,7 +4854,7 @@ paths: data: {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710330642,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} event: thread.run.completed - data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710330641,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710330642,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710330641,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710330642,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: done data: [DONE] @@ -4755,13 +4971,13 @@ paths: main(); response: | event: thread.run.created - data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.queued - data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.in_progress - data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710348075,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710348075,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.step.created data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} @@ -4793,7 +5009,7 @@ paths: data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710348077,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} event: thread.run.completed - data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710348075,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710348077,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710348075,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710348077,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: done data: [DONE] @@ -4874,7 +5090,7 @@ paths: "failed_at": null, "completed_at": 1699075073, "last_error": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": null, "incomplete_details": null, "tools": [ @@ -4993,7 +5209,7 @@ paths: "failed_at": null, "completed_at": 1699075073, "last_error": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": null, "incomplete_details": null, "tools": [ @@ -5137,7 +5353,7 @@ paths: "failed_at": null, "completed_at": null, "last_error": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": null, "tools": [ { @@ -5241,10 +5457,10 @@ paths: data: {"id":"step_001","object":"thread.run.step","created_at":1710352449,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"completed","cancelled_at":null,"completed_at":1710352475,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[{"id":"call_iWr0kQ2EaYMaxNdl0v3KYkx7","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"San Francisco, CA\",\"unit\":\"fahrenheit\"}","output":"70 degrees and sunny."}}]},"usage":{"prompt_tokens":291,"completion_tokens":24,"total_tokens":315}} event: thread.run.queued - data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":1710352448,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":1710352448,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.in_progress - data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710352475,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710352475,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: thread.run.step.created data: {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":null} @@ -5282,7 +5498,7 @@ paths: data: {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710352477,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":{"prompt_tokens":329,"completion_tokens":18,"total_tokens":347}} event: thread.run.completed - data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710352475,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710352477,"required_action":null,"last_error":null,"model":"gpt-4-turbo","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710352475,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710352477,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} event: done data: [DONE] @@ -5364,7 +5580,7 @@ paths: "failed_at": null, "completed_at": null, "last_error": null, - "model": "gpt-4-turbo", + "model": "gpt-4o", "instructions": "You summarize books.", "tools": [ { @@ -7013,877 +7229,1596 @@ paths: } } -components: - securitySchemes: - ApiKeyAuth: - type: http - scheme: "bearer" + # Organization + # Audit Logs List + /organization/audit_logs: + get: + summary: List user actions and configuration changes within this organization. + operationId: list-audit-logs + tags: + - Audit Logs + parameters: + - name: effective_at + in: query + description: Return only events whose `effective_at` (Unix seconds) is in this range. + required: false + schema: + type: object + properties: + gt: + type: integer + description: Return only events whose `effective_at` (Unix seconds) is greater than this value. + gte: + type: integer + description: Return only events whose `effective_at` (Unix seconds) is greater than or equal to this value. + lt: + type: integer + description: Return only events whose `effective_at` (Unix seconds) is less than this value. + lte: + type: integer + description: Return only events whose `effective_at` (Unix seconds) is less than or equal to this value. + - name: project_ids[] + in: query + description: Return only events for these projects. + required: false + schema: + type: array + items: + type: string + - name: event_types[] + in: query + description: Return only events with a `type` in one of these values. For example, `project.created`. For all options, see the documentation for the [audit log object](/docs/api-reference/audit-logs/object). + required: false + schema: + type: array + items: + $ref: "#/components/schemas/AuditLogEventType" + - name: actor_ids[] + in: query + description: Return only events performed by these actors. Can be a user ID, a service account ID, or an api key tracking ID. + required: false + schema: + type: array + items: + type: string + - name: actor_emails[] + in: query + description: Return only events performed by users with these emails. + required: false + schema: + type: array + items: + type: string + - name: resource_ids[] + in: query + description: Return only events performed on these targets. For example, a project ID updated. + required: false + schema: + type: array + items: + type: string + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: *pagination_after_param_description + schema: + type: string + - name: before + in: query + description: *pagination_before_param_description + schema: + type: string + responses: + "200": + description: Audit logs listed successfully. + content: + application/json: + schema: + $ref: "#/components/schemas/ListAuditLogsResponse" + x-oaiMeta: + name: List audit logs + group: audit-logs + returns: A list of paginated [Audit Log](/docs/api-reference/audit-logs/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/audit_logs \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + response: | + { + "object": "list", + "data": [ + { + "id": "audit_log-xxx_yyyymmdd", + "type": "project.archived", + "effective_at": 1722461446, + "actor": { + "type": "api_key", + "api_key": { + "type": "user", + "user": { + "id": "user-xxx", + "email": "user@example.com" + } + } + }, + "project.archived": { + "id": "proj_abc" + }, + }, + { + "id": "audit_log-yyy__20240101", + "type": "api_key.updated", + "effective_at": 1720804190, + "actor": { + "type": "session", + "session": { + "user": { + "id": "user-xxx", + "email": "user@example.com" + }, + "ip_address": "127.0.0.1", + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" + } + }, + "api_key.updated": { + "id": "key_xxxx", + "data": { + "scopes": ["resource_2.operation_2"] + } + }, + } + ], + "first_id": "audit_log-xxx__20240101", + "last_id": "audit_log_yyy__20240101", + "has_more": true + } + /organization/invites: + get: + summary: Returns a list of invites in the organization. + operationId: list-invites + tags: + - Invites + parameters: + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: *pagination_after_param_description + required: false + schema: + type: string + responses: + "200": + description: Invites listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/InviteListResponse' + x-oaiMeta: + name: List invites + group: administration + returns: A list of [Invite](/docs/api-reference/invite/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/invites?after=invite-abc&limit=20 \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "list", + "data": [ + { + "object": "organization.invite", + "id": "invite-abc", + "email": "user@example.com", + "role": "owner", + "status": "accepted", + "invited_at": 1711471533, + "expires_at": 1711471533, + "accepted_at": 1711471533 + } + ], + "first_id": "invite-abc", + "last_id": "invite-abc", + "has_more": false + } - schemas: - Error: - type: object - properties: - code: - type: string - nullable: true - message: - type: string - nullable: false - param: - type: string - nullable: true - type: + post: + summary: Create an invite for a user to the organization. The invite must be accepted by the user before they have access to the organization. + operationId: inviteUser + tags: + - Invites + requestBody: + description: The invite request payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InviteRequest' + responses: + "200": + description: User invited successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Invite' + x-oaiMeta: + name: Create invite + group: administration + returns: The created [Invite](/docs/api-reference/invite/object) object. + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/invites \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "email": "user@example.com", + "role": "owner" + }' + response: + content: | + { + "object": "organization.invite", + "id": "invite-abc", + "email": "user@example.com", + "role": "owner", + "invited_at": 1711471533, + "expires_at": 1711471533, + "accepted_at": null + } + + /organization/invites/{invite_id}: + get: + summary: Retrieves an invite. + operationId: retrieve-invite + tags: + - Invites + parameters: + - in: path + name: invite_id + required: true + schema: type: string - nullable: false - required: - - type - - message - - param - - code - ErrorResponse: - type: object - properties: - error: - $ref: "#/components/schemas/Error" - required: - - error - - ListModelsResponse: - type: object - properties: - object: - type: string - enum: [list] - data: - type: array - items: - $ref: "#/components/schemas/Model" - required: - - object - - data - DeleteModelResponse: - type: object - properties: - id: - type: string - deleted: - type: boolean - object: + description: The ID of the invite to retrieve. + responses: + "200": + description: Invite retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Invite' + x-oaiMeta: + name: Retrieve invite + group: administration + returns: The [Invite](/docs/api-reference/invite/object) object matching the specified ID. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/invites/invite-abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.invite", + "id": "invite-abc", + "email": "user@example.com", + "role": "owner", + "status": "accepted", + "invited_at": 1711471533, + "expires_at": 1711471533, + "accepted_at": 1711471533 + } + delete: + summary: Delete an invite. If the invite has already been accepted, it cannot be deleted. + operationId: delete-invite + tags: + - Invites + parameters: + - in: path + name: invite_id + required: true + schema: type: string - required: - - id - - object - - deleted + description: The ID of the invite to delete. + responses: + "200": + description: Invite deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/InviteDeleteResponse' + x-oaiMeta: + name: Delete invite + group: administration + returns: Confirmation that the invite has been deleted + examples: + request: + curl: | + curl -X DELETE https://api.openai.com/v1/organization/invites/invite-abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.invite.deleted", + "id": "invite-abc", + "deleted": true + } - CreateCompletionRequest: - type: object - properties: - model: - description: &model_description | - ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them. - anyOf: - - type: string - - type: string - enum: ["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"] - x-oaiTypeLabel: string - prompt: - description: &completions_prompt_description | - The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. + /organization/users: + get: + summary: Lists all of the users in the organization. + operationId: list-users + tags: + - Users + parameters: + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: *pagination_after_param_description + required: false + schema: + type: string + responses: + "200": + description: Users listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UserListResponse' + x-oaiMeta: + name: List users + group: administration + returns: A list of [User](/docs/api-reference/users/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/users?after=user_abc&limit=20 \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "list", + "data": [ + { + "object": "organization.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + ], + "first_id": "user-abc", + "last_id": "user-xyz", + "has_more": false + } - Note that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document. - default: "<|endoftext|>" - nullable: true - oneOf: - - type: string - default: "" - example: "This is a test." - - type: array - items: - type: string - default: "" - example: "This is a test." - - type: array - minItems: 1 - items: - type: integer - example: "[1212, 318, 257, 1332, 13]" - - type: array - minItems: 1 - items: - type: array - minItems: 1 - items: - type: integer - example: "[[1212, 318, 257, 1332, 13]]" - best_of: - type: integer - default: 1 - minimum: 0 - maximum: 20 - nullable: true - description: &completions_best_of_description | - Generates `best_of` completions server-side and returns the "best" (the one with the highest log probability per token). Results cannot be streamed. + /organization/users/{user_id}: + get: + summary: Retrieves a user by their identifier. + operationId: retrieve-user + tags: + - Users + parameters: + - name: user_id + in: path + description: The ID of the user. + required: true + schema: + type: string + responses: + "200": + description: User retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/User' + x-oaiMeta: + name: Retrieve user + group: administration + returns: The [User](/docs/api-reference/users/object) object matching the specified ID. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/users/user_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } - When used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`. + post: + summary: Modifies a user's role in the organization. + operationId: modify-user + tags: + - Users + requestBody: + description: The new user role to modify. This must be one of `owner` or `member`. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/UserRoleUpdateRequest' + responses: + "200": + description: User role updated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/User' + x-oaiMeta: + name: Modify user + group: administration + returns: The updated [User](/docs/api-reference/users/object) object. + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/users/user_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "role": "owner" + }' + response: + content: | + { + "object": "organization.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } - **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. - echo: + delete: + summary: Deletes a user from the organization. + operationId: delete-user + tags: + - Users + parameters: + - name: user_id + in: path + description: The ID of the user. + required: true + schema: + type: string + responses: + "200": + description: User deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UserDeleteResponse' + x-oaiMeta: + name: Delete user + group: administration + returns: Confirmation of the deleted user + examples: + request: + curl: | + curl -X DELETE https://api.openai.com/v1/organization/users/user_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.user.deleted", + "id": "user_abc", + "deleted": true + } + /organization/projects: + get: + summary: Returns a list of projects. + operationId: list-projects + tags: + - Projects + parameters: + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: *pagination_after_param_description + required: false + schema: + type: string + - name: include_archived + in: query + schema: type: boolean default: false - nullable: true - description: &completions_echo_description > - Echo back the prompt in addition to the completion - frequency_penalty: - type: number - default: 0 - minimum: -2 - maximum: 2 - nullable: true - description: &completions_frequency_penalty_description | - Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. + description: If `true` returns all projects including those that have been `archived`. Archived projects are not included by default. + responses: + "200": + description: Projects listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectListResponse' + x-oaiMeta: + name: List projects + group: administration + returns: A list of [Project](/docs/api-reference/projects/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/projects?after=proj_abc&limit=20&include_archived=false \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "list", + "data": [ + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project example", + "created_at": 1711471533, + "archived_at": null, + "status": "active" + } + ], + "first_id": "proj-abc", + "last_id": "proj-xyz", + "has_more": false + } - [See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details) - logit_bias: &completions_logit_bias - type: object - x-oaiTypeLabel: map - default: null - nullable: true - additionalProperties: - type: integer - description: &completions_logit_bias_description | - Modify the likelihood of specified tokens appearing in the completion. - - Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. - - As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. - logprobs: &completions_logprobs_configuration - type: integer - minimum: 0 - maximum: 5 - default: null - nullable: true - description: &completions_logprobs_description | - Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response. - - The maximum value for `logprobs` is 5. - max_tokens: - type: integer - minimum: 0 - default: 16 - example: 16 - nullable: true - description: &completions_max_tokens_description | - The maximum number of [tokens](/tokenizer) that can be generated in the completion. - - The token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. - n: - type: integer - minimum: 1 - maximum: 128 - default: 1 - example: 1 - nullable: true - description: &completions_completions_description | - How many completions to generate for each prompt. - - **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. - presence_penalty: - type: number - default: 0 - minimum: -2 - maximum: 2 - nullable: true - description: &completions_presence_penalty_description | - Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. + post: + summary: Create a new project in the organization. Projects can be created and archived, but cannot be deleted. + operationId: create-project + tags: + - Projects + requestBody: + description: The project create request payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectCreateRequest' + responses: + "200": + description: Project created successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Project' + x-oaiMeta: + name: Create project + group: administration + returns: The created [Project](/docs/api-reference/projects/object) object. + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/projects \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Project ABC" + }' + response: + content: | + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project ABC", + "created_at": 1711471533, + "archived_at": null, + "status": "active" + } - [See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details) - seed: &completions_seed_param - type: integer - minimum: -9223372036854775808 - maximum: 9223372036854775807 - nullable: true - description: | - If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + /organization/projects/{project_id}: + get: + summary: Retrieves a project. + operationId: retrieve-project + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + responses: + "200": + description: Project retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Project' + x-oaiMeta: + name: Retrieve project + group: administration + description: Retrieve a project. + returns: The [Project](/docs/api-reference/projects/object) object matching the specified ID. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/projects/proj_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project example", + "created_at": 1711471533, + "archived_at": null, + "status": "active" + } - Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. - stop: - description: &completions_stop_description > - Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. - default: null - nullable: true - oneOf: - - type: string - default: <|endoftext|> - example: "\n" - nullable: true - - type: array - minItems: 1 - maxItems: 4 - items: - type: string - example: '["\n"]' - stream: - description: > - Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). - type: boolean - nullable: true - default: false - stream_options: - $ref: "#/components/schemas/ChatCompletionStreamOptions" - suffix: - description: | - The suffix that comes after a completion of inserted text. + post: + summary: Modifies a project in the organization. + operationId: modify-project + tags: + - Projects + requestBody: + description: The project update request payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUpdateRequest' + responses: + "200": + description: Project updated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Project' + "400": + description: Error response when updating the default project. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: Modify project + group: administration + returns: The updated [Project](/docs/api-reference/projects/object) object. + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/projects/proj_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Project DEF" + }' - This parameter is only supported for `gpt-3.5-turbo-instruct`. - default: null - nullable: true + /organization/projects/{project_id}/archive: + post: + summary: Archives a project in the organization. Archived projects cannot be used or updated. + operationId: archive-project + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: type: string - example: "test." - temperature: - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - nullable: true - description: &completions_temperature_description | - What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. - - We generally recommend altering this or `top_p` but not both. - top_p: - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - nullable: true - description: &completions_top_p_description | - An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + responses: + "200": + description: Project archived successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Project' + x-oaiMeta: + name: Archive project + group: administration + returns: The archived [Project](/docs/api-reference/projects/object) object. + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/archive \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project DEF", + "created_at": 1711471533, + "archived_at": 1711471533, + "status": "archived" + } + - We generally recommend altering this or `temperature` but not both. - user: &end_user_param_configuration + /organization/projects/{project_id}/users: + get: + summary: Returns a list of users in the project. + operationId: list-project-users + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: type: string - example: user-1234 - description: | - A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). - required: - - model - - prompt + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: *pagination_after_param_description + required: false + schema: + type: string + responses: + "200": + description: Project users listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUserListResponse' + "400": + description: Error response when project is archived. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: List project users + group: administration + returns: A list of [ProjectUser](/docs/api-reference/project-users/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/projects/proj_abc/users?after=user_abc&limit=20 \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "list", + "data": [ + { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + ], + "first_id": "user-abc", + "last_id": "user-xyz", + "has_more": false + } + error_response: + content: | + { + "code": 400, + "message": "Project {name} is archived" + } - CreateCompletionResponse: - type: object - description: | - Represents a completion response from the API. Note: both the streamed and non-streamed response objects share the same shape (unlike the chat endpoint). - properties: - id: + post: + summary: Adds a user to the project. Users must already be members of the organization to be added to a project. + operationId: create-project-user + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: type: string - description: A unique identifier for the completion. - choices: - type: array - description: The list of completion choices the model generated for the input prompt. - items: - type: object - required: - - finish_reason - - index - - logprobs - - text - properties: - finish_reason: - type: string - description: &completion_finish_reason_description | - The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, - `length` if the maximum number of tokens specified in the request was reached, - or `content_filter` if content was omitted due to a flag from our content filters. - enum: ["stop", "length", "content_filter"] - index: - type: integer - logprobs: - type: object - nullable: true - properties: - text_offset: - type: array - items: - type: integer - token_logprobs: - type: array - items: - type: number - tokens: - type: array - items: - type: string - top_logprobs: - type: array - items: - type: object - additionalProperties: - type: number - text: - type: string - created: - type: integer - description: The Unix timestamp (in seconds) of when the completion was created. - model: - type: string - description: The model used for completion. - system_fingerprint: - type: string - description: | - This fingerprint represents the backend configuration that the model runs with. - - Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. - object: - type: string - description: The object type, which is always "text_completion" - enum: [text_completion] - usage: - $ref: "#/components/schemas/CompletionUsage" - required: - - id - - object - - created - - model - - choices + tags: + - Projects + requestBody: + description: The project user create request payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUserCreateRequest' + responses: + "200": + description: User added to project successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUser' + "400": + description: Error response for various conditions. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' x-oaiMeta: - name: The completion object - legacy: true - example: | - { - "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", - "object": "text_completion", - "created": 1589478378, - "model": "gpt-4-turbo", - "choices": [ - { - "text": "\n\nThis is indeed a test", - "index": 0, - "logprobs": null, - "finish_reason": "length" - } - ], - "usage": { - "prompt_tokens": 5, - "completion_tokens": 7, - "total_tokens": 12 - } - } - - ChatCompletionRequestMessageContentPart: - oneOf: - - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartText" - - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartImage" - x-oaiExpandable: true - - ChatCompletionRequestMessageContentPartImage: - type: object - title: Image content part - properties: - type: - type: string - enum: ["image_url"] - description: The type of the content part. - image_url: - type: object - properties: - url: - type: string - description: Either a URL of the image or the base64 encoded image data. - format: uri - detail: - type: string - description: Specifies the detail level of the image. Learn more in the [Vision guide](/docs/guides/vision/low-or-high-fidelity-image-understanding). - enum: ["auto", "low", "high"] - default: "auto" - required: - - url - required: - - type - - image_url - - ChatCompletionRequestMessageContentPartText: - type: object - title: Text content part - properties: - type: - type: string - enum: ["text"] - description: The type of the content part. - text: - type: string - description: The text content. - required: - - type - - text - - ChatCompletionRequestMessage: - oneOf: - - $ref: "#/components/schemas/ChatCompletionRequestSystemMessage" - - $ref: "#/components/schemas/ChatCompletionRequestUserMessage" - - $ref: "#/components/schemas/ChatCompletionRequestAssistantMessage" - - $ref: "#/components/schemas/ChatCompletionRequestToolMessage" - - $ref: "#/components/schemas/ChatCompletionRequestFunctionMessage" - x-oaiExpandable: true + name: Create project user + group: administration + returns: The created [ProjectUser](/docs/api-reference/project-users/object) object. + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/users \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "user_id": "user_abc", + "role": "member" + }' + response: + content: | + { + "object": "organization.project.user", + "id": "user_abc", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + error_response: + content: | + { + "code": 400, + "message": "Project {name} is archived" + } - ChatCompletionRequestSystemMessage: - type: object - title: System message - properties: - content: - description: The contents of the system message. - type: string - role: + /organization/projects/{project_id}/users/{user_id}: + get: + summary: Retrieves a user in the project. + operationId: retrieve-project-user + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: type: string - enum: ["system"] - description: The role of the messages author, in this case `system`. - name: + - name: user_id + in: path + description: The ID of the user. + required: true + schema: type: string - description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. - required: - - content - - role + responses: + "200": + description: Project user retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUser' + x-oaiMeta: + name: Retrieve project user + group: administration + returns: The [ProjectUser](/docs/api-reference/project-users/object) object matching the specified ID. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } - ChatCompletionRequestUserMessage: - type: object - title: User message - properties: + post: + summary: Modifies a user's role in the project. + operationId: modify-project-user + tags: + - Projects + requestBody: + description: The project user update request payload. + required: true content: - description: | - The contents of the user message. - oneOf: - - type: string - description: The text contents of the message. - title: Text content - - type: array - description: An array of content parts with a defined type, each can be of type `text` or `image_url` when passing in images. You can pass multiple images by adding multiple `image_url` content parts. Image input is only supported when using the `gpt-4-visual-preview` model. - title: Array of content parts - items: - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPart" - minItems: 1 - x-oaiExpandable: true - role: - type: string - enum: ["user"] - description: The role of the messages author, in this case `user`. - name: - type: string - description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. - required: - - content - - role + application/json: + schema: + $ref: '#/components/schemas/ProjectUserUpdateRequest' + responses: + "200": + description: Project user's role updated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUser' + "400": + description: Error response for various conditions. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: Modify project user + group: administration + returns: The updated [ProjectUser](/docs/api-reference/project-users/object) object. + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "role": "owner" + }' + response: + content: | + { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } - ChatCompletionRequestAssistantMessage: - type: object - title: Assistant message - properties: - content: - nullable: true - type: string - description: | - The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified. - role: - type: string - enum: ["assistant"] - description: The role of the messages author, in this case `assistant`. - name: - type: string - description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. - tool_calls: - $ref: "#/components/schemas/ChatCompletionMessageToolCalls" - function_call: - type: object - deprecated: true - description: "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." - nullable: true - properties: - arguments: - type: string - description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. - name: - type: string - description: The name of the function to call. - required: - - arguments - - name - required: - - role - - FineTuneChatCompletionRequestAssistantMessage: - allOf: - - type: object - title: Assistant message - deprecated: false - properties: - weight: - type: integer - enum: [0, 1] - description: "Controls whether the assistant message is trained against (0 or 1)" - - $ref: "#/components/schemas/ChatCompletionRequestAssistantMessage" - required: - - role + delete: + summary: Deletes a user from the project. + operationId: delete-project-user + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: user_id + in: path + description: The ID of the user. + required: true + schema: + type: string + responses: + "200": + description: Project user deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUserDeleteResponse' + "400": + description: Error response for various conditions. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: Delete project user + group: administration + returns: Confirmation that project has been deleted or an error in case of an archived project, which has no users + examples: + request: + curl: | + curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.project.user.deleted", + "id": "user_abc", + "deleted": true + } - ChatCompletionRequestToolMessage: - type: object - title: Tool message - properties: - role: - type: string - enum: ["tool"] - description: The role of the messages author, in this case `tool`. - content: - type: string - description: The contents of the tool message. - tool_call_id: - type: string - description: Tool call that this message is responding to. - required: - - role - - content - - tool_call_id + /organization/projects/{project_id}/service_accounts: + get: + summary: Returns a list of service accounts in the project. + operationId: list-project-service-accounts + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: *pagination_after_param_description + required: false + schema: + type: string + responses: + "200": + description: Project service accounts listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectServiceAccountListResponse' + "400": + description: Error response when project is archived. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: List project service accounts + group: administration + returns: A list of [ProjectServiceAccount](/docs/api-reference/project-service-accounts/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/projects/proj_abc/service_accounts?after=custom_id&limit=20 \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "list", + "data": [ + { + "object": "organization.project.service_account", + "id": "svc_acct_abc", + "name": "Service Account", + "role": "owner", + "created_at": 1711471533 + } + ], + "first_id": "svc_acct_abc", + "last_id": "svc_acct_xyz", + "has_more": false + } - ChatCompletionRequestFunctionMessage: - type: object - title: Function message - deprecated: true - properties: - role: - type: string - enum: ["function"] - description: The role of the messages author, in this case `function`. + post: + summary: Creates a new service account in the project. This also returns an unredacted API key for the service account. + operationId: create-project-service-account + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + requestBody: + description: The project service account create request payload. + required: true content: - nullable: true - type: string - description: The contents of the function message. - name: - type: string - description: The name of the function to call. - required: - - role - - content - - name + application/json: + schema: + $ref: '#/components/schemas/ProjectServiceAccountCreateRequest' + responses: + "200": + description: Project service account created successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectServiceAccountCreateResponse' + "400": + description: Error response when project is archived. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: Create project service account + group: administration + returns: The created [ProjectServiceAccount](/docs/api-reference/project-service-accounts/object) object. + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/service_accounts \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Production App" + }' + response: + content: | + { + "object": "organization.project.service_account", + "id": "svc_acct_abc", + "name": "Production App", + "role": "member", + "created_at": 1711471533, + "api_key": { + "object": "organization.project.service_account.api_key", + "value": "sk-abcdefghijklmnop123", + "name": "Secret Key", + "created_at": 1711471533, + "id": "key_abc" + } + } - FunctionParameters: - type: object - description: "The parameters the functions accepts, described as a JSON Schema object. See the [guide](/docs/guides/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. \n\nOmitting `parameters` defines a function with an empty parameter list." - additionalProperties: true + /organization/projects/{project_id}/service_accounts/{service_account_id}: + get: + summary: Retrieves a service account in the project. + operationId: retrieve-project-service-account + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: service_account_id + in: path + description: The ID of the service account. + required: true + schema: + type: string + responses: + "200": + description: Project service account retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectServiceAccount' + x-oaiMeta: + name: Retrieve project service account + group: administration + returns: The [ProjectServiceAccount](/docs/api-reference/project-service-accounts/object) object matching the specified ID. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.project.service_account", + "id": "svc_acct_abc", + "name": "Service Account", + "role": "owner", + "created_at": 1711471533 + } - ChatCompletionFunctions: - type: object - deprecated: true - properties: - description: - type: string - description: A description of what the function does, used by the model to choose when and how to call the function. - name: - type: string - description: The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. - parameters: - $ref: "#/components/schemas/FunctionParameters" - required: - - name + delete: + summary: Deletes a service account from the project. + operationId: delete-project-service-account + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: service_account_id + in: path + description: The ID of the service account. + required: true + schema: + type: string + responses: + "200": + description: Project service account deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectServiceAccountDeleteResponse' + x-oaiMeta: + name: Delete project service account + group: administration + returns: Confirmation of service account being deleted, or an error in case of an archived project, which has no service accounts + examples: + request: + curl: | + curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.project.service_account.deleted", + "id": "svc_acct_abc", + "deleted": true + } - ChatCompletionFunctionCallOption: - type: object - description: > - Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. - properties: - name: - type: string - description: The name of the function to call. - required: - - name + /organization/projects/{project_id}/api_keys: + get: + summary: Returns a list of API keys in the project. + operationId: list-project-api-keys + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: *pagination_after_param_description + required: false + schema: + type: string + responses: + "200": + description: Project API keys listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectApiKeyListResponse' - ChatCompletionTool: - type: object - properties: - type: - type: string - enum: ["function"] - description: The type of the tool. Currently, only `function` is supported. - function: - $ref: "#/components/schemas/FunctionObject" - required: - - type - - function + x-oaiMeta: + name: List project API keys + group: administration + returns: A list of [ProjectApiKey](/docs/api-reference/project-api-keys/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/projects/proj_abc/api_keys?after=key_abc&limit=20 \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "list", + "data": [ + { + "object": "organization.project.api_key", + "redacted_value": "sk-abc...def", + "name": "My API Key", + "created_at": 1711471533, + "id": "key_abc", + "owner": { + "type": "user", + "user": { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + } + } + ], + "first_id": "key_abc", + "last_id": "key_xyz", + "has_more": false + } + error_response: + content: | + { + "code": 400, + "message": "Project {name} is archived" + } - FunctionObject: - type: object - properties: - description: - type: string - description: A description of what the function does, used by the model to choose when and how to call the function. - name: - type: string - description: The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. - parameters: - $ref: "#/components/schemas/FunctionParameters" - required: - - name + /organization/projects/{project_id}/api_keys/{key_id}: + get: + summary: Retrieves an API key in the project. + operationId: retrieve-project-api-key + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: key_id + in: path + description: The ID of the API key. + required: true + schema: + type: string + responses: + "200": + description: Project API key retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectApiKey' + x-oaiMeta: + name: Retrieve project API key + group: administration + returns: The [ProjectApiKey](/docs/api-reference/project-api-keys/object) object matching the specified ID. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.project.api_key", + "redacted_value": "sk-abc...def", + "name": "My API Key", + "created_at": 1711471533, + "id": "key_abc", + "owner": { + "type": "user", + "user": { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + } + } - ChatCompletionToolChoiceOption: - description: | - Controls which (if any) tool is called by the model. - `none` means the model will not call any tool and instead generates a message. - `auto` means the model can pick between generating a message or calling one or more tools. - `required` means the model must call one or more tools. - Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + delete: + summary: Deletes an API key from the project. + operationId: delete-project-api-key + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: key_id + in: path + description: The ID of the API key. + required: true + schema: + type: string + responses: + "200": + description: Project API key deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectApiKeyDeleteResponse' + "400": + description: Error response for various conditions. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: Delete project API key + group: administration + returns: Confirmation of the key's deletion or an error if the key belonged to a service account + examples: + request: + curl: | + curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: + content: | + { + "object": "organization.project.api_key.deleted", + "id": "key_abc", + "deleted": true + } + error_response: + content: | + { + "code": 400, + "message": "API keys cannot be deleted for service accounts, please delete the service account" + } - `none` is the default when no tools are present. `auto` is the default if tools are present. - oneOf: - - type: string - description: > - `none` means the model will not call any tool and instead generates a message. - `auto` means the model can pick between generating a message or calling one or more tools. - `required` means the model must call one or more tools. - enum: [none, auto, required] - - $ref: "#/components/schemas/ChatCompletionNamedToolChoice" - x-oaiExpandable: true +components: + securitySchemes: + ApiKeyAuth: + type: http + scheme: "bearer" - ChatCompletionNamedToolChoice: + schemas: + Error: type: object - description: Specifies a tool the model should use. Use to force the model to call a specific function. properties: + code: + type: string + nullable: true + message: + type: string + nullable: false + param: + type: string + nullable: true type: type: string - enum: ["function"] - description: The type of the tool. Currently, only `function` is supported. - function: - type: object - properties: - name: - type: string - description: The name of the function to call. - required: - - name + nullable: false required: - type - - function - - ParallelToolCalls: - description: Whether to enable [parallel function calling](/docs/guides/function-calling/parallel-function-calling) during tool use. - type: boolean - default: true - - ChatCompletionMessageToolCalls: - type: array - description: The tool calls generated by the model, such as function calls. - items: - $ref: "#/components/schemas/ChatCompletionMessageToolCall" + - message + - param + - code + ErrorResponse: + type: object + properties: + error: + $ref: "#/components/schemas/Error" + required: + - error - ChatCompletionMessageToolCall: + ListModelsResponse: type: object properties: - # TODO: index included when streaming - id: - type: string - description: The ID of the tool call. - type: + object: type: string - enum: ["function"] - description: The type of the tool. Currently, only `function` is supported. - function: - type: object - description: The function that the model called. - properties: - name: - type: string - description: The name of the function to call. - arguments: - type: string - description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. - required: - - name - - arguments + enum: [list] + data: + type: array + items: + $ref: "#/components/schemas/Model" required: - - id - - type - - function - - ChatCompletionMessageToolCallChunk: + - object + - data + DeleteModelResponse: type: object properties: - index: - type: integer id: type: string - description: The ID of the tool call. - type: + deleted: + type: boolean + object: type: string - enum: ["function"] - description: The type of the tool. Currently, only `function` is supported. - function: - type: object - properties: - name: - type: string - description: The name of the function to call. - arguments: - type: string - description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. required: - - index - - # Note, this isn't referenced anywhere, but is kept as a convenience to record all possible roles in one place. - ChatCompletionRole: - type: string - description: The role of the author of a message - enum: - - system - - user - - assistant - - tool - - function + - id + - object + - deleted - ChatCompletionStreamOptions: - description: | - Options for streaming response. Only set this when you set `stream: true`. + CreateCompletionRequest: type: object - nullable: true - default: null properties: - include_usage: - type: boolean - description: | - If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value. + model: + description: &model_description | + ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them. + anyOf: + - type: string + - type: string + enum: ["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"] + x-oaiTypeLabel: string + prompt: + description: &completions_prompt_description | + The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. - ChatCompletionResponseMessage: - type: object - description: A chat completion message generated by the model. - properties: - content: - type: string - description: The contents of the message. + Note that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document. + default: "<|endoftext|>" nullable: true - tool_calls: - $ref: "#/components/schemas/ChatCompletionMessageToolCalls" - role: - type: string - enum: ["assistant"] - description: The role of the author of this message. - function_call: - type: object - deprecated: true - description: "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." - properties: - arguments: - type: string - description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. - name: - type: string - description: The name of the function to call. - required: - - name - - arguments - required: - - role - - content - - ChatCompletionStreamResponseDelta: - type: object - description: A chat completion delta generated by streamed model responses. - properties: - content: - type: string - description: The contents of the chunk message. + oneOf: + - type: string + default: "" + example: "This is a test." + - type: array + items: + type: string + default: "" + example: "This is a test." + - type: array + minItems: 1 + items: + type: integer + example: "[1212, 318, 257, 1332, 13]" + - type: array + minItems: 1 + items: + type: array + minItems: 1 + items: + type: integer + example: "[[1212, 318, 257, 1332, 13]]" + best_of: + type: integer + default: 1 + minimum: 0 + maximum: 20 nullable: true - function_call: - deprecated: true - type: object - description: "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." - properties: - arguments: - type: string - description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. - name: - type: string - description: The name of the function to call. - tool_calls: - type: array - items: - $ref: "#/components/schemas/ChatCompletionMessageToolCallChunk" - role: - type: string - enum: ["system", "user", "assistant", "tool"] - description: The role of the author of this message. + description: &completions_best_of_description | + Generates `best_of` completions server-side and returns the "best" (the one with the highest log probability per token). Results cannot be streamed. - CreateChatCompletionRequest: - type: object - properties: - messages: - description: A list of messages comprising the conversation so far. [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). - type: array - minItems: 1 - items: - $ref: "#/components/schemas/ChatCompletionRequestMessage" - model: - description: ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) table for details on which models work with the Chat API. - example: "gpt-4-turbo" - anyOf: - - type: string - - type: string - enum: - [ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0301", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ] - x-oaiTypeLabel: string + When used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`. + + **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. + echo: + type: boolean + default: false + nullable: true + description: &completions_echo_description > + Echo back the prompt in addition to the completion frequency_penalty: type: number default: 0 minimum: -2 maximum: 2 nullable: true - description: *completions_frequency_penalty_description - logit_bias: + description: &completions_frequency_penalty_description | + Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. + + [See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details) + logit_bias: &completions_logit_bias type: object x-oaiTypeLabel: map default: null nullable: true additionalProperties: type: integer - description: | + description: &completions_logit_bias_description | Modify the likelihood of specified tokens appearing in the completion. - Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. - logprobs: - description: Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`. - type: boolean - default: false - nullable: true - top_logprobs: - description: An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used. + Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. + + As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. + logprobs: &completions_logprobs_configuration type: integer minimum: 0 - maximum: 20 + maximum: 5 + default: null nullable: true - max_tokens: - description: | - The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. + description: &completions_logprobs_description | + Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response. - The total length of input tokens and generated tokens is limited by the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. + The maximum value for `logprobs` is 5. + max_tokens: type: integer + minimum: 0 + default: 16 + example: 16 nullable: true + description: &completions_max_tokens_description | + The maximum number of [tokens](/tokenizer) that can be generated in the completion. + + The token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. n: type: integer minimum: 1 @@ -7891,61 +8826,63 @@ components: default: 1 example: 1 nullable: true - description: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + description: &completions_completions_description | + How many completions to generate for each prompt. + + **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. presence_penalty: type: number default: 0 minimum: -2 maximum: 2 nullable: true - description: *completions_presence_penalty_description - response_format: - type: object - description: | - An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. - - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. + description: &completions_presence_penalty_description | + Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. - properties: - type: - type: string - enum: ["text", "json_object"] - example: "json_object" - default: "text" - description: Must be one of `text` or `json_object`. - seed: + [See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details) + seed: &completions_seed_param type: integer minimum: -9223372036854775808 maximum: 9223372036854775807 nullable: true description: | - This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. - x-oaiMeta: - beta: true stop: - description: | - Up to 4 sequences where the API will stop generating further tokens. + description: &completions_stop_description > + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. default: null + nullable: true oneOf: - type: string + default: <|endoftext|> + example: "\n" nullable: true - type: array minItems: 1 maxItems: 4 items: type: string + example: '["\n"]' stream: description: > - If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). type: boolean nullable: true default: false stream_options: $ref: "#/components/schemas/ChatCompletionStreamOptions" + suffix: + description: | + The suffix that comes after a completion of inserted text. + + This parameter is only supported for `gpt-3.5-turbo-instruct`. + default: null + nullable: true + type: string + example: "test." temperature: type: number minimum: 0 @@ -7953,7 +8890,10 @@ components: default: 1 example: 1 nullable: true - description: *completions_temperature_description + description: &completions_temperature_description | + What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + + We generally recommend altering this or `top_p` but not both. top_p: type: number minimum: 0 @@ -7961,111 +8901,77 @@ components: default: 1 example: 1 nullable: true - description: *completions_top_p_description - tools: - type: array - description: > - A list of tools the model may call. Currently, only functions are supported as a tool. - Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported. - items: - $ref: "#/components/schemas/ChatCompletionTool" - tool_choice: - $ref: "#/components/schemas/ChatCompletionToolChoiceOption" - parallel_tool_calls: - $ref: "#/components/schemas/ParallelToolCalls" - user: *end_user_param_configuration - function_call: - deprecated: true - description: | - Deprecated in favor of `tool_choice`. - - Controls which (if any) function is called by the model. - `none` means the model will not call a function and instead generates a message. - `auto` means the model can pick between generating a message or calling a function. - Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. + description: &completions_top_p_description | + An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. - `none` is the default when no functions are present. `auto` is the default if functions are present. - oneOf: - - type: string - description: > - `none` means the model will not call a function and instead generates a message. - `auto` means the model can pick between generating a message or calling a function. - enum: [none, auto] - - $ref: "#/components/schemas/ChatCompletionFunctionCallOption" - x-oaiExpandable: true - functions: - deprecated: true + We generally recommend altering this or `temperature` but not both. + user: &end_user_param_configuration + type: string + example: user-1234 description: | - Deprecated in favor of `tools`. + A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). + required: + - model + - prompt - A list of functions the model may generate JSON inputs for. - type: array - minItems: 1 - maxItems: 128 - items: - $ref: "#/components/schemas/ChatCompletionFunctions" - - required: - - model - - messages - - CreateChatCompletionResponse: + CreateCompletionResponse: type: object - description: Represents a chat completion response returned by model, based on the provided input. + description: | + Represents a completion response from the API. Note: both the streamed and non-streamed response objects share the same shape (unlike the chat endpoint). properties: id: type: string - description: A unique identifier for the chat completion. + description: A unique identifier for the completion. choices: type: array - description: A list of chat completion choices. Can be more than one if `n` is greater than 1. + description: The list of completion choices the model generated for the input prompt. items: type: object required: - finish_reason - index - - message - logprobs + - text properties: finish_reason: type: string - description: &chat_completion_finish_reason_description | + description: &completion_finish_reason_description | The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, - `content_filter` if content was omitted due to a flag from our content filters, - `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. - enum: - [ - "stop", - "length", - "tool_calls", - "content_filter", - "function_call", - ] + or `content_filter` if content was omitted due to a flag from our content filters. + enum: ["stop", "length", "content_filter"] index: type: integer - description: The index of the choice in the list of choices. - message: - $ref: "#/components/schemas/ChatCompletionResponseMessage" - logprobs: &chat_completion_response_logprobs - description: Log probability information for the choice. + logprobs: type: object nullable: true properties: - content: - description: A list of message content tokens with log probability information. + text_offset: type: array items: - $ref: "#/components/schemas/ChatCompletionTokenLogprob" - nullable: true - required: - - content + type: integer + token_logprobs: + type: array + items: + type: number + tokens: + type: array + items: + type: string + top_logprobs: + type: array + items: + type: object + additionalProperties: + type: number + text: + type: string created: type: integer - description: The Unix timestamp (in seconds) of when the chat completion was created. + description: The Unix timestamp (in seconds) of when the completion was created. model: type: string - description: The model used for the chat completion. + description: The model used for completion. system_fingerprint: type: string description: | @@ -8074,3857 +8980,3686 @@ components: Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. object: type: string - description: The object type, which is always `chat.completion`. - enum: [chat.completion] + description: The object type, which is always "text_completion" + enum: [text_completion] usage: $ref: "#/components/schemas/CompletionUsage" required: - - choices - - created - id - - model - object + - created + - model + - choices x-oaiMeta: - name: The chat completion object - group: chat - example: *chat_completion_example + name: The completion object + legacy: true + example: | + { + "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", + "object": "text_completion", + "created": 1589478378, + "model": "gpt-4-turbo", + "choices": [ + { + "text": "\n\nThis is indeed a test", + "index": 0, + "logprobs": null, + "finish_reason": "length" + } + ], + "usage": { + "prompt_tokens": 5, + "completion_tokens": 7, + "total_tokens": 12 + } + } - CreateChatCompletionFunctionResponse: + ChatCompletionRequestMessageContentPartText: type: object - description: Represents a chat completion response returned by model, based on the provided input. + title: Text content part properties: - id: - type: string - description: A unique identifier for the chat completion. - choices: - type: array - description: A list of chat completion choices. Can be more than one if `n` is greater than 1. - items: - type: object - required: - - finish_reason - - index - - message - - logprobs - properties: - finish_reason: - type: string - description: - &chat_completion_function_finish_reason_description | - The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content filters, or `function_call` if the model called a function. - enum: - ["stop", "length", "function_call", "content_filter"] - index: - type: integer - description: The index of the choice in the list of choices. - message: - $ref: "#/components/schemas/ChatCompletionResponseMessage" - created: - type: integer - description: The Unix timestamp (in seconds) of when the chat completion was created. - model: - type: string - description: The model used for the chat completion. - system_fingerprint: + type: type: string - description: | - This fingerprint represents the backend configuration that the model runs with. - - Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. - object: + enum: ["text"] + description: The type of the content part. + text: type: string - description: The object type, which is always `chat.completion`. - enum: [chat.completion] - usage: - $ref: "#/components/schemas/CompletionUsage" + description: The text content. required: - - choices - - created - - id - - model - - object - x-oaiMeta: - name: The chat completion object - group: chat - example: *chat_completion_function_example + - type + - text - ChatCompletionTokenLogprob: + ChatCompletionRequestMessageContentPartImage: type: object + title: Image content part properties: - token: &chat_completion_response_logprobs_token - description: The token. + type: type: string - logprob: &chat_completion_response_logprobs_token_logprob - description: The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely. - type: number - bytes: &chat_completion_response_logprobs_bytes - description: A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token. - type: array - items: - type: integer - nullable: true - top_logprobs: - description: List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned. - type: array - items: - type: object - properties: - token: *chat_completion_response_logprobs_token - logprob: *chat_completion_response_logprobs_token_logprob - bytes: *chat_completion_response_logprobs_bytes - required: - - token - - logprob - - bytes + enum: ["image_url"] + description: The type of the content part. + image_url: + type: object + properties: + url: + type: string + description: Either a URL of the image or the base64 encoded image data. + format: uri + detail: + type: string + description: Specifies the detail level of the image. Learn more in the [Vision guide](/docs/guides/vision/low-or-high-fidelity-image-understanding). + enum: ["auto", "low", "high"] + default: "auto" + required: + - url required: - - token - - logprob - - bytes - - top_logprobs + - type + - image_url - ListPaginatedFineTuningJobsResponse: + ChatCompletionRequestMessageContentPartRefusal: type: object + title: Refusal content part properties: - data: - type: array - items: - $ref: "#/components/schemas/FineTuningJob" - has_more: - type: boolean - object: + type: type: string - enum: [list] + enum: ["refusal"] + description: The type of the content part. + refusal: + type: string + description: The refusal message generated by the model. required: - - object - - data - - has_more + - type + - refusal - CreateChatCompletionStreamResponse: - type: object - description: Represents a streamed chunk of a chat completion response returned by model, based on the provided input. - properties: - id: - type: string - description: A unique identifier for the chat completion. Each chunk has the same ID. - choices: - type: array - description: | - A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the - last chunk if you set `stream_options: {"include_usage": true}`. - items: - type: object - required: - - delta - - finish_reason - - index - properties: - delta: - $ref: "#/components/schemas/ChatCompletionStreamResponseDelta" - logprobs: *chat_completion_response_logprobs - finish_reason: - type: string - description: *chat_completion_finish_reason_description - enum: - [ - "stop", - "length", - "tool_calls", - "content_filter", - "function_call", - ] - nullable: true - index: - type: integer - description: The index of the choice in the list of choices. - created: - type: integer - description: The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp. - model: - type: string - description: The model to generate the completion. - system_fingerprint: + ChatCompletionRequestMessage: + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestSystemMessage" + - $ref: "#/components/schemas/ChatCompletionRequestUserMessage" + - $ref: "#/components/schemas/ChatCompletionRequestAssistantMessage" + - $ref: "#/components/schemas/ChatCompletionRequestToolMessage" + - $ref: "#/components/schemas/ChatCompletionRequestFunctionMessage" + x-oaiExpandable: true + + ChatCompletionRequestSystemMessageContentPart: + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartText" + x-oaiExpandable: true + + ChatCompletionRequestUserMessageContentPart: + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartText" + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartImage" + x-oaiExpandable: true + + ChatCompletionRequestAssistantMessageContentPart: + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartText" + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartRefusal" + x-oaiExpandable: true + + ChatCompletionRequestToolMessageContentPart: + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartText" + x-oaiExpandable: true + + ChatCompletionRequestSystemMessage: + type: object + title: System message + properties: + content: + description: The contents of the system message. + oneOf: + - type: string + description: The contents of the system message. + title: Text content + - type: array + description: An array of content parts with a defined type. For system messages, only type `text` is supported. + title: Array of content parts + items: + $ref: "#/components/schemas/ChatCompletionRequestSystemMessageContentPart" + minItems: 1 + role: type: string - description: | - This fingerprint represents the backend configuration that the model runs with. - Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. - object: + enum: ["system"] + description: The role of the messages author, in this case `system`. + name: type: string - description: The object type, which is always `chat.completion.chunk`. - enum: [chat.completion.chunk] - usage: - type: object - description: | - An optional field that will only be present when you set `stream_options: {"include_usage": true}` in your request. - When present, it contains a null value except for the last chunk which contains the token usage statistics for the entire request. - properties: - completion_tokens: - type: integer - description: Number of tokens in the generated completion. - prompt_tokens: - type: integer - description: Number of tokens in the prompt. - total_tokens: - type: integer - description: Total number of tokens used in the request (prompt + completion). - required: - - prompt_tokens - - completion_tokens - - total_tokens + description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. required: - - choices - - created - - id - - model - - object - x-oaiMeta: - name: The chat completion chunk object - group: chat - example: *chat_completion_chunk_example + - content + - role - CreateChatCompletionImageResponse: + ChatCompletionRequestUserMessage: type: object - description: Represents a streamed chunk of a chat completion response returned by model, based on the provided input. - x-oaiMeta: - name: The chat completion chunk object - group: chat - example: *chat_completion_image_example + title: User message + properties: + content: + description: | + The contents of the user message. + oneOf: + - type: string + description: The text contents of the message. + title: Text content + - type: array + description: An array of content parts with a defined type, each can be of type `text` or `image_url` when passing in images. You can pass multiple images by adding multiple `image_url` content parts. Image input is only supported when using the `gpt-4o` model. + title: Array of content parts + items: + $ref: "#/components/schemas/ChatCompletionRequestUserMessageContentPart" + minItems: 1 + x-oaiExpandable: true + role: + type: string + enum: ["user"] + description: The role of the messages author, in this case `user`. + name: + type: string + description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. + required: + - content + - role - CreateImageRequest: + ChatCompletionRequestAssistantMessage: type: object + title: Assistant message properties: - prompt: - description: A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`. - type: string - example: "A cute baby sea otter" - model: - anyOf: - - type: string - - type: string - enum: ["dall-e-2", "dall-e-3"] - x-oaiTypeLabel: string - default: "dall-e-2" - example: "dall-e-3" + content: nullable: true - description: The model to use for image generation. - n: &images_n - type: integer - minimum: 1 - maximum: 10 - default: 1 - example: 1 + oneOf: + - type: string + description: The contents of the assistant message. + title: Text content + - type: array + description: An array of content parts with a defined type. Can be one or more of type `text`, or exactly one of type `refusal`. + title: Array of content parts + items: + $ref: "#/components/schemas/ChatCompletionRequestAssistantMessageContentPart" + minItems: 1 + description: | + The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified. + refusal: nullable: true - description: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported. - quality: - type: string - enum: ["standard", "hd"] - default: "standard" - example: "standard" - description: The quality of the image that will be generated. `hd` creates images with finer details and greater consistency across the image. This param is only supported for `dall-e-3`. - response_format: &images_response_format type: string - enum: ["url", "b64_json"] - default: "url" - example: "url" - nullable: true - description: The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. - size: &images_size + description: The refusal message by the assistant. + role: type: string - enum: ["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"] - default: "1024x1024" - example: "1024x1024" - nullable: true - description: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3` models. - style: + enum: ["assistant"] + description: The role of the messages author, in this case `assistant`. + name: type: string - enum: ["vivid", "natural"] - default: "vivid" - example: "vivid" + description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. + tool_calls: + $ref: "#/components/schemas/ChatCompletionMessageToolCalls" + function_call: + type: object + deprecated: true + description: "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." nullable: true - description: The style of the generated images. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images. This param is only supported for `dall-e-3`. - user: *end_user_param_configuration + properties: + arguments: + type: string + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + name: + type: string + description: The name of the function to call. + required: + - arguments + - name required: - - prompt - - ImagesResponse: - properties: - created: - type: integer - data: - type: array - items: - $ref: "#/components/schemas/Image" + - role + + FineTuneChatCompletionRequestAssistantMessage: + allOf: + - type: object + title: Assistant message + deprecated: false + properties: + weight: + type: integer + enum: [0, 1] + description: "Controls whether the assistant message is trained against (0 or 1)" + - $ref: "#/components/schemas/ChatCompletionRequestAssistantMessage" required: - - created - - data + - role - Image: + ChatCompletionRequestToolMessage: type: object - description: Represents the url or the content of an image generated by the OpenAI API. + title: Tool message properties: - b64_json: + role: type: string - description: The base64-encoded JSON of the generated image, if `response_format` is `b64_json`. - url: + enum: ["tool"] + description: The role of the messages author, in this case `tool`. + content: + oneOf: + - type: string + description: The contents of the tool message. + title: Text content + - type: array + description: An array of content parts with a defined type. For tool messages, only type `text` is supported. + title: Array of content parts + items: + $ref: "#/components/schemas/ChatCompletionRequestToolMessageContentPart" + minItems: 1 + description: The contents of the tool message. + tool_call_id: type: string - description: The URL of the generated image, if `response_format` is `url` (default). - revised_prompt: + description: Tool call that this message is responding to. + required: + - role + - content + - tool_call_id + + ChatCompletionRequestFunctionMessage: + type: object + title: Function message + deprecated: true + properties: + role: type: string - description: The prompt that was used to generate the image, if there was any revision to the prompt. - x-oaiMeta: - name: The image object - example: | - { - "url": "...", - "revised_prompt": "..." - } + enum: ["function"] + description: The role of the messages author, in this case `function`. + content: + nullable: true + type: string + description: The contents of the function message. + name: + type: string + description: The name of the function to call. + required: + - role + - content + - name - CreateImageEditRequest: + FunctionParameters: + type: object + description: "The parameters the functions accepts, described as a JSON Schema object. See the [guide](/docs/guides/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. \n\nOmitting `parameters` defines a function with an empty parameter list." + additionalProperties: true + + ChatCompletionFunctions: type: object + deprecated: true properties: - image: - description: The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask. + description: type: string - format: binary - prompt: - description: A text description of the desired image(s). The maximum length is 1000 characters. + description: A description of what the function does, used by the model to choose when and how to call the function. + name: type: string - example: "A cute baby sea otter wearing a beret" - mask: - description: An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. + description: The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + parameters: + $ref: "#/components/schemas/FunctionParameters" + required: + - name + + ChatCompletionFunctionCallOption: + type: object + description: > + Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. + properties: + name: type: string - format: binary - model: - anyOf: - - type: string - - type: string - enum: ["dall-e-2"] - x-oaiTypeLabel: string - default: "dall-e-2" - example: "dall-e-2" - nullable: true - description: The model to use for image generation. Only `dall-e-2` is supported at this time. - n: - type: integer - minimum: 1 - maximum: 10 - default: 1 - example: 1 - nullable: true - description: The number of images to generate. Must be between 1 and 10. - size: &dalle2_images_size + description: The name of the function to call. + required: + - name + + ChatCompletionTool: + type: object + properties: + type: type: string - enum: ["256x256", "512x512", "1024x1024"] - default: "1024x1024" - example: "1024x1024" - nullable: true - description: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. - response_format: *images_response_format - user: *end_user_param_configuration + enum: ["function"] + description: The type of the tool. Currently, only `function` is supported. + function: + $ref: "#/components/schemas/FunctionObject" required: - - prompt - - image + - type + - function - CreateImageVariationRequest: + FunctionObject: type: object properties: - image: - description: The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square. + description: type: string - format: binary - model: - anyOf: - - type: string - - type: string - enum: ["dall-e-2"] - x-oaiTypeLabel: string - default: "dall-e-2" - example: "dall-e-2" - nullable: true - description: The model to use for image generation. Only `dall-e-2` is supported at this time. - n: *images_n - response_format: *images_response_format - size: *dalle2_images_size - user: *end_user_param_configuration + description: A description of what the function does, used by the model to choose when and how to call the function. + name: + type: string + description: The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + parameters: + $ref: "#/components/schemas/FunctionParameters" + strict: + type: boolean + nullable: true + default: false + description: Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](docs/guides/function-calling). required: - - image + - name - CreateModerationRequest: + ResponseFormatText: type: object properties: - input: - description: The input text to classify - oneOf: - - type: string - default: "" - example: "I want to kill them." - - type: array - items: - type: string - default: "" - example: "I want to kill them." - model: - description: | - Two content moderations models are available: `text-moderation-stable` and `text-moderation-latest`. + type: + type: string + description: "The type of response format being defined: `text`" + enum: ["text"] + required: + - type - The default is `text-moderation-latest` which will be automatically upgraded over time. This ensures you are always using our most accurate model. If you use `text-moderation-stable`, we will provide advanced notice before updating the model. Accuracy of `text-moderation-stable` may be slightly lower than for `text-moderation-latest`. - nullable: false - default: "text-moderation-latest" - example: "text-moderation-stable" - anyOf: - - type: string - - type: string - enum: ["text-moderation-latest", "text-moderation-stable"] - x-oaiTypeLabel: string + ResponseFormatJsonObject: + type: object + properties: + type: + type: string + description: "The type of response format being defined: `json_object`" + enum: ["json_object"] required: - - input + - type - CreateModerationResponse: + ResponseFormatJsonSchemaSchema: + type: object + description: "The schema for the response format, described as a JSON Schema object." + additionalProperties: true + + ResponseFormatJsonSchema: + type: object + properties: + type: + type: string + description: 'The type of response format being defined: `json_schema`' + enum: ['json_schema'] + json_schema: + type: object + properties: + description: + type: string + description: A description of what the response format is for, used by the model to determine how to respond in the format. + name: + type: string + description: The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + schema: + $ref: '#/components/schemas/ResponseFormatJsonSchemaSchema' + strict: + type: boolean + nullable: true + default: false + description: Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs). + required: + - type + - name + required: + - type + - json_schema + + ChatCompletionToolChoiceOption: + description: | + Controls which (if any) tool is called by the model. + `none` means the model will not call any tool and instead generates a message. + `auto` means the model can pick between generating a message or calling one or more tools. + `required` means the model must call one or more tools. + Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + + `none` is the default when no tools are present. `auto` is the default if tools are present. + oneOf: + - type: string + description: > + `none` means the model will not call any tool and instead generates a message. + `auto` means the model can pick between generating a message or calling one or more tools. + `required` means the model must call one or more tools. + enum: [none, auto, required] + - $ref: "#/components/schemas/ChatCompletionNamedToolChoice" + x-oaiExpandable: true + + ChatCompletionNamedToolChoice: + type: object + description: Specifies a tool the model should use. Use to force the model to call a specific function. + properties: + type: + type: string + enum: ["function"] + description: The type of the tool. Currently, only `function` is supported. + function: + type: object + properties: + name: + type: string + description: The name of the function to call. + required: + - name + required: + - type + - function + + ParallelToolCalls: + description: Whether to enable [parallel function calling](/docs/guides/function-calling/parallel-function-calling) during tool use. + type: boolean + default: true + + ChatCompletionMessageToolCalls: + type: array + description: The tool calls generated by the model, such as function calls. + items: + $ref: "#/components/schemas/ChatCompletionMessageToolCall" + + ChatCompletionMessageToolCall: type: object - description: Represents if a given text input is potentially harmful. properties: + # TODO: index included when streaming id: type: string - description: The unique identifier for the moderation request. - model: + description: The ID of the tool call. + type: type: string - description: The model used to generate the moderation results. - results: - type: array - description: A list of moderation objects. - items: - type: object - properties: - flagged: - type: boolean - description: Whether any of the below categories are flagged. - categories: - type: object - description: A list of the categories, and whether they are flagged or not. - properties: - hate: - type: boolean - description: Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is harassment. - hate/threatening: - type: boolean - description: Hateful content that also includes violence or serious harm towards the targeted group based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. - harassment: - type: boolean - description: Content that expresses, incites, or promotes harassing language towards any target. - harassment/threatening: - type: boolean - description: Harassment content that also includes violence or serious harm towards any target. - self-harm: - type: boolean - description: Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders. - self-harm/intent: - type: boolean - description: Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders. - self-harm/instructions: - type: boolean - description: Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts. - sexual: - type: boolean - description: Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness). - sexual/minors: - type: boolean - description: Sexual content that includes an individual who is under 18 years old. - violence: - type: boolean - description: Content that depicts death, violence, or physical injury. - violence/graphic: - type: boolean - description: Content that depicts death, violence, or physical injury in graphic detail. - required: - - hate - - hate/threatening - - harassment - - harassment/threatening - - self-harm - - self-harm/intent - - self-harm/instructions - - sexual - - sexual/minors - - violence - - violence/graphic - category_scores: - type: object - description: A list of the categories along with their scores as predicted by model. - properties: - hate: - type: number - description: The score for the category 'hate'. - hate/threatening: - type: number - description: The score for the category 'hate/threatening'. - harassment: - type: number - description: The score for the category 'harassment'. - harassment/threatening: - type: number - description: The score for the category 'harassment/threatening'. - self-harm: - type: number - description: The score for the category 'self-harm'. - self-harm/intent: - type: number - description: The score for the category 'self-harm/intent'. - self-harm/instructions: - type: number - description: The score for the category 'self-harm/instructions'. - sexual: - type: number - description: The score for the category 'sexual'. - sexual/minors: - type: number - description: The score for the category 'sexual/minors'. - violence: - type: number - description: The score for the category 'violence'. - violence/graphic: - type: number - description: The score for the category 'violence/graphic'. - required: - - hate - - hate/threatening - - harassment - - harassment/threatening - - self-harm - - self-harm/intent - - self-harm/instructions - - sexual - - sexual/minors - - violence - - violence/graphic - required: - - flagged - - categories - - category_scores + enum: ["function"] + description: The type of the tool. Currently, only `function` is supported. + function: + type: object + description: The function that the model called. + properties: + name: + type: string + description: The name of the function to call. + arguments: + type: string + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + required: + - name + - arguments required: - id - - model - - results - x-oaiMeta: - name: The moderation object - example: *moderation_example + - type + - function - ListFilesResponse: + ChatCompletionMessageToolCallChunk: type: object properties: - data: - type: array - items: - $ref: "#/components/schemas/OpenAIFile" - object: + index: + type: integer + id: type: string - enum: [list] + description: The ID of the tool call. + type: + type: string + enum: ["function"] + description: The type of the tool. Currently, only `function` is supported. + function: + type: object + properties: + name: + type: string + description: The name of the function to call. + arguments: + type: string + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. required: - - object - - data + - index - CreateFileRequest: + # Note, this isn't referenced anywhere, but is kept as a convenience to record all possible roles in one place. + ChatCompletionRole: + type: string + description: The role of the author of a message + enum: + - system + - user + - assistant + - tool + - function + + ChatCompletionStreamOptions: + description: | + Options for streaming response. Only set this when you set `stream: true`. type: object - additionalProperties: false + nullable: true + default: null properties: - file: - description: | - The File object (not file name) to be uploaded. - type: string - format: binary - purpose: + include_usage: + type: boolean description: | - The intended purpose of the uploaded file. - - Use "assistants" for [Assistants](/docs/api-reference/assistants) and [Message](/docs/api-reference/messages) files, "vision" for Assistants image file inputs, "batch" for [Batch API](/docs/guides/batch), and "fine-tune" for [Fine-tuning](/docs/api-reference/fine-tuning). - type: string - enum: ["assistants", "batch", "fine-tune", "vision"] - required: - - file - - purpose + If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value. - DeleteFileResponse: + ChatCompletionResponseMessage: type: object + description: A chat completion message generated by the model. properties: - id: + content: type: string - object: + description: The contents of the message. + nullable: true + refusal: type: string - enum: [file] - deleted: - type: boolean + description: The refusal message generated by the model. + nullable: true + tool_calls: + $ref: "#/components/schemas/ChatCompletionMessageToolCalls" + role: + type: string + enum: ["assistant"] + description: The role of the author of this message. + function_call: + type: object + deprecated: true + description: "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." + properties: + arguments: + type: string + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + name: + type: string + description: The name of the function to call. + required: + - name + - arguments required: - - id - - object - - deleted + - role + - content + - refusal - CreateFineTuningJobRequest: + ChatCompletionStreamResponseDelta: type: object + description: A chat completion delta generated by streamed model responses. properties: - model: - description: | - The name of the model to fine-tune. You can select one of the - [supported models](/docs/guides/fine-tuning/what-models-can-be-fine-tuned). - example: "gpt-3.5-turbo" - anyOf: - - type: string - - type: string - enum: ["babbage-002", "davinci-002", "gpt-3.5-turbo"] - x-oaiTypeLabel: string - training_file: - description: | - The ID of an uploaded file that contains training data. - - See [upload file](/docs/api-reference/files/create) for how to upload a file. - - Your dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`. - - The contents of the file should differ depending on if the model uses the [chat](/docs/api-reference/fine-tuning/chat-input) or [completions](/docs/api-reference/fine-tuning/completions-input) format. - - See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. + content: type: string - example: "file-abc123" - hyperparameters: + description: The contents of the chunk message. + nullable: true + function_call: + deprecated: true type: object - description: The hyperparameters used for the fine-tuning job. + description: "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." properties: - batch_size: - description: | - Number of examples in each batch. A larger batch size means that model parameters - are updated less frequently, but with lower variance. - oneOf: - - type: string - enum: [auto] - - type: integer - minimum: 1 - maximum: 256 - default: auto - learning_rate_multiplier: - description: | - Scaling factor for the learning rate. A smaller learning rate may be useful to avoid - overfitting. - oneOf: - - type: string - enum: [auto] - - type: number - minimum: 0 - exclusiveMinimum: true - default: auto - n_epochs: - description: | - The number of epochs to train the model for. An epoch refers to one full cycle - through the training dataset. - oneOf: - - type: string - enum: [auto] - - type: integer - minimum: 1 - maximum: 50 - default: auto - suffix: - description: | - A string of up to 18 characters that will be added to your fine-tuned model name. - - For example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. - type: string - minLength: 1 - maxLength: 40 - default: null - nullable: true - validation_file: - description: | - The ID of an uploaded file that contains validation data. - - If you provide this file, the data is used to generate validation - metrics periodically during fine-tuning. These metrics can be viewed in - the fine-tuning results file. - The same data should not be present in both train and validation files. - - Your dataset must be formatted as a JSONL file. You must upload your file with the purpose `fine-tune`. - - See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. - type: string - nullable: true - example: "file-abc123" - integrations: - type: array - description: A list of integrations to enable for your fine-tuning job. - nullable: true - items: - type: object - required: - - type - - wandb - properties: - type: - description: | - The type of integration to enable. Currently, only "wandb" (Weights and Biases) is supported. - oneOf: - - type: string - enum: [wandb] - wandb: - type: object - description: | - The settings for your integration with Weights and Biases. This payload specifies the project that - metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags - to your run, and set a default entity (team, username, etc) to be associated with your run. - required: - - project - properties: - project: - description: | - The name of the project that the new run will be created under. - type: string - example: "my-wandb-project" - name: - description: | - A display name to set for the run. If not set, we will use the Job ID as the name. - nullable: true - type: string - entity: - description: | - The entity to use for the run. This allows you to set the team or username of the WandB user that you would - like associated with the run. If not set, the default entity for the registered WandB API key is used. - nullable: true - type: string - tags: - description: | - A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some - default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". - type: array - items: - type: string - example: "custom-tag" - - seed: - description: | - The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases. - If a seed is not specified, one will be generated for you. - type: integer - nullable: true - minimum: 0 - maximum: 2147483647 - example: 42 - required: - - model - - training_file - - ListFineTuningJobEventsResponse: - type: object - properties: - data: - type: array - items: - $ref: "#/components/schemas/FineTuningJobEvent" - object: - type: string - enum: [list] - required: - - object - - data - - ListFineTuningJobCheckpointsResponse: - type: object - properties: - data: + arguments: + type: string + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + name: + type: string + description: The name of the function to call. + tool_calls: type: array items: - $ref: "#/components/schemas/FineTuningJobCheckpoint" - object: - type: string - enum: [list] - first_id: + $ref: "#/components/schemas/ChatCompletionMessageToolCallChunk" + role: type: string - nullable: true - last_id: + enum: ["system", "user", "assistant", "tool"] + description: The role of the author of this message. + refusal: type: string + description: The refusal message generated by the model. nullable: true - has_more: - type: boolean - required: - - object - - data - - has_more - CreateEmbeddingRequest: + CreateChatCompletionRequest: type: object - additionalProperties: false properties: - input: - description: | - Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. - example: "The quick brown fox jumped over the lazy dog" - oneOf: - - type: string - title: string - description: The string that will be turned into an embedding. - default: "" - example: "This is a test." - - type: array - title: array - description: The array of strings that will be turned into an embedding. - minItems: 1 - maxItems: 2048 - items: - type: string - default: "" - example: "['This is a test.']" - - type: array - title: array - description: The array of integers that will be turned into an embedding. - minItems: 1 - maxItems: 2048 - items: - type: integer - example: "[1212, 318, 257, 1332, 13]" - - type: array - title: array - description: The array of arrays containing integers that will be turned into an embedding. - minItems: 1 - maxItems: 2048 - items: - type: array - minItems: 1 - items: - type: integer - example: "[[1212, 318, 257, 1332, 13]]" - x-oaiExpandable: true + messages: + description: A list of messages comprising the conversation so far. [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + type: array + minItems: 1 + items: + $ref: "#/components/schemas/ChatCompletionRequestMessage" model: - description: *model_description - example: "text-embedding-3-small" + description: ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) table for details on which models work with the Chat API. + example: "gpt-4o" anyOf: - type: string - type: string enum: [ - "text-embedding-ada-002", - "text-embedding-3-small", - "text-embedding-3-large", + "gpt-4o", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "chatgpt-4o-latest", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", ] x-oaiTypeLabel: string - encoding_format: - description: "The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/)." - example: "float" - default: "float" - type: string - enum: ["float", "base64"] - dimensions: - description: | - The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. - type: integer - minimum: 1 - user: *end_user_param_configuration - required: - - model - - input - - CreateEmbeddingResponse: - type: object - properties: - data: - type: array - description: The list of embeddings generated by the model. - items: - $ref: "#/components/schemas/Embedding" - model: - type: string - description: The name of the model used to generate the embedding. - object: - type: string - description: The object type, which is always "list". - enum: [list] - usage: + frequency_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 + nullable: true + description: *completions_frequency_penalty_description + logit_bias: type: object - description: The usage information for the request. - properties: - prompt_tokens: - type: integer - description: The number of tokens used by the prompt. - total_tokens: - type: integer - description: The total number of tokens used by the request. - required: - - prompt_tokens - - total_tokens - required: - - object - - model - - data - - usage - - CreateTranscriptionRequest: - type: object - additionalProperties: false - properties: - file: + x-oaiTypeLabel: map + default: null + nullable: true + additionalProperties: + type: integer description: | - The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. - type: string - x-oaiTypeLabel: file - format: binary - model: + Modify the likelihood of specified tokens appearing in the completion. + + Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. + logprobs: + description: Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`. + type: boolean + default: false + nullable: true + top_logprobs: + description: An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used. + type: integer + minimum: 0 + maximum: 20 + nullable: true + max_tokens: description: | - ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available. - example: whisper-1 - anyOf: - - type: string - - type: string - enum: ["whisper-1"] - x-oaiTypeLabel: string - language: + The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. + + The total length of input tokens and generated tokens is limited by the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. + type: integer + nullable: true + n: + type: integer + minimum: 1 + maximum: 128 + default: 1 + example: 1 + nullable: true + description: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + presence_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 + nullable: true + description: *completions_presence_penalty_description + response_format: description: | - The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will improve accuracy and latency. - type: string - prompt: + An object specifying the format that the model must output. Compatible with [GPT-4o](/docs/models/gpt-4o), [GPT-4o mini](/docs/models/gpt-4o-mini), [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which guarantees the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/docs/guides/structured-outputs). + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. + oneOf: + - $ref: "#/components/schemas/ResponseFormatText" + - $ref: "#/components/schemas/ResponseFormatJsonObject" + - $ref: "#/components/schemas/ResponseFormatJsonSchema" + x-oaiExpandable: true + seed: + type: integer + minimum: -9223372036854775808 + maximum: 9223372036854775807 + nullable: true description: | - An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. - type: string - response_format: + This feature is in Beta. + If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + x-oaiMeta: + beta: true + service_tier: + description: | + Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service: + - If set to 'auto', the system will utilize scale tier credits until they are exhausted. + - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` utilized. + type: string + enum: ["auto", "default"] + nullable: true + default: null + stop: description: | - The format of the transcript output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. - type: string - enum: - - json - - text - - srt - - verbose_json - - vtt - default: json + Up to 4 sequences where the API will stop generating further tokens. + default: null + oneOf: + - type: string + nullable: true + - type: array + minItems: 1 + maxItems: 4 + items: + type: string + stream: + description: > + If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + type: boolean + nullable: true + default: false + stream_options: + $ref: "#/components/schemas/ChatCompletionStreamOptions" temperature: - description: | - The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. type: number - default: 0 - timestamp_granularities[]: + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + description: *completions_temperature_description + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: *completions_top_p_description + tools: + type: array + description: > + A list of tools the model may call. Currently, only functions are supported as a tool. + Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported. + items: + $ref: "#/components/schemas/ChatCompletionTool" + tool_choice: + $ref: "#/components/schemas/ChatCompletionToolChoiceOption" + parallel_tool_calls: + $ref: "#/components/schemas/ParallelToolCalls" + user: *end_user_param_configuration + function_call: + deprecated: true description: | - The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. + Deprecated in favor of `tool_choice`. + + Controls which (if any) function is called by the model. + `none` means the model will not call a function and instead generates a message. + `auto` means the model can pick between generating a message or calling a function. + Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. + + `none` is the default when no functions are present. `auto` is the default if functions are present. + oneOf: + - type: string + description: > + `none` means the model will not call a function and instead generates a message. + `auto` means the model can pick between generating a message or calling a function. + enum: [none, auto] + - $ref: "#/components/schemas/ChatCompletionFunctionCallOption" + x-oaiExpandable: true + functions: + deprecated: true + description: | + Deprecated in favor of `tools`. + + A list of functions the model may generate JSON inputs for. type: array + minItems: 1 + maxItems: 128 items: - type: string - enum: - - word - - segment - default: [segment] - required: - - file - - model + $ref: "#/components/schemas/ChatCompletionFunctions" - # Note: This does not currently support the non-default response format types. - CreateTranscriptionResponseJson: - type: object - description: Represents a transcription response returned by model, based on the provided input. - properties: - text: - type: string - description: The transcribed text. required: - - text - x-oaiMeta: - name: The transcription object (JSON) - group: audio - example: *basic_transcription_response_example + - model + - messages - TranscriptionSegment: + CreateChatCompletionResponse: type: object + description: Represents a chat completion response returned by model, based on the provided input. properties: id: - type: integer - description: Unique identifier of the segment. - seek: - type: integer - description: Seek offset of the segment. - start: - type: number - format: float - description: Start time of the segment in seconds. - end: - type: number - format: float - description: End time of the segment in seconds. - text: type: string - description: Text content of the segment. - tokens: + description: A unique identifier for the chat completion. + choices: type: array + description: A list of chat completion choices. Can be more than one if `n` is greater than 1. items: - type: integer - description: Array of token IDs for the text content. - temperature: - type: number - format: float - description: Temperature parameter used for generating the segment. - avg_logprob: - type: number - format: float - description: Average logprob of the segment. If the value is lower than -1, consider the logprobs failed. - compression_ratio: - type: number - format: float - description: Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed. - no_speech_prob: - type: number - format: float - description: Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent. - required: - - id - - seek - - start - - end - - text - - tokens - - temperature - - avg_logprob - - compression_ratio - - no_speech_prob + type: object + required: + - finish_reason + - index + - message + - logprobs + properties: + finish_reason: + type: string + description: &chat_completion_finish_reason_description | + The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, + `length` if the maximum number of tokens specified in the request was reached, + `content_filter` if content was omitted due to a flag from our content filters, + `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. + enum: + [ + "stop", + "length", + "tool_calls", + "content_filter", + "function_call", + ] + index: + type: integer + description: The index of the choice in the list of choices. + message: + $ref: "#/components/schemas/ChatCompletionResponseMessage" + logprobs: &chat_completion_response_logprobs + description: Log probability information for the choice. + type: object + nullable: true + properties: + content: + description: A list of message content tokens with log probability information. + type: array + items: + $ref: "#/components/schemas/ChatCompletionTokenLogprob" + nullable: true + refusal: + description: A list of message refusal tokens with log probability information. + type: array + items: + $ref: "#/components/schemas/ChatCompletionTokenLogprob" + nullable: true + required: + - content + - refusal - TranscriptionWord: - type: object - properties: - word: + created: + type: integer + description: The Unix timestamp (in seconds) of when the chat completion was created. + model: type: string - description: The text content of the word. - start: - type: number - format: float - description: Start time of the word in seconds. - end: - type: number - format: float - description: End time of the word in seconds. - required: [word, start, end] - - CreateTranscriptionResponseVerboseJson: - type: object - description: Represents a verbose json transcription response returned by model, based on the provided input. - properties: - language: + description: The model used for the chat completion. + service_tier: + description: The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request. type: string - description: The language of the input audio. - duration: + enum: ["scale", "default"] + example: "scale" + nullable: true + system_fingerprint: type: string - description: The duration of the input audio. - text: + description: | + This fingerprint represents the backend configuration that the model runs with. + + Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + object: type: string - description: The transcribed text. - words: - type: array - description: Extracted words and their corresponding timestamps. - items: - $ref: "#/components/schemas/TranscriptionWord" - segments: - type: array - description: Segments of the transcribed text and their corresponding details. - items: - $ref: "#/components/schemas/TranscriptionSegment" - required: [language, duration, text] + description: The object type, which is always `chat.completion`. + enum: [chat.completion] + usage: + $ref: "#/components/schemas/CompletionUsage" + required: + - choices + - created + - id + - model + - object x-oaiMeta: - name: The transcription object (Verbose JSON) - group: audio - example: *verbose_transcription_response_example + name: The chat completion object + group: chat + example: *chat_completion_example - CreateTranslationRequest: + CreateChatCompletionFunctionResponse: type: object - additionalProperties: false + description: Represents a chat completion response returned by model, based on the provided input. properties: - file: - description: | - The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + id: type: string - x-oaiTypeLabel: file - format: binary + description: A unique identifier for the chat completion. + choices: + type: array + description: A list of chat completion choices. Can be more than one if `n` is greater than 1. + items: + type: object + required: + - finish_reason + - index + - message + - logprobs + properties: + finish_reason: + type: string + description: + &chat_completion_function_finish_reason_description | + The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content filters, or `function_call` if the model called a function. + enum: + ["stop", "length", "function_call", "content_filter"] + index: + type: integer + description: The index of the choice in the list of choices. + message: + $ref: "#/components/schemas/ChatCompletionResponseMessage" + created: + type: integer + description: The Unix timestamp (in seconds) of when the chat completion was created. model: - description: | - ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available. - example: whisper-1 - anyOf: - - type: string - - type: string - enum: ["whisper-1"] - x-oaiTypeLabel: string - prompt: - description: | - An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English. type: string - response_format: - description: | - The format of the transcript output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. + description: The model used for the chat completion. + system_fingerprint: type: string - default: json - temperature: description: | - The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. - type: number - default: 0 + This fingerprint represents the backend configuration that the model runs with. + + Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + object: + type: string + description: The object type, which is always `chat.completion`. + enum: [chat.completion] + usage: + $ref: "#/components/schemas/CompletionUsage" required: - - file + - choices + - created + - id - model + - object + x-oaiMeta: + name: The chat completion object + group: chat + example: *chat_completion_function_example - # Note: This does not currently support the non-default response format types. - CreateTranslationResponseJson: + ChatCompletionTokenLogprob: type: object properties: - text: + token: &chat_completion_response_logprobs_token + description: The token. type: string + logprob: &chat_completion_response_logprobs_token_logprob + description: The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely. + type: number + bytes: &chat_completion_response_logprobs_bytes + description: A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token. + type: array + items: + type: integer + nullable: true + top_logprobs: + description: List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned. + type: array + items: + type: object + properties: + token: *chat_completion_response_logprobs_token + logprob: *chat_completion_response_logprobs_token_logprob + bytes: *chat_completion_response_logprobs_bytes + required: + - token + - logprob + - bytes required: - - text + - token + - logprob + - bytes + - top_logprobs - CreateTranslationResponseVerboseJson: + ListPaginatedFineTuningJobsResponse: type: object properties: - language: - type: string - description: The language of the output translation (always `english`). - duration: - type: string - description: The duration of the input audio. - text: - type: string - description: The translated text. - segments: + data: type: array - description: Segments of the translated text and their corresponding details. items: - $ref: "#/components/schemas/TranscriptionSegment" - required: [language, duration, text] - - CreateSpeechRequest: - type: object - additionalProperties: false - properties: - model: - description: | - One of the available [TTS models](/docs/models/tts): `tts-1` or `tts-1-hd` - anyOf: - - type: string - - type: string - enum: ["tts-1", "tts-1-hd"] - x-oaiTypeLabel: string - input: - type: string - description: The text to generate audio for. The maximum length is 4096 characters. - maxLength: 4096 - voice: - description: The voice to use when generating the audio. Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are available in the [Text to speech guide](/docs/guides/text-to-speech/voice-options). - type: string - enum: ["alloy", "echo", "fable", "onyx", "nova", "shimmer"] - response_format: - description: "The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`." - default: "mp3" + $ref: "#/components/schemas/FineTuningJob" + has_more: + type: boolean + object: type: string - enum: ["mp3", "opus", "aac", "flac", "wav", "pcm"] - speed: - description: "The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default." - type: number - default: 1.0 - minimum: 0.25 - maximum: 4.0 + enum: [list] required: - - model - - input - - voice + - object + - data + - has_more - Model: - title: Model - description: Describes an OpenAI model offering that can be used with the API. + CreateChatCompletionStreamResponse: + type: object + description: Represents a streamed chunk of a chat completion response returned by model, based on the provided input. properties: id: type: string - description: The model identifier, which can be referenced in the API endpoints. + description: A unique identifier for the chat completion. Each chunk has the same ID. + choices: + type: array + description: | + A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the + last chunk if you set `stream_options: {"include_usage": true}`. + items: + type: object + required: + - delta + - finish_reason + - index + properties: + delta: + $ref: "#/components/schemas/ChatCompletionStreamResponseDelta" + logprobs: *chat_completion_response_logprobs + finish_reason: + type: string + description: *chat_completion_finish_reason_description + enum: + [ + "stop", + "length", + "tool_calls", + "content_filter", + "function_call", + ] + nullable: true + index: + type: integer + description: The index of the choice in the list of choices. created: type: integer - description: The Unix timestamp (in seconds) when the model was created. - object: + description: The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp. + model: type: string - description: The object type, which is always "model". - enum: [model] - owned_by: + description: The model to generate the completion. + service_tier: + description: The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request. type: string - description: The organization that owns the model. + enum: ["scale", "default"] + example: "scale" + nullable: true + system_fingerprint: + type: string + description: | + This fingerprint represents the backend configuration that the model runs with. + Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + object: + type: string + description: The object type, which is always `chat.completion.chunk`. + enum: [chat.completion.chunk] + usage: + type: object + description: | + An optional field that will only be present when you set `stream_options: {"include_usage": true}` in your request. + When present, it contains a null value except for the last chunk which contains the token usage statistics for the entire request. + properties: + completion_tokens: + type: integer + description: Number of tokens in the generated completion. + prompt_tokens: + type: integer + description: Number of tokens in the prompt. + total_tokens: + type: integer + description: Total number of tokens used in the request (prompt + completion). + required: + - prompt_tokens + - completion_tokens + - total_tokens required: + - choices + - created - id + - model - object - - created - - owned_by x-oaiMeta: - name: The model object - example: *retrieve_model_response + name: The chat completion chunk object + group: chat + example: *chat_completion_chunk_example - OpenAIFile: - title: OpenAIFile - description: The `File` object represents a document that has been uploaded to OpenAI. + CreateChatCompletionImageResponse: + type: object + description: Represents a streamed chunk of a chat completion response returned by model, based on the provided input. + x-oaiMeta: + name: The chat completion chunk object + group: chat + example: *chat_completion_image_example + + CreateImageRequest: + type: object properties: - id: + prompt: + description: A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`. type: string - description: The file identifier, which can be referenced in the API endpoints. - bytes: - type: integer - description: The size of the file, in bytes. - created_at: + example: "A cute baby sea otter" + model: + anyOf: + - type: string + - type: string + enum: ["dall-e-2", "dall-e-3"] + x-oaiTypeLabel: string + default: "dall-e-2" + example: "dall-e-3" + nullable: true + description: The model to use for image generation. + n: &images_n type: integer - description: The Unix timestamp (in seconds) for when the file was created. - filename: - type: string - description: The name of the file. - object: + minimum: 1 + maximum: 10 + default: 1 + example: 1 + nullable: true + description: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported. + quality: type: string - description: The object type, which is always `file`. - enum: ["file"] - purpose: + enum: ["standard", "hd"] + default: "standard" + example: "standard" + description: The quality of the image that will be generated. `hd` creates images with finer details and greater consistency across the image. This param is only supported for `dall-e-3`. + response_format: &images_response_format type: string - description: The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results` and `vision`. - enum: - [ - "assistants", - "assistants_output", - "batch", - "batch_output", - "fine-tune", - "fine-tune-results", - "vision", - ] - status: + enum: ["url", "b64_json"] + default: "url" + example: "url" + nullable: true + description: The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. + size: &images_size type: string - deprecated: true - description: Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`. - enum: ["uploaded", "processed", "error"] - status_details: + enum: ["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"] + default: "1024x1024" + example: "1024x1024" + nullable: true + description: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3` models. + style: type: string - deprecated: true - description: Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`. + enum: ["vivid", "natural"] + default: "vivid" + example: "vivid" + nullable: true + description: The style of the generated images. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images. This param is only supported for `dall-e-3`. + user: *end_user_param_configuration required: - - id - - object - - bytes - - created_at - - filename - - purpose - - status - x-oaiMeta: - name: The file object - example: | - { - "id": "file-abc123", - "object": "file", - "bytes": 120000, - "created_at": 1677610602, - "filename": "salesOverview.pdf", - "purpose": "assistants", - } - Embedding: - type: object - description: | - Represents an embedding vector returned by embedding endpoint. + - prompt + + ImagesResponse: properties: - index: + created: type: integer - description: The index of the embedding in the list of embeddings. - embedding: + data: type: array - description: | - The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the [embedding guide](/docs/guides/embeddings). items: - type: number - object: - type: string - description: The object type, which is always "embedding". - enum: [embedding] + $ref: "#/components/schemas/Image" required: - - index - - object - - embedding + - created + - data + + Image: + type: object + description: Represents the url or the content of an image generated by the OpenAI API. + properties: + b64_json: + type: string + description: The base64-encoded JSON of the generated image, if `response_format` is `b64_json`. + url: + type: string + description: The URL of the generated image, if `response_format` is `url` (default). + revised_prompt: + type: string + description: The prompt that was used to generate the image, if there was any revision to the prompt. x-oaiMeta: - name: The embedding object + name: The image object example: | { - "object": "embedding", - "embedding": [ - 0.0023064255, - -0.009327292, - .... (1536 floats total for ada-002) - -0.0028842222, - ], - "index": 0 + "url": "...", + "revised_prompt": "..." } - FineTuningJob: + CreateImageEditRequest: type: object - title: FineTuningJob - description: | - The `fine_tuning.job` object represents a fine-tuning job that has been created through the API. properties: - id: - type: string - description: The object identifier, which can be referenced in the API endpoints. - created_at: - type: integer - description: The Unix timestamp (in seconds) for when the fine-tuning job was created. - error: - type: object - nullable: true - description: For fine-tuning jobs that have `failed`, this will contain more information on the cause of the failure. - properties: - code: - type: string - description: A machine-readable error code. - message: - type: string - description: A human-readable error message. - param: - type: string - description: The parameter that was invalid, usually `training_file` or `validation_file`. This field will be null if the failure was not parameter-specific. - nullable: true - required: - - code - - message - - param - fine_tuned_model: - type: string - nullable: true - description: The name of the fine-tuned model that is being created. The value will be null if the fine-tuning job is still running. - finished_at: - type: integer - nullable: true - description: The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be null if the fine-tuning job is still running. - hyperparameters: - type: object - description: The hyperparameters used for the fine-tuning job. See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. - properties: - n_epochs: - oneOf: - - type: string - enum: [auto] - - type: integer - minimum: 1 - maximum: 50 - default: auto - description: - The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. - - "auto" decides the optimal number of epochs based on the size of the dataset. If setting the number manually, we support any number between 1 and 50 epochs. - required: - - n_epochs - model: - type: string - description: The base model that is being fine-tuned. - object: + image: + description: The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask. type: string - description: The object type, which is always "fine_tuning.job". - enum: [fine_tuning.job] - organization_id: + format: binary + prompt: + description: A text description of the desired image(s). The maximum length is 1000 characters. type: string - description: The organization that owns the fine-tuning job. - result_files: - type: array - description: The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the [Files API](/docs/api-reference/files/retrieve-contents). - items: - type: string - example: file-abc123 - status: + example: "A cute baby sea otter wearing a beret" + mask: + description: An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. type: string - description: The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. - enum: - [ - "validating_files", - "queued", - "running", - "succeeded", - "failed", - "cancelled", - ] - trained_tokens: + format: binary + model: + anyOf: + - type: string + - type: string + enum: ["dall-e-2"] + x-oaiTypeLabel: string + default: "dall-e-2" + example: "dall-e-2" + nullable: true + description: The model to use for image generation. Only `dall-e-2` is supported at this time. + n: type: integer + minimum: 1 + maximum: 10 + default: 1 + example: 1 nullable: true - description: The total number of billable tokens processed by this fine-tuning job. The value will be null if the fine-tuning job is still running. - training_file: - type: string - description: The file ID used for training. You can retrieve the training data with the [Files API](/docs/api-reference/files/retrieve-contents). - validation_file: + description: The number of images to generate. Must be between 1 and 10. + size: &dalle2_images_size type: string + enum: ["256x256", "512x512", "1024x1024"] + default: "1024x1024" + example: "1024x1024" nullable: true - description: The file ID used for validation. You can retrieve the validation results with the [Files API](/docs/api-reference/files/retrieve-contents). - integrations: - type: array - nullable: true - description: A list of integrations to enable for this fine-tuning job. - maxItems: 5 - items: - oneOf: - - $ref: "#/components/schemas/FineTuningIntegration" - x-oaiExpandable: true - seed: - type: integer - description: The seed used for the fine-tuning job. - estimated_finish: - type: integer - nullable: true - description: The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The value will be null if the fine-tuning job is not running. + description: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. + response_format: *images_response_format + user: *end_user_param_configuration required: - - created_at - - error - - finished_at - - fine_tuned_model - - hyperparameters - - id - - model - - object - - organization_id - - result_files - - status - - trained_tokens - - training_file - - validation_file - - seed - x-oaiMeta: - name: The fine-tuning job object - example: *fine_tuning_example + - prompt + - image - FineTuningIntegration: + CreateImageVariationRequest: type: object - title: Fine-Tuning Job Integration - required: - - type - - wandb properties: - type: + image: + description: The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square. type: string - description: "The type of the integration being enabled for the fine-tuning job" - enum: ["wandb"] - wandb: - type: object - description: | - The settings for your integration with Weights and Biases. This payload specifies the project that - metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags - to your run, and set a default entity (team, username, etc) to be associated with your run. - required: - - project - properties: - project: - description: | - The name of the project that the new run will be created under. - type: string - example: "my-wandb-project" - name: - description: | - A display name to set for the run. If not set, we will use the Job ID as the name. - nullable: true - type: string - entity: - description: | - The entity to use for the run. This allows you to set the team or username of the WandB user that you would - like associated with the run. If not set, the default entity for the registered WandB API key is used. - nullable: true - type: string - tags: - description: | - A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some - default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". - type: array - items: - type: string - example: "custom-tag" + format: binary + model: + anyOf: + - type: string + - type: string + enum: ["dall-e-2"] + x-oaiTypeLabel: string + default: "dall-e-2" + example: "dall-e-2" + nullable: true + description: The model to use for image generation. Only `dall-e-2` is supported at this time. + n: *images_n + response_format: *images_response_format + size: *dalle2_images_size + user: *end_user_param_configuration + required: + - image - FineTuningJobEvent: + CreateModerationRequest: type: object - description: Fine-tuning job event object properties: - id: - type: string - created_at: - type: integer - level: + input: + description: The input text to classify + oneOf: + - type: string + default: "" + example: "I want to kill them." + - type: array + items: + type: string + default: "" + example: "I want to kill them." + model: + description: | + Two content moderations models are available: `text-moderation-stable` and `text-moderation-latest`. + + The default is `text-moderation-latest` which will be automatically upgraded over time. This ensures you are always using our most accurate model. If you use `text-moderation-stable`, we will provide advanced notice before updating the model. Accuracy of `text-moderation-stable` may be slightly lower than for `text-moderation-latest`. + nullable: false + default: "text-moderation-latest" + example: "text-moderation-stable" + anyOf: + - type: string + - type: string + enum: ["text-moderation-latest", "text-moderation-stable"] + x-oaiTypeLabel: string + required: + - input + + CreateModerationResponse: + type: object + description: Represents if a given text input is potentially harmful. + properties: + id: type: string - enum: ["info", "warn", "error"] - message: + description: The unique identifier for the moderation request. + model: type: string + description: The model used to generate the moderation results. + results: + type: array + description: A list of moderation objects. + items: + type: object + properties: + flagged: + type: boolean + description: Whether any of the below categories are flagged. + categories: + type: object + description: A list of the categories, and whether they are flagged or not. + properties: + hate: + type: boolean + description: Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is harassment. + hate/threatening: + type: boolean + description: Hateful content that also includes violence or serious harm towards the targeted group based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. + harassment: + type: boolean + description: Content that expresses, incites, or promotes harassing language towards any target. + harassment/threatening: + type: boolean + description: Harassment content that also includes violence or serious harm towards any target. + self-harm: + type: boolean + description: Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders. + self-harm/intent: + type: boolean + description: Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders. + self-harm/instructions: + type: boolean + description: Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts. + sexual: + type: boolean + description: Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness). + sexual/minors: + type: boolean + description: Sexual content that includes an individual who is under 18 years old. + violence: + type: boolean + description: Content that depicts death, violence, or physical injury. + violence/graphic: + type: boolean + description: Content that depicts death, violence, or physical injury in graphic detail. + required: + - hate + - hate/threatening + - harassment + - harassment/threatening + - self-harm + - self-harm/intent + - self-harm/instructions + - sexual + - sexual/minors + - violence + - violence/graphic + category_scores: + type: object + description: A list of the categories along with their scores as predicted by model. + properties: + hate: + type: number + description: The score for the category 'hate'. + hate/threatening: + type: number + description: The score for the category 'hate/threatening'. + harassment: + type: number + description: The score for the category 'harassment'. + harassment/threatening: + type: number + description: The score for the category 'harassment/threatening'. + self-harm: + type: number + description: The score for the category 'self-harm'. + self-harm/intent: + type: number + description: The score for the category 'self-harm/intent'. + self-harm/instructions: + type: number + description: The score for the category 'self-harm/instructions'. + sexual: + type: number + description: The score for the category 'sexual'. + sexual/minors: + type: number + description: The score for the category 'sexual/minors'. + violence: + type: number + description: The score for the category 'violence'. + violence/graphic: + type: number + description: The score for the category 'violence/graphic'. + required: + - hate + - hate/threatening + - harassment + - harassment/threatening + - self-harm + - self-harm/intent + - self-harm/instructions + - sexual + - sexual/minors + - violence + - violence/graphic + required: + - flagged + - categories + - category_scores + required: + - id + - model + - results + x-oaiMeta: + name: The moderation object + example: *moderation_example + + ListFilesResponse: + type: object + properties: + data: + type: array + items: + $ref: "#/components/schemas/OpenAIFile" object: type: string - enum: [fine_tuning.job.event] + enum: [list] required: - - id - object - - created_at - - level - - message - x-oaiMeta: - name: The fine-tuning job event object - example: | - { - "object": "fine_tuning.job.event", - "id": "ftevent-abc123" - "created_at": 1677610602, - "level": "info", - "message": "Created fine-tuning job" - } + - data - FineTuningJobCheckpoint: + CreateFileRequest: type: object - title: FineTuningJobCheckpoint - description: | - The `fine_tuning.job.checkpoint` object represents a model checkpoint for a fine-tuning job that is ready to use. + additionalProperties: false properties: - id: + file: + description: | + The File object (not file name) to be uploaded. type: string - description: The checkpoint identifier, which can be referenced in the API endpoints. - created_at: - type: integer - description: The Unix timestamp (in seconds) for when the checkpoint was created. - fine_tuned_model_checkpoint: + format: binary + purpose: + description: | + The intended purpose of the uploaded file. + + Use "assistants" for [Assistants](/docs/api-reference/assistants) and [Message](/docs/api-reference/messages) files, "vision" for Assistants image file inputs, "batch" for [Batch API](/docs/guides/batch), and "fine-tune" for [Fine-tuning](/docs/api-reference/fine-tuning). type: string - description: The name of the fine-tuned checkpoint model that is created. - step_number: - type: integer - description: The step number that the checkpoint was created at. - metrics: - type: object - description: Metrics at the step number during the fine-tuning job. - properties: - step: - type: number - train_loss: - type: number - train_mean_token_accuracy: - type: number - valid_loss: - type: number - valid_mean_token_accuracy: - type: number - full_valid_loss: - type: number - full_valid_mean_token_accuracy: - type: number - fine_tuning_job_id: + enum: ["assistants", "batch", "fine-tune", "vision"] + required: + - file + - purpose + + DeleteFileResponse: + type: object + properties: + id: type: string - description: The name of the fine-tuning job that this checkpoint was created from. object: type: string - description: The object type, which is always "fine_tuning.job.checkpoint". - enum: [fine_tuning.job.checkpoint] + enum: [file] + deleted: + type: boolean required: - - created_at - - fine_tuning_job_id - - fine_tuned_model_checkpoint - id - - metrics - object - - step_number - x-oaiMeta: - name: The fine-tuning job checkpoint object - example: | - { - "object": "fine_tuning.job.checkpoint", - "id": "ftckpt_qtZ5Gyk4BLq1SfLFWp3RtO3P", - "created_at": 1712211699, - "fine_tuned_model_checkpoint": "ft:gpt-3.5-turbo-0125:my-org:custom_suffix:9ABel2dg:ckpt-step-88", - "fine_tuning_job_id": "ftjob-fpbNQ3H1GrMehXRf8cO97xTN", - "metrics": { - "step": 88, - "train_loss": 0.478, - "train_mean_token_accuracy": 0.924, - "valid_loss": 10.112, - "valid_mean_token_accuracy": 0.145, - "full_valid_loss": 0.567, - "full_valid_mean_token_accuracy": 0.944 - }, - "step_number": 88 - } + - deleted - FinetuneChatRequestInput: - type: object - description: The per-line training example of a fine-tuning input file for chat models - properties: - messages: - type: array - minItems: 1 - items: - oneOf: - - $ref: "#/components/schemas/ChatCompletionRequestSystemMessage" - - $ref: "#/components/schemas/ChatCompletionRequestUserMessage" - - $ref: "#/components/schemas/FineTuneChatCompletionRequestAssistantMessage" - - $ref: "#/components/schemas/ChatCompletionRequestToolMessage" - - $ref: "#/components/schemas/ChatCompletionRequestFunctionMessage" - x-oaiExpandable: true - tools: - type: array - description: A list of tools the model may generate JSON inputs for. - items: - $ref: "#/components/schemas/ChatCompletionTool" - parallel_tool_calls: - $ref: "#/components/schemas/ParallelToolCalls" - functions: - deprecated: true - description: - A list of functions the model may generate JSON inputs for. - type: array - minItems: 1 - maxItems: 128 - items: - $ref: "#/components/schemas/ChatCompletionFunctions" - x-oaiMeta: - name: Training format for chat models - example: | - { - "messages": [ - { "role": "user", "content": "What is the weather in San Francisco?" }, - { - "role": "assistant", - "tool_calls": [ - { - "id": "call_id", - "type": "function", - "function": { - "name": "get_current_weather", - "arguments": "{\"location\": \"San Francisco, USA\", \"format\": \"celsius\"}" - } - } - ] - } - ], - "parallel_tool_calls": false, - "tools": [ - { - "type": "function", - "function": { - "name": "get_current_weather", - "description": "Get the current weather", - "parameters": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and country, eg. San Francisco, USA" - }, - "format": { "type": "string", "enum": ["celsius", "fahrenheit"] } - }, - "required": ["location", "format"] - } - } - } - ] - } - - FinetuneCompletionRequestInput: + CreateUploadRequest: type: object - description: The per-line training example of a fine-tuning input file for completions models + additionalProperties: false properties: - prompt: + filename: + description: | + The name of the file to upload. type: string - description: The input prompt for this training example. - completion: + purpose: + description: | + The intended purpose of the uploaded file. + + See the [documentation on File purposes](/docs/api-reference/files/create#files-create-purpose). type: string - description: The desired completion for this training example. - x-oaiMeta: - name: Training format for completions models - example: | - { - "prompt": "What is the answer to 2+2", - "completion": "4" - } - - CompletionUsage: - type: object - description: Usage statistics for the completion request. - properties: - completion_tokens: - type: integer - description: Number of tokens in the generated completion. - prompt_tokens: - type: integer - description: Number of tokens in the prompt. - total_tokens: + enum: ["assistants", "batch", "fine-tune", "vision"] + bytes: + description: | + The number of bytes in the file you are uploading. type: integer - description: Total number of tokens used in the request (prompt + completion). + mime_type: + description: | + The MIME type of the file. + + This must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision. + type: string required: - - prompt_tokens - - completion_tokens - - total_tokens + - filename + - purpose + - bytes + - mime_type - RunCompletionUsage: + AddUploadPartRequest: type: object - description: Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). + additionalProperties: false properties: - completion_tokens: - type: integer - description: Number of completion tokens used over the course of the run. - prompt_tokens: - type: integer - description: Number of prompt tokens used over the course of the run. - total_tokens: - type: integer - description: Total number of tokens used (prompt + completion). + data: + description: | + The chunk of bytes for this Part. + type: string + format: binary required: - - prompt_tokens - - completion_tokens - - total_tokens - nullable: true + - data - RunStepCompletionUsage: + CompleteUploadRequest: type: object - description: Usage statistics related to the run step. This value will be `null` while the run step's status is `in_progress`. + additionalProperties: false properties: - completion_tokens: - type: integer - description: Number of completion tokens used over the course of the run step. - prompt_tokens: - type: integer - description: Number of prompt tokens used over the course of the run step. - total_tokens: - type: integer - description: Total number of tokens used (prompt + completion). + part_ids: + type: array + description: | + The ordered list of Part IDs. + items: + type: string + md5: + description: | + The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect. + type: string required: - - prompt_tokens - - completion_tokens - - total_tokens - nullable: true - - AssistantsApiResponseFormatOption: - description: | - Specifies the format that the model must output. Compatible with [GPT-4o](/docs/models/gpt-4o), [GPT-4 Turbo](/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. - - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. - - **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. - oneOf: - - type: string - description: > - `auto` is the default value - enum: [none, auto] - - $ref: "#/components/schemas/AssistantsApiResponseFormat" - x-oaiExpandable: true + - part_ids - AssistantsApiResponseFormat: + CancelUploadRequest: type: object - description: | - An object describing the expected output of the model. If `json_object` only `function` type `tools` are allowed to be passed to the Run. If `text` the model can return text or any value needed. - properties: - type: - type: string - enum: ["text", "json_object"] - example: "json_object" - default: "text" - description: Must be one of `text` or `json_object`. + additionalProperties: false - AssistantObject: + CreateFineTuningJobRequest: type: object - title: Assistant - description: Represents an `assistant` that can call the model and use tools. properties: - id: - description: The identifier, which can be referenced in API endpoints. - type: string - object: - description: The object type, which is always `assistant`. - type: string - enum: [assistant] - created_at: - description: The Unix timestamp (in seconds) for when the assistant was created. - type: integer - name: - description: &assistant_name_param_description | - The name of the assistant. The maximum length is 256 characters. - type: string - maxLength: 256 - nullable: true - description: - description: &assistant_description_param_description | - The description of the assistant. The maximum length is 512 characters. - type: string - maxLength: 512 - nullable: true model: - description: *model_description - type: string - instructions: - description: &assistant_instructions_param_description | - The system instructions that the assistant uses. The maximum length is 256,000 characters. + description: | + The name of the model to fine-tune. You can select one of the + [supported models](/docs/guides/fine-tuning/which-models-can-be-fine-tuned). + example: "gpt-4o-mini" + anyOf: + - type: string + - type: string + enum: ["babbage-002", "davinci-002", "gpt-3.5-turbo", "gpt-4o-mini"] + x-oaiTypeLabel: string + training_file: + description: | + The ID of an uploaded file that contains training data. + + See [upload file](/docs/api-reference/files/create) for how to upload a file. + + Your dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`. + + The contents of the file should differ depending on if the model uses the [chat](/docs/api-reference/fine-tuning/chat-input) or [completions](/docs/api-reference/fine-tuning/completions-input) format. + + See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. type: string - maxLength: 256000 - nullable: true - tools: - description: &assistant_tools_param_description | - A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`. - default: [] - type: array - maxItems: 128 - items: - oneOf: - - $ref: "#/components/schemas/AssistantToolsCode" - - $ref: "#/components/schemas/AssistantToolsFileSearch" - - $ref: "#/components/schemas/AssistantToolsFunction" - x-oaiExpandable: true - tool_resources: + example: "file-abc123" + hyperparameters: type: object - description: | - A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + description: The hyperparameters used for the fine-tuning job. properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: | - A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: | - The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. - maxItems: 1 - items: - type: string + batch_size: + description: | + Number of examples in each batch. A larger batch size means that model parameters + are updated less frequently, but with lower variance. + oneOf: + - type: string + enum: [auto] + - type: integer + minimum: 1 + maximum: 256 + default: auto + learning_rate_multiplier: + description: | + Scaling factor for the learning rate. A smaller learning rate may be useful to avoid + overfitting. + oneOf: + - type: string + enum: [auto] + - type: number + minimum: 0 + exclusiveMinimum: true + default: auto + n_epochs: + description: | + The number of epochs to train the model for. An epoch refers to one full cycle + through the training dataset. + oneOf: + - type: string + enum: [auto] + - type: integer + minimum: 1 + maximum: 50 + default: auto + suffix: + description: | + A string of up to 18 characters that will be added to your fine-tuned model name. + + For example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. + type: string + minLength: 1 + maxLength: 40 + default: null nullable: true - metadata: - description: &metadata_description | - Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. - type: object - x-oaiTypeLabel: map + validation_file: + description: | + The ID of an uploaded file that contains validation data. + + If you provide this file, the data is used to generate validation + metrics periodically during fine-tuning. These metrics can be viewed in + the fine-tuning results file. + The same data should not be present in both train and validation files. + + Your dataset must be formatted as a JSONL file. You must upload your file with the purpose `fine-tune`. + + See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. + type: string nullable: true - temperature: - description: &run_temperature_description | - What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 + example: "file-abc123" + integrations: + type: array + description: A list of integrations to enable for your fine-tuning job. nullable: true - top_p: - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 + items: + type: object + required: + - type + - wandb + properties: + type: + description: | + The type of integration to enable. Currently, only "wandb" (Weights and Biases) is supported. + oneOf: + - type: string + enum: [wandb] + wandb: + type: object + description: | + The settings for your integration with Weights and Biases. This payload specifies the project that + metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags + to your run, and set a default entity (team, username, etc) to be associated with your run. + required: + - project + properties: + project: + description: | + The name of the project that the new run will be created under. + type: string + example: "my-wandb-project" + name: + description: | + A display name to set for the run. If not set, we will use the Job ID as the name. + nullable: true + type: string + entity: + description: | + The entity to use for the run. This allows you to set the team or username of the WandB user that you would + like associated with the run. If not set, the default entity for the registered WandB API key is used. + nullable: true + type: string + tags: + description: | + A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some + default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + type: array + items: + type: string + example: "custom-tag" + + seed: + description: | + The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases. + If a seed is not specified, one will be generated for you. + type: integer nullable: true - description: &run_top_p_description | - An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + minimum: 0 + maximum: 2147483647 + example: 42 + required: + - model + - training_file - We generally recommend altering this or temperature but not both. - response_format: - $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + ListFineTuningJobEventsResponse: + type: object + properties: + data: + type: array + items: + $ref: "#/components/schemas/FineTuningJobEvent" + object: + type: string + enum: [list] + required: + - object + - data + + ListFineTuningJobCheckpointsResponse: + type: object + properties: + data: + type: array + items: + $ref: "#/components/schemas/FineTuningJobCheckpoint" + object: + type: string + enum: [list] + first_id: + type: string + nullable: true + last_id: + type: string nullable: true + has_more: + type: boolean required: - - id - object - - created_at - - name - - description - - model - - instructions - - tools - - metadata - x-oaiMeta: - name: The assistant object - beta: true - example: *create_assistants_example + - data + - has_more - CreateAssistantRequest: + CreateEmbeddingRequest: type: object additionalProperties: false properties: + input: + description: | + Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. + example: "The quick brown fox jumped over the lazy dog" + oneOf: + - type: string + title: string + description: The string that will be turned into an embedding. + default: "" + example: "This is a test." + - type: array + title: array + description: The array of strings that will be turned into an embedding. + minItems: 1 + maxItems: 2048 + items: + type: string + default: "" + example: "['This is a test.']" + - type: array + title: array + description: The array of integers that will be turned into an embedding. + minItems: 1 + maxItems: 2048 + items: + type: integer + example: "[1212, 318, 257, 1332, 13]" + - type: array + title: array + description: The array of arrays containing integers that will be turned into an embedding. + minItems: 1 + maxItems: 2048 + items: + type: array + minItems: 1 + items: + type: integer + example: "[[1212, 318, 257, 1332, 13]]" + x-oaiExpandable: true model: description: *model_description - example: "gpt-4-turbo" + example: "text-embedding-3-small" anyOf: - type: string - type: string enum: [ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", + "text-embedding-ada-002", + "text-embedding-3-small", + "text-embedding-3-large", ] x-oaiTypeLabel: string - name: - description: *assistant_name_param_description - type: string - nullable: true - maxLength: 256 - description: - description: *assistant_description_param_description - type: string - nullable: true - maxLength: 512 - instructions: - description: *assistant_instructions_param_description + encoding_format: + description: "The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/)." + example: "float" + default: "float" type: string - nullable: true - maxLength: 256000 - tools: - description: *assistant_tools_param_description - default: [] + enum: ["float", "base64"] + dimensions: + description: | + The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. + type: integer + minimum: 1 + user: *end_user_param_configuration + required: + - model + - input + + CreateEmbeddingResponse: + type: object + properties: + data: type: array - maxItems: 128 + description: The list of embeddings generated by the model. items: - oneOf: - - $ref: "#/components/schemas/AssistantToolsCode" - - $ref: "#/components/schemas/AssistantToolsFileSearch" - - $ref: "#/components/schemas/AssistantToolsFunction" - x-oaiExpandable: true - tool_resources: + $ref: "#/components/schemas/Embedding" + model: + type: string + description: The name of the model used to generate the embedding. + object: + type: string + description: The object type, which is always "list". + enum: [list] + usage: type: object - description: | - A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + description: The usage information for the request. properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: | - A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: | - The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. - maxItems: 1 - items: - type: string - vector_stores: - type: array - description: | - A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant. - maxItems: 1 - items: - type: object - properties: - file_ids: - type: array - description: | - A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. - maxItems: 10000 - items: - type: string - chunking_strategy: - # Ideally we'd reuse the chunking strategy schema here, but it doesn't expand properly - type: object - description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. - oneOf: - - type: object - title: Auto Chunking Strategy - description: The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. - additionalProperties: false - properties: - type: - type: string - description: Always `auto`. - enum: ["auto"] - required: - - type - - type: object - title: Static Chunking Strategy - additionalProperties: false - properties: - type: - type: string - description: Always `static`. - enum: ["static"] - static: - type: object - additionalProperties: false - properties: - max_chunk_size_tokens: - type: integer - minimum: 100 - maximum: 4096 - description: The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. - chunk_overlap_tokens: - type: integer - description: | - The number of tokens that overlap between chunks. The default value is `400`. - - Note that the overlap must not exceed half of `max_chunk_size_tokens`. - required: - - max_chunk_size_tokens - - chunk_overlap_tokens - required: - - type - - static - x-oaiExpandable: true - metadata: - type: object - description: | - Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. - x-oaiTypeLabel: map - oneOf: - - required: [vector_store_ids] - - required: [vector_stores] - nullable: true - metadata: - description: *metadata_description - type: object - x-oaiTypeLabel: map - nullable: true - temperature: - description: &run_temperature_description | - What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - nullable: true - top_p: - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - nullable: true - description: &run_top_p_description | - An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. - response_format: - $ref: "#/components/schemas/AssistantsApiResponseFormatOption" - nullable: true + prompt_tokens: + type: integer + description: The number of tokens used by the prompt. + total_tokens: + type: integer + description: The total number of tokens used by the request. + required: + - prompt_tokens + - total_tokens required: + - object - model + - data + - usage - ModifyAssistantRequest: + CreateTranscriptionRequest: type: object additionalProperties: false properties: + file: + description: | + The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + type: string + x-oaiTypeLabel: file + format: binary model: - description: *model_description + description: | + ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available. + example: whisper-1 anyOf: - type: string - name: - description: *assistant_name_param_description + - type: string + enum: ["whisper-1"] + x-oaiTypeLabel: string + language: + description: | + The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will improve accuracy and latency. type: string - nullable: true - maxLength: 256 - description: - description: *assistant_description_param_description + prompt: + description: | + An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. type: string - nullable: true - maxLength: 512 - instructions: - description: *assistant_instructions_param_description + response_format: + description: | + The format of the transcript output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. type: string - nullable: true - maxLength: 256000 - tools: - description: *assistant_tools_param_description - default: [] + enum: + - json + - text + - srt + - verbose_json + - vtt + default: json + temperature: + description: | + The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. + type: number + default: 0 + timestamp_granularities[]: + description: | + The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. type: array - maxItems: 128 items: - oneOf: - - $ref: "#/components/schemas/AssistantToolsCode" - - $ref: "#/components/schemas/AssistantToolsFileSearch" - - $ref: "#/components/schemas/AssistantToolsFunction" - x-oaiExpandable: true - tool_resources: - type: object - description: | - A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. - properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: | - Overrides the list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: | - Overrides the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. - maxItems: 1 - items: - type: string - nullable: true - metadata: - description: *metadata_description - type: object - x-oaiTypeLabel: map - nullable: true - temperature: - description: *run_temperature_description - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - nullable: true - top_p: - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - nullable: true - description: &run_top_p_description | - An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. - response_format: - $ref: "#/components/schemas/AssistantsApiResponseFormatOption" - nullable: true + type: string + enum: + - word + - segment + default: [segment] + required: + - file + - model - DeleteAssistantResponse: + # Note: This does not currently support the non-default response format types. + CreateTranscriptionResponseJson: type: object + description: Represents a transcription response returned by model, based on the provided input. properties: - id: - type: string - deleted: - type: boolean - object: + text: type: string - enum: [assistant.deleted] + description: The transcribed text. required: - - id - - object - - deleted + - text + x-oaiMeta: + name: The transcription object (JSON) + group: audio + example: *basic_transcription_response_example - ListAssistantsResponse: + TranscriptionSegment: type: object properties: - object: + id: + type: integer + description: Unique identifier of the segment. + seek: + type: integer + description: Seek offset of the segment. + start: + type: number + format: float + description: Start time of the segment in seconds. + end: + type: number + format: float + description: End time of the segment in seconds. + text: type: string - example: "list" - data: + description: Text content of the segment. + tokens: type: array items: - $ref: "#/components/schemas/AssistantObject" - first_id: - type: string - example: "asst_abc123" - last_id: - type: string - example: "asst_abc456" - has_more: - type: boolean - example: false + type: integer + description: Array of token IDs for the text content. + temperature: + type: number + format: float + description: Temperature parameter used for generating the segment. + avg_logprob: + type: number + format: float + description: Average logprob of the segment. If the value is lower than -1, consider the logprobs failed. + compression_ratio: + type: number + format: float + description: Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed. + no_speech_prob: + type: number + format: float + description: Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent. required: - - object - - data - - first_id - - last_id - - has_more - x-oaiMeta: - name: List assistants response object - group: chat - example: *list_assistants_example + - id + - seek + - start + - end + - text + - tokens + - temperature + - avg_logprob + - compression_ratio + - no_speech_prob - AssistantToolsCode: + TranscriptionWord: type: object - title: Code interpreter tool properties: - type: + word: type: string - description: "The type of tool being defined: `code_interpreter`" - enum: ["code_interpreter"] - required: - - type + description: The text content of the word. + start: + type: number + format: float + description: Start time of the word in seconds. + end: + type: number + format: float + description: End time of the word in seconds. + required: [word, start, end] - AssistantToolsFileSearch: + CreateTranscriptionResponseVerboseJson: type: object - title: FileSearch tool + description: Represents a verbose json transcription response returned by model, based on the provided input. properties: - type: + language: type: string - description: "The type of tool being defined: `file_search`" - enum: ["file_search"] - file_search: - type: object - description: Overrides for the file search tool. - properties: - max_num_results: - type: integer - minimum: 1 - maximum: 50 - description: | - The maximum number of results the file search tool should output. The default is 20 for gpt-4* models and 5 for gpt-3.5-turbo. This number should be between 1 and 50 inclusive. - - Note that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](/docs/assistants/tools/file-search/number-of-chunks-returned) for more information. - required: - - type - - AssistantToolsFileSearchTypeOnly: - type: object - title: FileSearch tool - properties: - type: + description: The language of the input audio. + duration: type: string - description: "The type of tool being defined: `file_search`" - enum: ["file_search"] - required: - - type - - AssistantToolsFunction: - type: object - title: Function tool - properties: - type: + description: The duration of the input audio. + text: type: string - description: "The type of tool being defined: `function`" - enum: ["function"] - function: - $ref: "#/components/schemas/FunctionObject" - required: - - type - - function + description: The transcribed text. + words: + type: array + description: Extracted words and their corresponding timestamps. + items: + $ref: "#/components/schemas/TranscriptionWord" + segments: + type: array + description: Segments of the transcribed text and their corresponding details. + items: + $ref: "#/components/schemas/TranscriptionSegment" + required: [language, duration, text] + x-oaiMeta: + name: The transcription object (Verbose JSON) + group: audio + example: *verbose_transcription_response_example - TruncationObject: + CreateTranslationRequest: type: object - title: Thread Truncation Controls - description: Controls for how a thread will be truncated prior to the run. Use this to control the intial context window of the run. + additionalProperties: false properties: - type: + file: + description: | + The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. type: string - description: The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`. - enum: ["auto", "last_messages"] - last_messages: - type: integer - description: The number of most recent messages from the thread when constructing the context for the run. - minimum: 1 - nullable: true + x-oaiTypeLabel: file + format: binary + model: + description: | + ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available. + example: whisper-1 + anyOf: + - type: string + - type: string + enum: ["whisper-1"] + x-oaiTypeLabel: string + prompt: + description: | + An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English. + type: string + response_format: + description: | + The format of the transcript output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. + type: string + default: json + temperature: + description: | + The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. + type: number + default: 0 required: - - type + - file + - model - AssistantsApiToolChoiceOption: - description: | - Controls which (if any) tool is called by the model. - `none` means the model will not call any tools and instead generates a message. - `auto` is the default value and means the model can pick between generating a message or calling one or more tools. - `required` means the model must call one or more tools before responding to the user. - Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + # Note: This does not currently support the non-default response format types. + CreateTranslationResponseJson: + type: object + properties: + text: + type: string + required: + - text - oneOf: - - type: string - description: > - `none` means the model will not call any tools and instead generates a message. - `auto` means the model can pick between generating a message or calling one or more tools. - `required` means the model must call one or more tools before responding to the user. - enum: [none, auto, required] - - $ref: "#/components/schemas/AssistantsNamedToolChoice" - x-oaiExpandable: true + CreateTranslationResponseVerboseJson: + type: object + properties: + language: + type: string + description: The language of the output translation (always `english`). + duration: + type: string + description: The duration of the input audio. + text: + type: string + description: The translated text. + segments: + type: array + description: Segments of the translated text and their corresponding details. + items: + $ref: "#/components/schemas/TranscriptionSegment" + required: [language, duration, text] - AssistantsNamedToolChoice: + CreateSpeechRequest: type: object - description: Specifies a tool the model should use. Use to force the model to call a specific tool. + additionalProperties: false properties: - type: + model: + description: | + One of the available [TTS models](/docs/models/tts): `tts-1` or `tts-1-hd` + anyOf: + - type: string + - type: string + enum: ["tts-1", "tts-1-hd"] + x-oaiTypeLabel: string + input: type: string - enum: ["function", "code_interpreter", "file_search"] - description: The type of the tool. If type is `function`, the function name must be set - function: - type: object - properties: - name: - type: string - description: The name of the function to call. - required: - - name + description: The text to generate audio for. The maximum length is 4096 characters. + maxLength: 4096 + voice: + description: The voice to use when generating the audio. Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are available in the [Text to speech guide](/docs/guides/text-to-speech/voice-options). + type: string + enum: ["alloy", "echo", "fable", "onyx", "nova", "shimmer"] + response_format: + description: "The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`." + default: "mp3" + type: string + enum: ["mp3", "opus", "aac", "flac", "wav", "pcm"] + speed: + description: "The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default." + type: number + default: 1.0 + minimum: 0.25 + maximum: 4.0 required: - - type + - model + - input + - voice - RunObject: - type: object - title: A run on a thread - description: Represents an execution run on a [thread](/docs/api-reference/threads). + Model: + title: Model + description: Describes an OpenAI model offering that can be used with the API. properties: id: - description: The identifier, which can be referenced in API endpoints. type: string + description: The model identifier, which can be referenced in the API endpoints. + created: + type: integer + description: The Unix timestamp (in seconds) when the model was created. object: - description: The object type, which is always `thread.run`. type: string - enum: ["thread.run"] + description: The object type, which is always "model". + enum: [model] + owned_by: + type: string + description: The organization that owns the model. + required: + - id + - object + - created + - owned_by + x-oaiMeta: + name: The model object + example: *retrieve_model_response + + OpenAIFile: + title: OpenAIFile + description: The `File` object represents a document that has been uploaded to OpenAI. + properties: + id: + type: string + description: The file identifier, which can be referenced in the API endpoints. + bytes: + type: integer + description: The size of the file, in bytes. created_at: - description: The Unix timestamp (in seconds) for when the run was created. type: integer - thread_id: - description: The ID of the [thread](/docs/api-reference/threads) that was executed on as a part of this run. + description: The Unix timestamp (in seconds) for when the file was created. + filename: type: string - assistant_id: - description: The ID of the [assistant](/docs/api-reference/assistants) used for execution of this run. + description: The name of the file. + object: type: string - status: - description: The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, `incomplete`, or `expired`. + description: The object type, which is always `file`. + enum: ["file"] + purpose: type: string + description: The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results` and `vision`. enum: [ - "queued", - "in_progress", - "requires_action", - "cancelling", - "cancelled", - "failed", - "completed", - "incomplete", - "expired", + "assistants", + "assistants_output", + "batch", + "batch_output", + "fine-tune", + "fine-tune-results", + "vision", ] - required_action: - type: object - description: Details on the action required to continue the run. Will be `null` if no action is required. - nullable: true - properties: - type: - description: For now, this is always `submit_tool_outputs`. - type: string - enum: ["submit_tool_outputs"] - submit_tool_outputs: - type: object - description: Details on the tool outputs needed for this run to continue. - properties: - tool_calls: - type: array - description: A list of the relevant tool calls. - items: - $ref: "#/components/schemas/RunToolCallObject" - required: - - tool_calls - required: - - type - - submit_tool_outputs - last_error: - type: object - description: The last error associated with this run. Will be `null` if there are no errors. - nullable: true - properties: - code: - type: string - description: One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`. - enum: - ["server_error", "rate_limit_exceeded", "invalid_prompt"] - message: - type: string - description: A human-readable description of the error. - required: - - code - - message - expires_at: - description: The Unix timestamp (in seconds) for when the run will expire. - type: integer - nullable: true - started_at: - description: The Unix timestamp (in seconds) for when the run was started. - type: integer - nullable: true - cancelled_at: - description: The Unix timestamp (in seconds) for when the run was cancelled. - type: integer - nullable: true - failed_at: - description: The Unix timestamp (in seconds) for when the run failed. - type: integer - nullable: true - completed_at: - description: The Unix timestamp (in seconds) for when the run was completed. - type: integer - nullable: true - incomplete_details: - description: Details on why the run is incomplete. Will be `null` if the run is not incomplete. - type: object - nullable: true - properties: - reason: - description: The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run. - type: string - enum: ["max_completion_tokens", "max_prompt_tokens"] - model: - description: The model that the [assistant](/docs/api-reference/assistants) used for this run. + status: type: string - instructions: - description: The instructions that the [assistant](/docs/api-reference/assistants) used for this run. + deprecated: true + description: Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`. + enum: ["uploaded", "processed", "error"] + status_details: type: string - tools: - description: The list of tools that the [assistant](/docs/api-reference/assistants) used for this run. - default: [] - type: array - maxItems: 20 - items: - oneOf: - - $ref: "#/components/schemas/AssistantToolsCode" - - $ref: "#/components/schemas/AssistantToolsFileSearch" - - $ref: "#/components/schemas/AssistantToolsFunction" - x-oaiExpandable: true - metadata: - description: *metadata_description - type: object - x-oaiTypeLabel: map - nullable: true - usage: - $ref: "#/components/schemas/RunCompletionUsage" - temperature: - description: The sampling temperature used for this run. If not set, defaults to 1. - type: number - nullable: true - top_p: - description: The nucleus sampling value used for this run. If not set, defaults to 1. - type: number - nullable: true - max_prompt_tokens: - type: integer - nullable: true - description: | - The maximum number of prompt tokens specified to have been used over the course of the run. - minimum: 256 - max_completion_tokens: - type: integer - nullable: true - description: | - The maximum number of completion tokens specified to have been used over the course of the run. - minimum: 256 - truncation_strategy: - $ref: "#/components/schemas/TruncationObject" - nullable: true - tool_choice: - $ref: "#/components/schemas/AssistantsApiToolChoiceOption" - nullable: true - parallel_tool_calls: - $ref: "#/components/schemas/ParallelToolCalls" - response_format: - $ref: "#/components/schemas/AssistantsApiResponseFormatOption" - nullable: true + deprecated: true + description: Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`. required: - id - object + - bytes - created_at - - thread_id - - assistant_id + - filename + - purpose - status - - required_action - - last_error + x-oaiMeta: + name: The file object + example: | + { + "id": "file-abc123", + "object": "file", + "bytes": 120000, + "created_at": 1677610602, + "filename": "salesOverview.pdf", + "purpose": "assistants", + } + Upload: + type: object + title: Upload + description: | + The Upload object can accept byte chunks in the form of Parts. + properties: + id: + type: string + description: The Upload unique identifier, which can be referenced in API endpoints. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the Upload was created. + filename: + type: string + description: The name of the file to be uploaded. + bytes: + type: integer + description: The intended number of bytes to be uploaded. + purpose: + type: string + description: The intended purpose of the file. [Please refer here](/docs/api-reference/files/object#files/object-purpose) for acceptable values. + status: + type: string + description: The status of the Upload. + enum: ["pending", "completed", "cancelled", "expired"] + expires_at: + type: integer + description: The Unix timestamp (in seconds) for when the Upload was created. + object: + type: string + description: The object type, which is always "upload". + enum: [upload] + file: + $ref: "#/components/schemas/OpenAIFile" + nullable: true + description: The ready File object after the Upload is completed. + required: + - bytes + - created_at - expires_at - - started_at - - cancelled_at - - failed_at - - completed_at - - model - - instructions - - tools - - metadata - - usage - - incomplete_details - - max_prompt_tokens - - max_completion_tokens - - truncation_strategy - - tool_choice - - parallel_tool_calls - - response_format + - filename + - id + - purpose + - status + - step_number x-oaiMeta: - name: The run object - beta: true + name: The upload object example: | { - "id": "run_abc123", - "object": "thread.run", - "created_at": 1698107661, - "assistant_id": "asst_abc123", - "thread_id": "thread_abc123", + "id": "upload_abc123", + "object": "upload", + "bytes": 2147483648, + "created_at": 1719184911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", "status": "completed", - "started_at": 1699073476, - "expires_at": null, - "cancelled_at": null, - "failed_at": null, - "completed_at": 1699073498, - "last_error": null, - "model": "gpt-4-turbo", - "instructions": null, - "tools": [{"type": "file_search"}, {"type": "code_interpreter"}], - "metadata": {}, - "incomplete_details": null, - "usage": { - "prompt_tokens": 123, - "completion_tokens": 456, - "total_tokens": 579 - }, - "temperature": 1.0, - "top_p": 1.0, - "max_prompt_tokens": 1000, - "max_completion_tokens": 1000, - "truncation_strategy": { - "type": "auto", - "last_messages": null - }, - "response_format": "auto", - "tool_choice": "auto", - "parallel_tool_calls": true + "expires_at": 1719127296, + "file": { + "id": "file-xyz321", + "object": "file", + "bytes": 2147483648, + "created_at": 1719186911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + } } - CreateRunRequest: + UploadPart: type: object - additionalProperties: false + title: UploadPart + description: | + The upload Part represents a chunk of bytes we can add to an Upload object. properties: - assistant_id: - description: The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run. + id: type: string - model: - description: The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. - example: "gpt-4-turbo" - anyOf: - - type: string - - type: string - enum: - [ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ] - x-oaiTypeLabel: string - nullable: true - instructions: - description: Overrides the [instructions](/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. + description: The upload Part unique identifier, which can be referenced in API endpoints. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the Part was created. + upload_id: type: string - nullable: true - additional_instructions: - description: Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. + description: The ID of the Upload object that this Part was added to. + object: type: string - nullable: true - additional_messages: - description: Adds additional messages to the thread before creating the run. - type: array - items: - $ref: "#/components/schemas/CreateMessageRequest" - nullable: true - tools: - description: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. - nullable: true + description: The object type, which is always `upload.part`. + enum: ['upload.part'] + required: + - created_at + - id + - object + - upload_id + x-oaiMeta: + name: The upload part object + example: | + { + "id": "part_def456", + "object": "upload.part", + "created_at": 1719186911, + "upload_id": "upload_abc123" + } + Embedding: + type: object + description: | + Represents an embedding vector returned by embedding endpoint. + properties: + index: + type: integer + description: The index of the embedding in the list of embeddings. + embedding: type: array - maxItems: 20 + description: | + The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the [embedding guide](/docs/guides/embeddings). items: - oneOf: - - $ref: "#/components/schemas/AssistantToolsCode" - - $ref: "#/components/schemas/AssistantToolsFileSearch" - - $ref: "#/components/schemas/AssistantToolsFunction" - x-oaiExpandable: true - metadata: - description: *metadata_description - type: object - x-oaiTypeLabel: map - nullable: true - temperature: - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - nullable: true - description: *run_temperature_description - top_p: - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - nullable: true - description: &run_top_p_description | - An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. - stream: - type: boolean - nullable: true - description: | - If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. - max_prompt_tokens: - type: integer - nullable: true - description: | - The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. - minimum: 256 - max_completion_tokens: + type: number + object: + type: string + description: The object type, which is always "embedding". + enum: [embedding] + required: + - index + - object + - embedding + x-oaiMeta: + name: The embedding object + example: | + { + "object": "embedding", + "embedding": [ + 0.0023064255, + -0.009327292, + .... (1536 floats total for ada-002) + -0.0028842222, + ], + "index": 0 + } + + FineTuningJob: + type: object + title: FineTuningJob + description: | + The `fine_tuning.job` object represents a fine-tuning job that has been created through the API. + properties: + id: + type: string + description: The object identifier, which can be referenced in the API endpoints. + created_at: type: integer + description: The Unix timestamp (in seconds) for when the fine-tuning job was created. + error: + type: object nullable: true - description: | - The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. - minimum: 256 - truncation_strategy: - $ref: "#/components/schemas/TruncationObject" - nullable: true - tool_choice: - $ref: "#/components/schemas/AssistantsApiToolChoiceOption" + description: For fine-tuning jobs that have `failed`, this will contain more information on the cause of the failure. + properties: + code: + type: string + description: A machine-readable error code. + message: + type: string + description: A human-readable error message. + param: + type: string + description: The parameter that was invalid, usually `training_file` or `validation_file`. This field will be null if the failure was not parameter-specific. + nullable: true + required: + - code + - message + - param + fine_tuned_model: + type: string nullable: true - parallel_tool_calls: - $ref: "#/components/schemas/ParallelToolCalls" - response_format: - $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + description: The name of the fine-tuned model that is being created. The value will be null if the fine-tuning job is still running. + finished_at: + type: integer nullable: true - required: - - thread_id - - assistant_id - ListRunsResponse: - type: object - properties: + description: The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be null if the fine-tuning job is still running. + hyperparameters: + type: object + description: The hyperparameters used for the fine-tuning job. See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. + properties: + n_epochs: + oneOf: + - type: string + enum: [auto] + - type: integer + minimum: 1 + maximum: 50 + default: auto + description: + The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. + + "auto" decides the optimal number of epochs based on the size of the dataset. If setting the number manually, we support any number between 1 and 50 epochs. + required: + - n_epochs + model: + type: string + description: The base model that is being fine-tuned. object: type: string - example: "list" - data: + description: The object type, which is always "fine_tuning.job". + enum: [fine_tuning.job] + organization_id: + type: string + description: The organization that owns the fine-tuning job. + result_files: type: array + description: The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the [Files API](/docs/api-reference/files/retrieve-contents). items: - $ref: "#/components/schemas/RunObject" - first_id: + type: string + example: file-abc123 + status: type: string - example: "run_abc123" - last_id: + description: The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. + enum: + [ + "validating_files", + "queued", + "running", + "succeeded", + "failed", + "cancelled", + ] + trained_tokens: + type: integer + nullable: true + description: The total number of billable tokens processed by this fine-tuning job. The value will be null if the fine-tuning job is still running. + training_file: + type: string + description: The file ID used for training. You can retrieve the training data with the [Files API](/docs/api-reference/files/retrieve-contents). + validation_file: type: string - example: "run_abc456" - has_more: - type: boolean - example: false - required: - - object - - data - - first_id - - last_id - - has_more - ModifyRunRequest: - type: object - additionalProperties: false - properties: - metadata: - description: *metadata_description - type: object - x-oaiTypeLabel: map nullable: true - SubmitToolOutputsRunRequest: - type: object - additionalProperties: false - properties: - tool_outputs: - description: A list of tools for which the outputs are being submitted. + description: The file ID used for validation. You can retrieve the validation results with the [Files API](/docs/api-reference/files/retrieve-contents). + integrations: type: array + nullable: true + description: A list of integrations to enable for this fine-tuning job. + maxItems: 5 items: - type: object - properties: - tool_call_id: - type: string - description: The ID of the tool call in the `required_action` object within the run object the output is being submitted for. - output: - type: string - description: The output of the tool call to be submitted to continue the run. - stream: - type: boolean + oneOf: + - $ref: "#/components/schemas/FineTuningIntegration" + x-oaiExpandable: true + seed: + type: integer + description: The seed used for the fine-tuning job. + estimated_finish: + type: integer nullable: true - description: | - If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + description: The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The value will be null if the fine-tuning job is not running. required: - - tool_outputs + - created_at + - error + - finished_at + - fine_tuned_model + - hyperparameters + - id + - model + - object + - organization_id + - result_files + - status + - trained_tokens + - training_file + - validation_file + - seed + x-oaiMeta: + name: The fine-tuning job object + example: *fine_tuning_example - RunToolCallObject: + FineTuningIntegration: type: object - description: Tool call objects + title: Fine-Tuning Job Integration + required: + - type + - wandb properties: - id: - type: string - description: The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the [Submit tool outputs to run](/docs/api-reference/runs/submitToolOutputs) endpoint. type: type: string - description: The type of tool call the output is required for. For now, this is always `function`. - enum: ["function"] - function: + description: "The type of the integration being enabled for the fine-tuning job" + enum: ["wandb"] + wandb: type: object - description: The function definition. + description: | + The settings for your integration with Weights and Biases. This payload specifies the project that + metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags + to your run, and set a default entity (team, username, etc) to be associated with your run. + required: + - project properties: + project: + description: | + The name of the project that the new run will be created under. + type: string + example: "my-wandb-project" name: + description: | + A display name to set for the run. If not set, we will use the Job ID as the name. + nullable: true type: string - description: The name of the function. - arguments: + entity: + description: | + The entity to use for the run. This allows you to set the team or username of the WandB user that you would + like associated with the run. If not set, the default entity for the registered WandB API key is used. + nullable: true type: string - description: The arguments that the model expects you to pass to the function. - required: - - name - - arguments - required: - - id - - type - - function + tags: + description: | + A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some + default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + type: array + items: + type: string + example: "custom-tag" - CreateThreadAndRunRequest: + FineTuningJobEvent: type: object - additionalProperties: false + description: Fine-tuning job event object properties: - assistant_id: - description: The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run. - type: string - thread: - $ref: "#/components/schemas/CreateThreadRequest" - description: If no thread is provided, an empty thread will be created. - model: - description: The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. - example: "gpt-4-turbo" - anyOf: - - type: string - - type: string - enum: - [ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ] - x-oaiTypeLabel: string - nullable: true - instructions: - description: Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. + id: type: string - nullable: true - tools: - description: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. - nullable: true - type: array - maxItems: 20 - items: - oneOf: - - $ref: "#/components/schemas/AssistantToolsCode" - - $ref: "#/components/schemas/AssistantToolsFileSearch" - - $ref: "#/components/schemas/AssistantToolsFunction" - tool_resources: - type: object - description: | - A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. - properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: | - A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: | - The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. - maxItems: 1 - items: - type: string - nullable: true - metadata: - description: *metadata_description - type: object - x-oaiTypeLabel: map - nullable: true - temperature: - type: number - minimum: 0 - maximum: 2 - default: 1 - example: 1 - nullable: true - description: *run_temperature_description - top_p: - type: number - minimum: 0 - maximum: 1 - default: 1 - example: 1 - nullable: true - description: *run_top_p_description - stream: - type: boolean - nullable: true - description: | - If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. - max_prompt_tokens: - type: integer - nullable: true - description: | - The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. - minimum: 256 - max_completion_tokens: + created_at: type: integer - nullable: true - description: | - The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. - minimum: 256 - truncation_strategy: - $ref: "#/components/schemas/TruncationObject" - nullable: true - tool_choice: - $ref: "#/components/schemas/AssistantsApiToolChoiceOption" - nullable: true - parallel_tool_calls: - $ref: "#/components/schemas/ParallelToolCalls" - response_format: - $ref: "#/components/schemas/AssistantsApiResponseFormatOption" - nullable: true - required: - - thread_id - - assistant_id - - ThreadObject: - type: object - title: Thread - description: Represents a thread that contains [messages](/docs/api-reference/messages). - properties: - id: - description: The identifier, which can be referenced in API endpoints. + level: + type: string + enum: ["info", "warn", "error"] + message: type: string object: - description: The object type, which is always `thread`. type: string - enum: ["thread"] - created_at: - description: The Unix timestamp (in seconds) for when the thread was created. - type: integer - tool_resources: - type: object - description: | - A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. - properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: | - A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: | - The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. - maxItems: 1 - items: - type: string - nullable: true - metadata: - description: *metadata_description - type: object - x-oaiTypeLabel: map - nullable: true + enum: [fine_tuning.job.event] required: - id - object - created_at - - tool_resources - - metadata + - level + - message x-oaiMeta: - name: The thread object - beta: true + name: The fine-tuning job event object example: | { - "id": "thread_abc123", - "object": "thread", - "created_at": 1698107661, - "metadata": {} + "object": "fine_tuning.job.event", + "id": "ftevent-abc123" + "created_at": 1677610602, + "level": "info", + "message": "Created fine-tuning job" } - CreateThreadRequest: + FineTuningJobCheckpoint: type: object - additionalProperties: false + title: FineTuningJobCheckpoint + description: | + The `fine_tuning.job.checkpoint` object represents a model checkpoint for a fine-tuning job that is ready to use. properties: - messages: - description: A list of [messages](/docs/api-reference/messages) to start the thread with. - type: array - items: - $ref: "#/components/schemas/CreateMessageRequest" - tool_resources: + id: + type: string + description: The checkpoint identifier, which can be referenced in the API endpoints. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the checkpoint was created. + fine_tuned_model_checkpoint: + type: string + description: The name of the fine-tuned checkpoint model that is created. + step_number: + type: integer + description: The step number that the checkpoint was created at. + metrics: type: object - description: | - A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + description: Metrics at the step number during the fine-tuning job. properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: | - A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: | - The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. - maxItems: 1 - items: - type: string - vector_stores: - type: array - description: | - A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread. - maxItems: 1 - items: - type: object - properties: - file_ids: - type: array - description: | - A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. - maxItems: 10000 - items: - type: string - chunking_strategy: - # Ideally we'd reuse the chunking strategy schema here, but it doesn't expand properly - type: object - description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. - oneOf: - - type: object - title: Auto Chunking Strategy - description: The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. - additionalProperties: false - properties: - type: - type: string - description: Always `auto`. - enum: ["auto"] - required: - - type - - type: object - title: Static Chunking Strategy - additionalProperties: false - properties: - type: - type: string - description: Always `static`. - enum: ["static"] - static: - type: object - additionalProperties: false - properties: - max_chunk_size_tokens: - type: integer - minimum: 100 - maximum: 4096 - description: The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. - chunk_overlap_tokens: - type: integer - description: | - The number of tokens that overlap between chunks. The default value is `400`. - - Note that the overlap must not exceed half of `max_chunk_size_tokens`. - required: - - max_chunk_size_tokens - - chunk_overlap_tokens - required: - - type - - static - x-oaiExpandable: true - metadata: - type: object - description: | - Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. - x-oaiTypeLabel: map - x-oaiExpandable: true - oneOf: - - required: [vector_store_ids] - - required: [vector_stores] - nullable: true - metadata: - description: *metadata_description - type: object - x-oaiTypeLabel: map - nullable: true - - ModifyThreadRequest: - type: object - additionalProperties: false - properties: - tool_resources: - type: object - description: | - A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. - properties: - code_interpreter: - type: object - properties: - file_ids: - type: array - description: | - A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. - default: [] - maxItems: 20 - items: - type: string - file_search: - type: object - properties: - vector_store_ids: - type: array - description: | - The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. - maxItems: 1 - items: - type: string - nullable: true - metadata: - description: *metadata_description - type: object - x-oaiTypeLabel: map - nullable: true - - DeleteThreadResponse: - type: object - properties: - id: + step: + type: number + train_loss: + type: number + train_mean_token_accuracy: + type: number + valid_loss: + type: number + valid_mean_token_accuracy: + type: number + full_valid_loss: + type: number + full_valid_mean_token_accuracy: + type: number + fine_tuning_job_id: type: string - deleted: - type: boolean + description: The name of the fine-tuning job that this checkpoint was created from. object: type: string - enum: [thread.deleted] + description: The object type, which is always "fine_tuning.job.checkpoint". + enum: [fine_tuning.job.checkpoint] required: + - created_at + - fine_tuning_job_id + - fine_tuned_model_checkpoint - id + - metrics - object - - deleted + - step_number + x-oaiMeta: + name: The fine-tuning job checkpoint object + example: | + { + "object": "fine_tuning.job.checkpoint", + "id": "ftckpt_qtZ5Gyk4BLq1SfLFWp3RtO3P", + "created_at": 1712211699, + "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom_suffix:9ABel2dg:ckpt-step-88", + "fine_tuning_job_id": "ftjob-fpbNQ3H1GrMehXRf8cO97xTN", + "metrics": { + "step": 88, + "train_loss": 0.478, + "train_mean_token_accuracy": 0.924, + "valid_loss": 10.112, + "valid_mean_token_accuracy": 0.145, + "full_valid_loss": 0.567, + "full_valid_mean_token_accuracy": 0.944 + }, + "step_number": 88 + } - ListThreadsResponse: + FinetuneChatRequestInput: + type: object + description: The per-line training example of a fine-tuning input file for chat models properties: - object: - type: string - example: "list" - data: + messages: type: array + minItems: 1 items: - $ref: "#/components/schemas/ThreadObject" - first_id: - type: string - example: "asst_abc123" - last_id: - type: string - example: "asst_abc456" - has_more: - type: boolean - example: false - required: - - object - - data - - first_id - - last_id - - has_more - - MessageObject: - type: object - title: The message object - description: Represents a message within a [thread](/docs/api-reference/threads). - properties: - id: - description: The identifier, which can be referenced in API endpoints. - type: string - object: - description: The object type, which is always `thread.message`. - type: string - enum: ["thread.message"] - created_at: - description: The Unix timestamp (in seconds) for when the message was created. - type: integer - thread_id: - description: The [thread](/docs/api-reference/threads) ID that this message belongs to. - type: string - status: - description: The status of the message, which can be either `in_progress`, `incomplete`, or `completed`. - type: string - enum: ["in_progress", "incomplete", "completed"] - incomplete_details: - description: On an incomplete message, details about why the message is incomplete. - type: object - properties: - reason: - type: string - description: The reason the message is incomplete. - enum: - [ - "content_filter", - "max_tokens", - "run_cancelled", - "run_expired", - "run_failed", - ] - nullable: true - required: - - reason - completed_at: - description: The Unix timestamp (in seconds) for when the message was completed. - type: integer - nullable: true - incomplete_at: - description: The Unix timestamp (in seconds) for when the message was marked as incomplete. - type: integer - nullable: true - role: - description: The entity that produced the message. One of `user` or `assistant`. - type: string - enum: ["user", "assistant"] - content: - description: The content of the message in array of text and/or images. + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestSystemMessage" + - $ref: "#/components/schemas/ChatCompletionRequestUserMessage" + - $ref: "#/components/schemas/FineTuneChatCompletionRequestAssistantMessage" + - $ref: "#/components/schemas/ChatCompletionRequestToolMessage" + - $ref: "#/components/schemas/ChatCompletionRequestFunctionMessage" + x-oaiExpandable: true + tools: type: array + description: A list of tools the model may generate JSON inputs for. items: - oneOf: - - $ref: "#/components/schemas/MessageContentImageFileObject" - - $ref: "#/components/schemas/MessageContentImageUrlObject" - - $ref: "#/components/schemas/MessageContentTextObject" - x-oaiExpandable: true - assistant_id: - description: If applicable, the ID of the [assistant](/docs/api-reference/assistants) that authored this message. - type: string - nullable: true - run_id: - description: The ID of the [run](/docs/api-reference/runs) associated with the creation of this message. Value is `null` when messages are created manually using the create message or create thread endpoints. - type: string - nullable: true - attachments: + $ref: "#/components/schemas/ChatCompletionTool" + parallel_tool_calls: + $ref: "#/components/schemas/ParallelToolCalls" + functions: + deprecated: true + description: + A list of functions the model may generate JSON inputs for. type: array + minItems: 1 + maxItems: 128 items: - type: object - properties: - file_id: - type: string - description: The ID of the file to attach to the message. - tools: - description: The tools to add this file to. - type: array - items: - oneOf: - - $ref: "#/components/schemas/AssistantToolsCode" - - $ref: "#/components/schemas/AssistantToolsFileSearchTypeOnly" - x-oaiExpandable: true - description: A list of files attached to the message, and the tools they were added to. - nullable: true - metadata: - description: *metadata_description - type: object - x-oaiTypeLabel: map - nullable: true - required: - - id - - object - - created_at - - thread_id - - status - - incomplete_details - - completed_at - - incomplete_at - - role - - content - - assistant_id - - run_id - - attachments - - metadata + $ref: "#/components/schemas/ChatCompletionFunctions" x-oaiMeta: - name: The message object - beta: true + name: Training format for chat models example: | - { - "id": "msg_abc123", - "object": "thread.message", - "created_at": 1698983503, - "thread_id": "thread_abc123", - "role": "assistant", - "content": [ - { - "type": "text", - "text": { - "value": "Hi! How can I help you today?", - "annotations": [] + { + "messages": [ + { "role": "user", "content": "What is the weather in San Francisco?" }, + { + "role": "assistant", + "tool_calls": [ + { + "id": "call_id", + "type": "function", + "function": { + "name": "get_current_weather", + "arguments": "{\"location\": \"San Francisco, USA\", \"format\": \"celsius\"}" + } + } + ] + } + ], + "parallel_tool_calls": false, + "tools": [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and country, eg. San Francisco, USA" + }, + "format": { "type": "string", "enum": ["celsius", "fahrenheit"] } + }, + "required": ["location", "format"] } } - ], - "assistant_id": "asst_abc123", - "run_id": "run_abc123", - "attachments": [], - "metadata": {} - } - - MessageDeltaObject: + } + ] + } + + FinetuneCompletionRequestInput: type: object - title: Message delta object - description: | - Represents a message delta i.e. any changed fields on a message during streaming. + description: The per-line training example of a fine-tuning input file for completions models properties: - id: - description: The identifier of the message, which can be referenced in API endpoints. + prompt: type: string - object: - description: The object type, which is always `thread.message.delta`. + description: The input prompt for this training example. + completion: type: string - enum: ["thread.message.delta"] - delta: - description: The delta containing the fields that have changed on the Message. - type: object - properties: - role: - description: The entity that produced the message. One of `user` or `assistant`. - type: string - enum: ["user", "assistant"] - content: - description: The content of the message in array of text and/or images. - type: array - items: - oneOf: - - $ref: "#/components/schemas/MessageDeltaContentImageFileObject" - - $ref: "#/components/schemas/MessageDeltaContentTextObject" - - $ref: "#/components/schemas/MessageDeltaContentImageUrlObject" - x-oaiExpandable: true - required: - - id - - object - - delta + description: The desired completion for this training example. x-oaiMeta: - name: The message delta object - beta: true + name: Training format for completions models example: | { - "id": "msg_123", - "object": "thread.message.delta", - "delta": { - "content": [ - { - "index": 0, - "type": "text", - "text": { "value": "Hello", "annotations": [] } - } - ] - } + "prompt": "What is the answer to 2+2", + "completion": "4" } - CreateMessageRequest: - type: object - additionalProperties: false - required: - - role - - content - properties: - role: - type: string - enum: ["user", "assistant"] - description: | - The role of the entity that is creating the message. Allowed values include: - - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. - - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation. - content: - oneOf: - - type: string - description: The text contents of the message. - title: Text content - - type: array - description: An array of content parts with a defined type, each can be of type `text` or images can be passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible models](/docs/models/overview). - title: Array of content parts - items: - oneOf: - - $ref: "#/components/schemas/MessageContentImageFileObject" - - $ref: "#/components/schemas/MessageContentImageUrlObject" - - $ref: "#/components/schemas/MessageRequestContentTextObject" - x-oaiExpandable: true - minItems: 1 - x-oaiExpandable: true - attachments: - type: array - items: - type: object - properties: - file_id: - type: string - description: The ID of the file to attach to the message. - tools: - description: The tools to add this file to. - type: array - items: - oneOf: - - $ref: "#/components/schemas/AssistantToolsCode" - - $ref: "#/components/schemas/AssistantToolsFileSearchTypeOnly" - x-oaiExpandable: true - description: A list of files attached to the message, and the tools they should be added to. - required: - - file_id - - tools - nullable: true - metadata: - description: *metadata_description - type: object - x-oaiTypeLabel: map - nullable: true - - ModifyMessageRequest: + CompletionUsage: type: object - additionalProperties: false + description: Usage statistics for the completion request. properties: - metadata: - description: *metadata_description - type: object - x-oaiTypeLabel: map - nullable: true + completion_tokens: + type: integer + description: Number of tokens in the generated completion. + prompt_tokens: + type: integer + description: Number of tokens in the prompt. + total_tokens: + type: integer + description: Total number of tokens used in the request (prompt + completion). + required: + - prompt_tokens + - completion_tokens + - total_tokens - DeleteMessageResponse: + RunCompletionUsage: type: object + description: Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). properties: - id: - type: string - deleted: - type: boolean - object: - type: string - enum: [thread.message.deleted] - required: - - id - - object - - deleted - - ListMessagesResponse: - properties: - object: - type: string - example: "list" - data: - type: array - items: - $ref: "#/components/schemas/MessageObject" - first_id: - type: string - example: "msg_abc123" - last_id: - type: string - example: "msg_abc123" - has_more: - type: boolean - example: false + completion_tokens: + type: integer + description: Number of completion tokens used over the course of the run. + prompt_tokens: + type: integer + description: Number of prompt tokens used over the course of the run. + total_tokens: + type: integer + description: Total number of tokens used (prompt + completion). required: - - object - - data - - first_id - - last_id - - has_more + - prompt_tokens + - completion_tokens + - total_tokens + nullable: true - MessageContentImageFileObject: - title: Image file + RunStepCompletionUsage: type: object - description: References an image [File](/docs/api-reference/files) in the content of a message. + description: Usage statistics related to the run step. This value will be `null` while the run step's status is `in_progress`. properties: - type: - description: Always `image_file`. - type: string - enum: ["image_file"] - image_file: - type: object - properties: - file_id: - description: The [File](/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content. - type: string - detail: - type: string - description: Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`. - enum: ["auto", "low", "high"] - default: "auto" - required: - - file_id + completion_tokens: + type: integer + description: Number of completion tokens used over the course of the run step. + prompt_tokens: + type: integer + description: Number of prompt tokens used over the course of the run step. + total_tokens: + type: integer + description: Total number of tokens used (prompt + completion). required: - - type - - image_file + - prompt_tokens + - completion_tokens + - total_tokens + nullable: true - MessageDeltaContentImageFileObject: - title: Image file + AssistantsApiResponseFormatOption: + description: | + Specifies the format that the model must output. Compatible with [GPT-4o](/docs/models/gpt-4o), [GPT-4 Turbo](/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which guarantees the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/docs/guides/structured-outputs). + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. + oneOf: + - type: string + description: > + `auto` is the default value + enum: [auto] + - $ref: '#/components/schemas/ResponseFormatText' + - $ref: '#/components/schemas/ResponseFormatJsonObject' + - $ref: '#/components/schemas/ResponseFormatJsonSchema' + x-oaiExpandable: true + + AssistantObject: type: object - description: References an image [File](/docs/api-reference/files) in the content of a message. + title: Assistant + description: Represents an `assistant` that can call the model and use tools. properties: - index: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `assistant`. + type: string + enum: [assistant] + created_at: + description: The Unix timestamp (in seconds) for when the assistant was created. type: integer - description: The index of the content part in the message. - type: - description: Always `image_file`. + name: + description: &assistant_name_param_description | + The name of the assistant. The maximum length is 256 characters. type: string - enum: ["image_file"] - image_file: - type: object - properties: - file_id: - description: The [File](/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content. - type: string - detail: - type: string - description: Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`. - enum: ["auto", "low", "high"] - default: "auto" - required: - - index - - type - - MessageContentImageUrlObject: - title: Image URL - type: object - description: References an image URL in the content of a message. - properties: - type: + maxLength: 256 + nullable: true + description: + description: &assistant_description_param_description | + The description of the assistant. The maximum length is 512 characters. type: string - enum: ["image_url"] - description: The type of the content part. - image_url: + maxLength: 512 + nullable: true + model: + description: *model_description + type: string + instructions: + description: &assistant_instructions_param_description | + The system instructions that the assistant uses. The maximum length is 256,000 characters. + type: string + maxLength: 256000 + nullable: true + tools: + description: &assistant_tools_param_description | + A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`. + default: [] + type: array + maxItems: 128 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + tool_resources: type: object + description: | + A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: - url: - type: string - description: "The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp." - format: uri - detail: - type: string - description: Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto` - enum: ["auto", "low", "high"] - default: "auto" - required: - - url + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: string + nullable: true + metadata: + description: &metadata_description | + Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + type: object + x-oaiTypeLabel: map + nullable: true + temperature: + description: &run_temperature_description | + What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: &run_top_p_description | + An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true required: - - type - - image_url + - id + - object + - created_at + - name + - description + - model + - instructions + - tools + - metadata + x-oaiMeta: + name: The assistant object + beta: true + example: *create_assistants_example - MessageDeltaContentImageUrlObject: - title: Image URL + CreateAssistantRequest: type: object - description: References an image URL in the content of a message. + additionalProperties: false properties: - index: - type: integer - description: The index of the content part in the message. - type: - description: Always `image_url`. + model: + description: *model_description + example: "gpt-4o" + anyOf: + - type: string + - type: string + enum: + [ + "gpt-4o", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ] + x-oaiTypeLabel: string + name: + description: *assistant_name_param_description type: string - enum: ["image_url"] - image_url: - type: object - properties: - url: - description: "The URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp." - type: string - detail: - type: string - description: Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. - enum: ["auto", "low", "high"] - default: "auto" - required: - - index - - type - - MessageContentTextObject: - title: Text - type: object - description: The text content that is part of a message. - properties: - type: - description: Always `text`. + nullable: true + maxLength: 256 + description: + description: *assistant_description_param_description type: string - enum: ["text"] - text: + nullable: true + maxLength: 512 + instructions: + description: *assistant_instructions_param_description + type: string + nullable: true + maxLength: 256000 + tools: + description: *assistant_tools_param_description + default: [] + type: array + maxItems: 128 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + tool_resources: type: object + description: | + A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: - value: - description: The data that makes up the text. - type: string - annotations: - type: array - items: - oneOf: - - $ref: "#/components/schemas/MessageContentTextAnnotationsFileCitationObject" - - $ref: "#/components/schemas/MessageContentTextAnnotationsFilePathObject" - x-oaiExpandable: true - required: - - value - - annotations + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: string + vector_stores: + type: array + description: | + A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + maxItems: 10000 + items: + type: string + chunking_strategy: + # Ideally we'd reuse the chunking strategy schema here, but it doesn't expand properly + type: object + description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + oneOf: + - type: object + title: Auto Chunking Strategy + description: The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. + additionalProperties: false + properties: + type: + type: string + description: Always `auto`. + enum: ["auto"] + required: + - type + - type: object + title: Static Chunking Strategy + additionalProperties: false + properties: + type: + type: string + description: Always `static`. + enum: ["static"] + static: + type: object + additionalProperties: false + properties: + max_chunk_size_tokens: + type: integer + minimum: 100 + maximum: 4096 + description: The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. + chunk_overlap_tokens: + type: integer + description: | + The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + required: + - max_chunk_size_tokens + - chunk_overlap_tokens + required: + - type + - static + x-oaiExpandable: true + metadata: + type: object + description: | + Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + x-oaiTypeLabel: map + oneOf: + - required: [vector_store_ids] + - required: [vector_stores] + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + temperature: + description: *run_temperature_description + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: *run_top_p_description + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true required: - - type - - text + - model - MessageRequestContentTextObject: - title: Text + ModifyAssistantRequest: type: object - description: The text content that is part of a message. + additionalProperties: false properties: - type: - description: Always `text`. - type: string - enum: ["text"] - text: + model: + description: *model_description + anyOf: + - type: string + name: + description: *assistant_name_param_description type: string - description: Text content to be sent to the model - required: - - type - - text - - MessageContentTextAnnotationsFileCitationObject: - title: File citation - type: object - description: A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the "file_search" tool to search files. - properties: - type: - description: Always `file_citation`. + nullable: true + maxLength: 256 + description: + description: *assistant_description_param_description type: string - enum: ["file_citation"] - text: - description: The text in the message content that needs to be replaced. + nullable: true + maxLength: 512 + instructions: + description: *assistant_instructions_param_description type: string - file_citation: + nullable: true + maxLength: 256000 + tools: + description: *assistant_tools_param_description + default: [] + type: array + maxItems: 128 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + tool_resources: type: object + description: | + A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: - file_id: - description: The ID of the specific File the citation is from. - type: string - required: - - file_id - start_index: - type: integer + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + Overrides the list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + Overrides the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: string + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + temperature: + description: *run_temperature_description + type: number minimum: 0 - end_index: - type: integer + maximum: 2 + default: 1 + example: 1 + nullable: true + top_p: + type: number minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: *run_top_p_description + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true + + DeleteAssistantResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: [assistant.deleted] required: - - type - - text - - file_citation - - start_index - - end_index + - id + - object + - deleted - MessageContentTextAnnotationsFilePathObject: - title: File path + ListAssistantsResponse: type: object - description: A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file. properties: - type: - description: Always `file_path`. + object: type: string - enum: ["file_path"] - text: - description: The text in the message content that needs to be replaced. + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/AssistantObject" + first_id: type: string - file_path: - type: object - properties: - file_id: - description: The ID of the file that was generated. - type: string - required: - - file_id - start_index: - type: integer - minimum: 0 - end_index: - type: integer - minimum: 0 + example: "asst_abc123" + last_id: + type: string + example: "asst_abc456" + has_more: + type: boolean + example: false required: - - type - - text - - file_path - - start_index - - end_index + - object + - data + - first_id + - last_id + - has_more + x-oaiMeta: + name: List assistants response object + group: chat + example: *list_assistants_example - MessageDeltaContentTextObject: - title: Text + AssistantToolsCode: type: object - description: The text content that is part of a message. + title: Code interpreter tool properties: - index: - type: integer - description: The index of the content part in the message. type: - description: Always `text`. type: string - enum: ["text"] - text: - type: object - properties: - value: - description: The data that makes up the text. - type: string - annotations: - type: array - items: - oneOf: - - $ref: "#/components/schemas/MessageDeltaContentTextAnnotationsFileCitationObject" - - $ref: "#/components/schemas/MessageDeltaContentTextAnnotationsFilePathObject" - x-oaiExpandable: true + description: "The type of tool being defined: `code_interpreter`" + enum: ["code_interpreter"] required: - - index - type - MessageDeltaContentTextAnnotationsFileCitationObject: - title: File citation + AssistantToolsFileSearch: type: object - description: A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the "file_search" tool to search files. + title: FileSearch tool properties: - index: - type: integer - description: The index of the annotation in the text content part. type: - description: Always `file_citation`. - type: string - enum: ["file_citation"] - text: - description: The text in the message content that needs to be replaced. type: string - file_citation: + description: "The type of tool being defined: `file_search`" + enum: ["file_search"] + file_search: type: object + description: Overrides for the file search tool. properties: - file_id: - description: The ID of the specific File the citation is from. - type: string - quote: - description: The specific quote in the file. - type: string - start_index: - type: integer - minimum: 0 - end_index: - type: integer - minimum: 0 + max_num_results: + type: integer + minimum: 1 + maximum: 50 + description: | + The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive. + + Note that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](/docs/assistants/tools/file-search/number-of-chunks-returned) for more information. required: - - index - type - MessageDeltaContentTextAnnotationsFilePathObject: - title: File path + AssistantToolsFileSearchTypeOnly: type: object - description: A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file. + title: FileSearch tool properties: - index: - type: integer - description: The index of the annotation in the text content part. type: - description: Always `file_path`. type: string - enum: ["file_path"] - text: - description: The text in the message content that needs to be replaced. + description: "The type of tool being defined: `file_search`" + enum: ["file_search"] + required: + - type + + AssistantToolsFunction: + type: object + title: Function tool + properties: + type: type: string - file_path: - type: object - properties: - file_id: - description: The ID of the file that was generated. - type: string - start_index: - type: integer - minimum: 0 - end_index: - type: integer - minimum: 0 + description: "The type of tool being defined: `function`" + enum: ["function"] + function: + $ref: "#/components/schemas/FunctionObject" required: - - index - type + - function - RunStepObject: + TruncationObject: type: object - title: Run steps - description: | - Represents a step in execution of a run. + title: Thread Truncation Controls + description: Controls for how a thread will be truncated prior to the run. Use this to control the intial context window of the run. properties: - id: - description: The identifier of the run step, which can be referenced in API endpoints. + type: type: string - object: - description: The object type, which is always `thread.run.step`. + description: The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`. + enum: ["auto", "last_messages"] + last_messages: + type: integer + description: The number of most recent messages from the thread when constructing the context for the run. + minimum: 1 + nullable: true + required: + - type + + AssistantsApiToolChoiceOption: + description: | + Controls which (if any) tool is called by the model. + `none` means the model will not call any tools and instead generates a message. + `auto` is the default value and means the model can pick between generating a message or calling one or more tools. + `required` means the model must call one or more tools before responding to the user. + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + + oneOf: + - type: string + description: > + `none` means the model will not call any tools and instead generates a message. + `auto` means the model can pick between generating a message or calling one or more tools. + `required` means the model must call one or more tools before responding to the user. + enum: [none, auto, required] + - $ref: "#/components/schemas/AssistantsNamedToolChoice" + x-oaiExpandable: true + + AssistantsNamedToolChoice: + type: object + description: Specifies a tool the model should use. Use to force the model to call a specific tool. + properties: + type: type: string - enum: ["thread.run.step"] + enum: ["function", "code_interpreter", "file_search"] + description: The type of the tool. If type is `function`, the function name must be set + function: + type: object + properties: + name: + type: string + description: The name of the function to call. + required: + - name + required: + - type + + RunObject: + type: object + title: A run on a thread + description: Represents an execution run on a [thread](/docs/api-reference/threads). + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread.run`. + type: string + enum: ["thread.run"] created_at: - description: The Unix timestamp (in seconds) for when the run step was created. + description: The Unix timestamp (in seconds) for when the run was created. type: integer - assistant_id: - description: The ID of the [assistant](/docs/api-reference/assistants) associated with the run step. - type: string thread_id: - description: The ID of the [thread](/docs/api-reference/threads) that was run. - type: string - run_id: - description: The ID of the [run](/docs/api-reference/runs) that this run step is a part of. + description: The ID of the [thread](/docs/api-reference/threads) that was executed on as a part of this run. type: string - type: - description: The type of run step, which can be either `message_creation` or `tool_calls`. + assistant_id: + description: The ID of the [assistant](/docs/api-reference/assistants) used for execution of this run. type: string - enum: ["message_creation", "tool_calls"] status: - description: The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`. + description: The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, `incomplete`, or `expired`. type: string - enum: ["in_progress", "cancelled", "failed", "completed", "expired"] - step_details: + enum: + [ + "queued", + "in_progress", + "requires_action", + "cancelling", + "cancelled", + "failed", + "completed", + "incomplete", + "expired", + ] + required_action: type: object - description: The details of the run step. - oneOf: - - $ref: "#/components/schemas/RunStepDetailsMessageCreationObject" - - $ref: "#/components/schemas/RunStepDetailsToolCallsObject" - x-oaiExpandable: true + description: Details on the action required to continue the run. Will be `null` if no action is required. + nullable: true + properties: + type: + description: For now, this is always `submit_tool_outputs`. + type: string + enum: ["submit_tool_outputs"] + submit_tool_outputs: + type: object + description: Details on the tool outputs needed for this run to continue. + properties: + tool_calls: + type: array + description: A list of the relevant tool calls. + items: + $ref: "#/components/schemas/RunToolCallObject" + required: + - tool_calls + required: + - type + - submit_tool_outputs last_error: type: object - description: The last error associated with this run step. Will be `null` if there are no errors. + description: The last error associated with this run. Will be `null` if there are no errors. nullable: true properties: code: type: string - description: One of `server_error` or `rate_limit_exceeded`. - enum: ["server_error", "rate_limit_exceeded"] + description: One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`. + enum: + ["server_error", "rate_limit_exceeded", "invalid_prompt"] message: type: string description: A human-readable description of the error. required: - code - message - expired_at: - description: The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired. + expires_at: + description: The Unix timestamp (in seconds) for when the run will expire. + type: integer + nullable: true + started_at: + description: The Unix timestamp (in seconds) for when the run was started. type: integer nullable: true cancelled_at: - description: The Unix timestamp (in seconds) for when the run step was cancelled. + description: The Unix timestamp (in seconds) for when the run was cancelled. type: integer nullable: true failed_at: - description: The Unix timestamp (in seconds) for when the run step failed. + description: The Unix timestamp (in seconds) for when the run failed. type: integer nullable: true completed_at: - description: The Unix timestamp (in seconds) for when the run step completed. + description: The Unix timestamp (in seconds) for when the run was completed. type: integer nullable: true + incomplete_details: + description: Details on why the run is incomplete. Will be `null` if the run is not incomplete. + type: object + nullable: true + properties: + reason: + description: The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run. + type: string + enum: ["max_completion_tokens", "max_prompt_tokens"] + model: + description: The model that the [assistant](/docs/api-reference/assistants) used for this run. + type: string + instructions: + description: The instructions that the [assistant](/docs/api-reference/assistants) used for this run. + type: string + tools: + description: The list of tools that the [assistant](/docs/api-reference/assistants) used for this run. + default: [] + type: array + maxItems: 20 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true metadata: description: *metadata_description type: object x-oaiTypeLabel: map nullable: true usage: - $ref: "#/components/schemas/RunStepCompletionUsage" + $ref: "#/components/schemas/RunCompletionUsage" + temperature: + description: The sampling temperature used for this run. If not set, defaults to 1. + type: number + nullable: true + top_p: + description: The nucleus sampling value used for this run. If not set, defaults to 1. + type: number + nullable: true + max_prompt_tokens: + type: integer + nullable: true + description: | + The maximum number of prompt tokens specified to have been used over the course of the run. + minimum: 256 + max_completion_tokens: + type: integer + nullable: true + description: | + The maximum number of completion tokens specified to have been used over the course of the run. + minimum: 256 + truncation_strategy: + $ref: "#/components/schemas/TruncationObject" + nullable: true + tool_choice: + $ref: "#/components/schemas/AssistantsApiToolChoiceOption" + nullable: true + parallel_tool_calls: + $ref: "#/components/schemas/ParallelToolCalls" + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true required: - id - object - created_at - - assistant_id - thread_id - - run_id - - type + - assistant_id - status - - step_details + - required_action - last_error - - expired_at + - expires_at + - started_at - cancelled_at - failed_at - completed_at + - model + - instructions + - tools - metadata - usage + - incomplete_details + - max_prompt_tokens + - max_completion_tokens + - truncation_strategy + - tool_choice + - parallel_tool_calls + - response_format x-oaiMeta: - name: The run step object - beta: true - example: *run_step_object_example - - RunStepDeltaObject: - type: object - title: Run step delta object - description: | - Represents a run step delta i.e. any changed fields on a run step during streaming. - properties: - id: - description: The identifier of the run step, which can be referenced in API endpoints. - type: string - object: - description: The object type, which is always `thread.run.step.delta`. - type: string - enum: ["thread.run.step.delta"] - delta: - description: The delta containing the fields that have changed on the run step. - type: object - properties: - step_details: - type: object - description: The details of the run step. - oneOf: - - $ref: "#/components/schemas/RunStepDeltaStepDetailsMessageCreationObject" - - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsObject" - x-oaiExpandable: true - required: - - id - - object - - delta - x-oaiMeta: - name: The run step delta object + name: The run object beta: true example: | { - "id": "step_123", - "object": "thread.run.step.delta", - "delta": { - "step_details": { - "type": "tool_calls", - "tool_calls": [ - { - "index": 0, - "id": "call_123", - "type": "code_interpreter", - "code_interpreter": { "input": "", "outputs": [] } - } - ] - } - } + "id": "run_abc123", + "object": "thread.run", + "created_at": 1698107661, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "completed", + "started_at": 1699073476, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699073498, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "tools": [{"type": "file_search"}, {"type": "code_interpreter"}], + "metadata": {}, + "incomplete_details": null, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + }, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true } - - ListRunStepsResponse: + CreateRunRequest: + type: object + additionalProperties: false + properties: + assistant_id: + description: The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run. + type: string + model: + description: The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. + example: "gpt-4o" + anyOf: + - type: string + - type: string + enum: + [ + "gpt-4o", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ] + x-oaiTypeLabel: string + nullable: true + instructions: + description: Overrides the [instructions](/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. + type: string + nullable: true + additional_instructions: + description: Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. + type: string + nullable: true + additional_messages: + description: Adds additional messages to the thread before creating the run. + type: array + items: + $ref: "#/components/schemas/CreateMessageRequest" + nullable: true + tools: + description: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + nullable: true + type: array + maxItems: 20 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + temperature: + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + description: *run_temperature_description + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: *run_top_p_description + stream: + type: boolean + nullable: true + description: | + If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + max_prompt_tokens: + type: integer + nullable: true + description: | + The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + max_completion_tokens: + type: integer + nullable: true + description: | + The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + truncation_strategy: + $ref: "#/components/schemas/TruncationObject" + nullable: true + tool_choice: + $ref: "#/components/schemas/AssistantsApiToolChoiceOption" + nullable: true + parallel_tool_calls: + $ref: "#/components/schemas/ParallelToolCalls" + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true + required: + - thread_id + - assistant_id + ListRunsResponse: + type: object properties: object: type: string @@ -11932,13 +12667,13 @@ components: data: type: array items: - $ref: "#/components/schemas/RunStepObject" + $ref: "#/components/schemas/RunObject" first_id: type: string - example: "step_abc123" + example: "run_abc123" last_id: type: string - example: "step_abc456" + example: "run_abc456" has_more: type: boolean example: false @@ -11948,423 +12683,547 @@ components: - first_id - last_id - has_more - - RunStepDetailsMessageCreationObject: - title: Message creation + ModifyRunRequest: type: object - description: Details of the message creation by the run step. + additionalProperties: false properties: - type: - description: Always `message_creation`. - type: string - enum: ["message_creation"] - message_creation: + metadata: + description: *metadata_description type: object - properties: - message_id: - type: string - description: The ID of the message that was created by this run step. - required: - - message_id + x-oaiTypeLabel: map + nullable: true + SubmitToolOutputsRunRequest: + type: object + additionalProperties: false + properties: + tool_outputs: + description: A list of tools for which the outputs are being submitted. + type: array + items: + type: object + properties: + tool_call_id: + type: string + description: The ID of the tool call in the `required_action` object within the run object the output is being submitted for. + output: + type: string + description: The output of the tool call to be submitted to continue the run. + stream: + type: boolean + nullable: true + description: | + If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. required: - - type - - message_creation + - tool_outputs - RunStepDeltaStepDetailsMessageCreationObject: - title: Message creation + RunToolCallObject: type: object - description: Details of the message creation by the run step. + description: Tool call objects properties: + id: + type: string + description: The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the [Submit tool outputs to run](/docs/api-reference/runs/submitToolOutputs) endpoint. type: - description: Always `message_creation`. type: string - enum: ["message_creation"] - message_creation: + description: The type of tool call the output is required for. For now, this is always `function`. + enum: ["function"] + function: type: object + description: The function definition. properties: - message_id: + name: type: string - description: The ID of the message that was created by this run step. + description: The name of the function. + arguments: + type: string + description: The arguments that the model expects you to pass to the function. + required: + - name + - arguments required: + - id - type + - function - RunStepDetailsToolCallsObject: - title: Tool calls + CreateThreadAndRunRequest: type: object - description: Details of the tool call. + additionalProperties: false properties: - type: - description: Always `tool_calls`. + assistant_id: + description: The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run. type: string - enum: ["tool_calls"] - tool_calls: - type: array - description: | - An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`. - items: - oneOf: - - $ref: "#/components/schemas/RunStepDetailsToolCallsCodeObject" - - $ref: "#/components/schemas/RunStepDetailsToolCallsFileSearchObject" - - $ref: "#/components/schemas/RunStepDetailsToolCallsFunctionObject" - x-oaiExpandable: true - required: - - type - - tool_calls - - RunStepDeltaStepDetailsToolCallsObject: - title: Tool calls - type: object - description: Details of the tool call. - properties: - type: - description: Always `tool_calls`. + thread: + $ref: "#/components/schemas/CreateThreadRequest" + description: If no thread is provided, an empty thread will be created. + model: + description: The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. + example: "gpt-4o" + anyOf: + - type: string + - type: string + enum: + [ + "gpt-4o", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ] + x-oaiTypeLabel: string + nullable: true + instructions: + description: Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. type: string - enum: ["tool_calls"] - tool_calls: + nullable: true + tools: + description: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + nullable: true type: array - description: | - An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`. + maxItems: 20 items: oneOf: - - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeObject" - - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsFileSearchObject" - - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsFunctionObject" - x-oaiExpandable: true + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + tool_resources: + type: object + description: | + A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: string + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + temperature: + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + description: *run_temperature_description + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: *run_top_p_description + stream: + type: boolean + nullable: true + description: | + If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + max_prompt_tokens: + type: integer + nullable: true + description: | + The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + max_completion_tokens: + type: integer + nullable: true + description: | + The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + truncation_strategy: + $ref: "#/components/schemas/TruncationObject" + nullable: true + tool_choice: + $ref: "#/components/schemas/AssistantsApiToolChoiceOption" + nullable: true + parallel_tool_calls: + $ref: "#/components/schemas/ParallelToolCalls" + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true required: - - type + - thread_id + - assistant_id - RunStepDetailsToolCallsCodeObject: - title: Code Interpreter tool call + ThreadObject: type: object - description: Details of the Code Interpreter tool call the run step was involved in. + title: Thread + description: Represents a thread that contains [messages](/docs/api-reference/messages). properties: id: + description: The identifier, which can be referenced in API endpoints. type: string - description: The ID of the tool call. - type: + object: + description: The object type, which is always `thread`. type: string - description: The type of tool call. This is always going to be `code_interpreter` for this type of tool call. - enum: ["code_interpreter"] - code_interpreter: + enum: ["thread"] + created_at: + description: The Unix timestamp (in seconds) for when the thread was created. + type: integer + tool_resources: type: object - description: The Code Interpreter tool call definition. - required: - - input - - outputs + description: | + A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: - input: - type: string - description: The input to the Code Interpreter tool call. - outputs: - type: array - description: The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type. - items: - type: object - oneOf: - - $ref: "#/components/schemas/RunStepDetailsToolCallsCodeOutputLogsObject" - - $ref: "#/components/schemas/RunStepDetailsToolCallsCodeOutputImageObject" - x-oaiExpandable: true + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. + maxItems: 1 + items: + type: string + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true required: - id - - type - - code_interpreter + - object + - created_at + - tool_resources + - metadata + x-oaiMeta: + name: The thread object + beta: true + example: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1698107661, + "metadata": {} + } - RunStepDeltaStepDetailsToolCallsCodeObject: - title: Code interpreter tool call + CreateThreadRequest: type: object - description: Details of the Code Interpreter tool call the run step was involved in. + additionalProperties: false properties: - index: - type: integer - description: The index of the tool call in the tool calls array. - id: - type: string - description: The ID of the tool call. - type: - type: string - description: The type of tool call. This is always going to be `code_interpreter` for this type of tool call. - enum: ["code_interpreter"] - code_interpreter: + messages: + description: A list of [messages](/docs/api-reference/messages) to start the thread with. + type: array + items: + $ref: "#/components/schemas/CreateMessageRequest" + tool_resources: type: object - description: The Code Interpreter tool call definition. + description: | + A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. properties: - input: - type: string - description: The input to the Code Interpreter tool call. - outputs: - type: array - description: The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type. - items: - type: object - oneOf: - - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject" - - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputImageObject" - x-oaiExpandable: true - required: - - index - - type + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. + maxItems: 1 + items: + type: string + vector_stores: + type: array + description: | + A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread. + maxItems: 1 + items: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + maxItems: 10000 + items: + type: string + chunking_strategy: + # Ideally we'd reuse the chunking strategy schema here, but it doesn't expand properly + type: object + description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + oneOf: + - type: object + title: Auto Chunking Strategy + description: The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. + additionalProperties: false + properties: + type: + type: string + description: Always `auto`. + enum: ["auto"] + required: + - type + - type: object + title: Static Chunking Strategy + additionalProperties: false + properties: + type: + type: string + description: Always `static`. + enum: ["static"] + static: + type: object + additionalProperties: false + properties: + max_chunk_size_tokens: + type: integer + minimum: 100 + maximum: 4096 + description: The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. + chunk_overlap_tokens: + type: integer + description: | + The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + required: + - max_chunk_size_tokens + - chunk_overlap_tokens + required: + - type + - static + x-oaiExpandable: true + metadata: + type: object + description: | + Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + x-oaiTypeLabel: map + x-oaiExpandable: true + oneOf: + - required: [vector_store_ids] + - required: [vector_stores] + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true - RunStepDetailsToolCallsCodeOutputLogsObject: - title: Code Interpreter log output + ModifyThreadRequest: type: object - description: Text output from the Code Interpreter tool call as part of a run step. + additionalProperties: false properties: - type: - description: Always `logs`. - type: string - enum: ["logs"] - logs: - type: string - description: The text output from the Code Interpreter tool call. - required: - - type - - logs + tool_resources: + type: object + description: | + A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. + maxItems: 1 + items: + type: string + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true - RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject: - title: Code interpreter log output + DeleteThreadResponse: type: object - description: Text output from the Code Interpreter tool call as part of a run step. properties: - index: - type: integer - description: The index of the output in the outputs array. - type: - description: Always `logs`. + id: type: string - enum: ["logs"] - logs: + deleted: + type: boolean + object: type: string - description: The text output from the Code Interpreter tool call. + enum: [thread.deleted] required: - - index - - type + - id + - object + - deleted - RunStepDetailsToolCallsCodeOutputImageObject: - title: Code Interpreter image output - type: object + ListThreadsResponse: properties: - type: - description: Always `image`. + object: type: string - enum: ["image"] - image: - type: object - properties: - file_id: - description: The [file](/docs/api-reference/files) ID of the image. - type: string - required: - - file_id - required: - - type - - image - - RunStepDeltaStepDetailsToolCallsCodeOutputImageObject: - title: Code interpreter image output - type: object - properties: - index: - type: integer - description: The index of the output in the outputs array. - type: - description: Always `image`. + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/ThreadObject" + first_id: type: string - enum: ["image"] - image: - type: object - properties: - file_id: - description: The [file](/docs/api-reference/files) ID of the image. - type: string + example: "asst_abc123" + last_id: + type: string + example: "asst_abc456" + has_more: + type: boolean + example: false required: - - index - - type + - object + - data + - first_id + - last_id + - has_more - RunStepDetailsToolCallsFileSearchObject: - title: File search tool call + MessageObject: type: object + title: The message object + description: Represents a message within a [thread](/docs/api-reference/threads). properties: id: + description: The identifier, which can be referenced in API endpoints. type: string - description: The ID of the tool call object. - type: + object: + description: The object type, which is always `thread.message`. type: string - description: The type of tool call. This is always going to be `file_search` for this type of tool call. - enum: ["file_search"] - file_search: + enum: ["thread.message"] + created_at: + description: The Unix timestamp (in seconds) for when the message was created. + type: integer + thread_id: + description: The [thread](/docs/api-reference/threads) ID that this message belongs to. + type: string + status: + description: The status of the message, which can be either `in_progress`, `incomplete`, or `completed`. + type: string + enum: ["in_progress", "incomplete", "completed"] + incomplete_details: + description: On an incomplete message, details about why the message is incomplete. type: object - description: For now, this is always going to be an empty object. - x-oaiTypeLabel: map - required: - - id - - type - - file_search - - RunStepDeltaStepDetailsToolCallsFileSearchObject: - title: File search tool call - type: object - properties: - index: - type: integer - description: The index of the tool call in the tool calls array. - id: - type: string - description: The ID of the tool call object. - type: - type: string - description: The type of tool call. This is always going to be `file_search` for this type of tool call. - enum: ["file_search"] - file_search: - type: object - description: For now, this is always going to be an empty object. - x-oaiTypeLabel: map - required: - - index - - type - - file_search - - RunStepDetailsToolCallsFunctionObject: - type: object - title: Function tool call - properties: - id: - type: string - description: The ID of the tool call object. - type: - type: string - description: The type of tool call. This is always going to be `function` for this type of tool call. - enum: ["function"] - function: - type: object - description: The definition of the function that was called. properties: - name: - type: string - description: The name of the function. - arguments: - type: string - description: The arguments passed to the function. - output: + reason: type: string - description: The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet. - nullable: true + description: The reason the message is incomplete. + enum: + [ + "content_filter", + "max_tokens", + "run_cancelled", + "run_expired", + "run_failed", + ] + nullable: true required: - - name - - arguments - - output - required: - - id - - type - - function - - RunStepDeltaStepDetailsToolCallsFunctionObject: - type: object - title: Function tool call - properties: - index: + - reason + completed_at: + description: The Unix timestamp (in seconds) for when the message was completed. type: integer - description: The index of the tool call in the tool calls array. - id: - type: string - description: The ID of the tool call object. - type: - type: string - description: The type of tool call. This is always going to be `function` for this type of tool call. - enum: ["function"] - function: - type: object - description: The definition of the function that was called. - properties: - name: - type: string - description: The name of the function. - arguments: - type: string - description: The arguments passed to the function. - output: - type: string - description: The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet. - nullable: true - required: - - index - - type - - VectorStoreExpirationAfter: - type: object - title: Vector store expiration policy - description: The expiration policy for a vector store. - properties: - anchor: - description: "Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`." - type: string - enum: ["last_active_at"] - days: - description: The number of days after the anchor time that the vector store will expire. + nullable: true + incomplete_at: + description: The Unix timestamp (in seconds) for when the message was marked as incomplete. type: integer - minimum: 1 - maximum: 365 - required: - - anchor - - days - - VectorStoreObject: - type: object - title: Vector store - description: A vector store is a collection of processed files can be used by the `file_search` tool. - properties: - id: - description: The identifier, which can be referenced in API endpoints. - type: string - object: - description: The object type, which is always `vector_store`. + nullable: true + role: + description: The entity that produced the message. One of `user` or `assistant`. type: string - enum: ["vector_store"] - created_at: - description: The Unix timestamp (in seconds) for when the vector store was created. - type: integer - name: - description: The name of the vector store. + enum: ["user", "assistant"] + content: + description: The content of the message in array of text and/or images. + type: array + items: + oneOf: + - $ref: "#/components/schemas/MessageContentImageFileObject" + - $ref: "#/components/schemas/MessageContentImageUrlObject" + - $ref: "#/components/schemas/MessageContentTextObject" + - $ref: "#/components/schemas/MessageContentRefusalObject" + x-oaiExpandable: true + assistant_id: + description: If applicable, the ID of the [assistant](/docs/api-reference/assistants) that authored this message. type: string - usage_bytes: - description: The total number of bytes used by the files in the vector store. - type: integer - file_counts: - type: object - properties: - in_progress: - description: The number of files that are currently being processed. - type: integer - completed: - description: The number of files that have been successfully processed. - type: integer - failed: - description: The number of files that have failed to process. - type: integer - cancelled: - description: The number of files that were cancelled. - type: integer - total: - description: The total number of files. - type: integer - required: - - in_progress - - completed - - failed - - cancelled - - total - status: - description: The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. + nullable: true + run_id: + description: The ID of the [run](/docs/api-reference/runs) associated with the creation of this message. Value is `null` when messages are created manually using the create message or create thread endpoints. type: string - enum: ["expired", "in_progress", "completed"] - expires_after: - $ref: "#/components/schemas/VectorStoreExpirationAfter" - expires_at: - description: The Unix timestamp (in seconds) for when the vector store will expire. - type: integer nullable: true - last_active_at: - description: The Unix timestamp (in seconds) for when the vector store was last active. - type: integer + attachments: + type: array + items: + type: object + properties: + file_id: + type: string + description: The ID of the file to attach to the message. + tools: + description: The tools to add this file to. + type: array + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearchTypeOnly" + x-oaiExpandable: true + description: A list of files attached to the message, and the tools they were added to. nullable: true metadata: description: *metadata_description @@ -12374,82 +13233,179 @@ components: required: - id - object - - usage_bytes - created_at + - thread_id - status - - last_active_at - - name - - file_counts + - incomplete_details + - completed_at + - incomplete_at + - role + - content + - assistant_id + - run_id + - attachments - metadata x-oaiMeta: - name: The vector store object + name: The message object beta: true example: | { - "id": "vs_123", - "object": "vector_store", - "created_at": 1698107661, - "usage_bytes": 123456, - "last_active_at": 1698107661, - "name": "my_vector_store", - "status": "completed", - "file_counts": { - "in_progress": 0, - "completed": 100, - "cancelled": 0, - "failed": 0, - "total": 100 - }, - "metadata": {}, - "last_used_at": 1698107661 - } - - CreateVectorStoreRequest: - type: object - additionalProperties: false - properties: - file_ids: - description: A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. - type: array - maxItems: 500 - items: - type: string - name: - description: The name of the vector store. + "id": "msg_abc123", + "object": "thread.message", + "created_at": 1698983503, + "thread_id": "thread_abc123", + "role": "assistant", + "content": [ + { + "type": "text", + "text": { + "value": "Hi! How can I help you today?", + "annotations": [] + } + } + ], + "assistant_id": "asst_abc123", + "run_id": "run_abc123", + "attachments": [], + "metadata": {} + } + + MessageDeltaObject: + type: object + title: Message delta object + description: | + Represents a message delta i.e. any changed fields on a message during streaming. + properties: + id: + description: The identifier of the message, which can be referenced in API endpoints. type: string - expires_after: - $ref: "#/components/schemas/VectorStoreExpirationAfter" - chunking_strategy: + object: + description: The object type, which is always `thread.message.delta`. + type: string + enum: ["thread.message.delta"] + delta: + description: The delta containing the fields that have changed on the Message. type: object - description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. + properties: + role: + description: The entity that produced the message. One of `user` or `assistant`. + type: string + enum: ["user", "assistant"] + content: + description: The content of the message in array of text and/or images. + type: array + items: + oneOf: + - $ref: "#/components/schemas/MessageDeltaContentImageFileObject" + - $ref: "#/components/schemas/MessageDeltaContentTextObject" + - $ref: "#/components/schemas/MessageDeltaContentRefusalObject" + - $ref: "#/components/schemas/MessageDeltaContentImageUrlObject" + x-oaiExpandable: true + required: + - id + - object + - delta + x-oaiMeta: + name: The message delta object + beta: true + example: | + { + "id": "msg_123", + "object": "thread.message.delta", + "delta": { + "content": [ + { + "index": 0, + "type": "text", + "text": { "value": "Hello", "annotations": [] } + } + ] + } + } + + CreateMessageRequest: + type: object + additionalProperties: false + required: + - role + - content + properties: + role: + type: string + enum: ["user", "assistant"] + description: | + The role of the entity that is creating the message. Allowed values include: + - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. + - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation. + content: oneOf: - - $ref: "#/components/schemas/AutoChunkingStrategyRequestParam" - - $ref: "#/components/schemas/StaticChunkingStrategyRequestParam" + - type: string + description: The text contents of the message. + title: Text content + - type: array + description: An array of content parts with a defined type, each can be of type `text` or images can be passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible models](/docs/models/overview). + title: Array of content parts + items: + oneOf: + - $ref: "#/components/schemas/MessageContentImageFileObject" + - $ref: "#/components/schemas/MessageContentImageUrlObject" + - $ref: "#/components/schemas/MessageRequestContentTextObject" + x-oaiExpandable: true + minItems: 1 x-oaiExpandable: true + attachments: + type: array + items: + type: object + properties: + file_id: + type: string + description: The ID of the file to attach to the message. + tools: + description: The tools to add this file to. + type: array + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearchTypeOnly" + x-oaiExpandable: true + description: A list of files attached to the message, and the tools they should be added to. + required: + - file_id + - tools + nullable: true metadata: description: *metadata_description type: object x-oaiTypeLabel: map nullable: true - UpdateVectorStoreRequest: + ModifyMessageRequest: type: object additionalProperties: false properties: - name: - description: The name of the vector store. - type: string - nullable: true - expires_after: - $ref: "#/components/schemas/VectorStoreExpirationAfter" - nullable: true metadata: description: *metadata_description type: object x-oaiTypeLabel: map nullable: true - ListVectorStoresResponse: + DeleteMessageResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: [thread.message.deleted] + required: + - id + - object + - deleted + + ListMessagesResponse: properties: object: type: string @@ -12457,13 +13413,13 @@ components: data: type: array items: - $ref: "#/components/schemas/VectorStoreObject" + $ref: "#/components/schemas/MessageObject" first_id: type: string - example: "vs_abc123" + example: "msg_abc123" last_id: type: string - example: "vs_abc456" + example: "msg_abc123" has_more: type: boolean example: false @@ -12474,904 +13430,2977 @@ components: - last_id - has_more - DeleteVectorStoreResponse: + MessageContentImageFileObject: + title: Image file type: object + description: References an image [File](/docs/api-reference/files) in the content of a message. properties: - id: - type: string - deleted: - type: boolean - object: + type: + description: Always `image_file`. type: string - enum: [vector_store.deleted] + enum: ["image_file"] + image_file: + type: object + properties: + file_id: + description: The [File](/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content. + type: string + detail: + type: string + description: Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`. + enum: ["auto", "low", "high"] + default: "auto" + required: + - file_id required: - - id - - object - - deleted + - type + - image_file - VectorStoreFileObject: + MessageDeltaContentImageFileObject: + title: Image file type: object - title: Vector store files - description: A list of files attached to a vector store. + description: References an image [File](/docs/api-reference/files) in the content of a message. properties: - id: - description: The identifier, which can be referenced in API endpoints. - type: string - object: - description: The object type, which is always `vector_store.file`. - type: string - enum: ["vector_store.file"] - usage_bytes: - description: The total vector store usage in bytes. Note that this may be different from the original file size. - type: integer - created_at: - description: The Unix timestamp (in seconds) for when the vector store file was created. + index: type: integer - vector_store_id: - description: The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to. - type: string - status: - description: The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. + description: The index of the content part in the message. + type: + description: Always `image_file`. type: string - enum: ["in_progress", "completed", "cancelled", "failed"] - last_error: + enum: ["image_file"] + image_file: type: object - description: The last error associated with this vector store file. Will be `null` if there are no errors. - nullable: true properties: - code: + file_id: + description: The [File](/docs/api-reference/files) ID of the image in the message content. Set `purpose="vision"` when uploading the File if you need to later display the file content. type: string - description: One of `server_error` or `rate_limit_exceeded`. - enum: - [ - "internal_error", - "file_not_found", - "parsing_error", - "unhandled_mime_type", - ] - message: + detail: type: string - description: A human-readable description of the error. - required: - - code - - message - chunking_strategy: - type: object - description: The strategy used to chunk the file. - oneOf: - - $ref: "#/components/schemas/StaticChunkingStrategyResponseParam" - - $ref: "#/components/schemas/OtherChunkingStrategyResponseParam" - x-oaiExpandable: true + description: Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`. + enum: ["auto", "low", "high"] + default: "auto" required: - - id - - object - - usage_bytes - - created_at - - vector_store_id - - status - - last_error - x-oaiMeta: - name: The vector store file object - beta: true - example: | - { - "id": "file-abc123", - "object": "vector_store.file", - "usage_bytes": 1234, - "created_at": 1698107661, - "vector_store_id": "vs_abc123", - "status": "completed", - "last_error": null, - "chunking_strategy": { - "type": "static", - "static": { - "max_chunk_size_tokens": 800, - "chunk_overlap_tokens": 400 - } - } - } + - index + - type - OtherChunkingStrategyResponseParam: + MessageContentImageUrlObject: + title: Image URL type: object - title: Other Chunking Strategy - description: This is returned when the chunking strategy is unknown. Typically, this is because the file was indexed before the `chunking_strategy` concept was introduced in the API. - additionalProperties: false + description: References an image URL in the content of a message. properties: type: type: string - description: Always `other`. - enum: ["other"] + enum: ["image_url"] + description: The type of the content part. + image_url: + type: object + properties: + url: + type: string + description: "The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp." + format: uri + detail: + type: string + description: Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto` + enum: ["auto", "low", "high"] + default: "auto" + required: + - url required: - type + - image_url - StaticChunkingStrategyResponseParam: + MessageDeltaContentImageUrlObject: + title: Image URL type: object - title: Static Chunking Strategy - additionalProperties: false + description: References an image URL in the content of a message. properties: + index: + type: integer + description: The index of the content part in the message. type: + description: Always `image_url`. type: string - description: Always `static`. - enum: ["static"] - static: - $ref: "#/components/schemas/StaticChunkingStrategy" + enum: ["image_url"] + image_url: + type: object + properties: + url: + description: "The URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp." + type: string + detail: + type: string + description: Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. + enum: ["auto", "low", "high"] + default: "auto" required: + - index - type - - static - - StaticChunkingStrategy: - type: object - additionalProperties: false - properties: - max_chunk_size_tokens: - type: integer - minimum: 100 - maximum: 4096 - description: The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. - chunk_overlap_tokens: - type: integer - description: | - The number of tokens that overlap between chunks. The default value is `400`. - - Note that the overlap must not exceed half of `max_chunk_size_tokens`. - required: - - max_chunk_size_tokens - - chunk_overlap_tokens - AutoChunkingStrategyRequestParam: + MessageContentTextObject: + title: Text type: object - title: Auto Chunking Strategy - description: The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. - additionalProperties: false + description: The text content that is part of a message. properties: type: + description: Always `text`. type: string - description: Always `auto`. - enum: ["auto"] + enum: ["text"] + text: + type: object + properties: + value: + description: The data that makes up the text. + type: string + annotations: + type: array + items: + oneOf: + - $ref: "#/components/schemas/MessageContentTextAnnotationsFileCitationObject" + - $ref: "#/components/schemas/MessageContentTextAnnotationsFilePathObject" + x-oaiExpandable: true + required: + - value + - annotations required: - type + - text - StaticChunkingStrategyRequestParam: + MessageContentRefusalObject: + title: Refusal type: object - title: Static Chunking Strategy - additionalProperties: false + description: The refusal content generated by the assistant. properties: type: + description: Always `refusal`. type: string - description: Always `static`. - enum: ["static"] - static: - $ref: "#/components/schemas/StaticChunkingStrategy" + enum: ["refusal"] + refusal: + type: string + nullable: false required: - type - - static - - ChunkingStrategyRequestParam: - type: object - description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. - oneOf: - - $ref: "#/components/schemas/AutoChunkingStrategyRequestParam" - - $ref: "#/components/schemas/StaticChunkingStrategyRequestParam" - x-oaiExpandable: true + - refusal - CreateVectorStoreFileRequest: + MessageRequestContentTextObject: + title: Text type: object - additionalProperties: false + description: The text content that is part of a message. properties: - file_id: - description: A [File](/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files. + type: + description: Always `text`. type: string - chunking_strategy: - $ref: "#/components/schemas/ChunkingStrategyRequestParam" + enum: ["text"] + text: + type: string + description: Text content to be sent to the model required: - - file_id + - type + - text - ListVectorStoreFilesResponse: + MessageContentTextAnnotationsFileCitationObject: + title: File citation + type: object + description: A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the "file_search" tool to search files. properties: - object: - type: string - example: "list" - data: - type: array - items: - $ref: "#/components/schemas/VectorStoreFileObject" - first_id: + type: + description: Always `file_citation`. type: string - example: "file-abc123" - last_id: + enum: ["file_citation"] + text: + description: The text in the message content that needs to be replaced. type: string - example: "file-abc456" - has_more: - type: boolean - example: false + file_citation: + type: object + properties: + file_id: + description: The ID of the specific File the citation is from. + type: string + required: + - file_id + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 required: - - object - - data - - first_id - - last_id - - has_more + - type + - text + - file_citation + - start_index + - end_index - DeleteVectorStoreFileResponse: + MessageContentTextAnnotationsFilePathObject: + title: File path type: object + description: A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file. properties: - id: + type: + description: Always `file_path`. type: string - deleted: - type: boolean - object: + enum: ["file_path"] + text: + description: The text in the message content that needs to be replaced. type: string - enum: [vector_store.file.deleted] + file_path: + type: object + properties: + file_id: + description: The ID of the file that was generated. + type: string + required: + - file_id + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 required: - - id - - object - - deleted + - type + - text + - file_path + - start_index + - end_index - VectorStoreFileBatchObject: + MessageDeltaContentTextObject: + title: Text type: object - title: Vector store file batch - description: A batch of files attached to a vector store. + description: The text content that is part of a message. properties: - id: - description: The identifier, which can be referenced in API endpoints. + index: + type: integer + description: The index of the content part in the message. + type: + description: Always `text`. type: string - object: - description: The object type, which is always `vector_store.file_batch`. + enum: ["text"] + text: + type: object + properties: + value: + description: The data that makes up the text. + type: string + annotations: + type: array + items: + oneOf: + - $ref: "#/components/schemas/MessageDeltaContentTextAnnotationsFileCitationObject" + - $ref: "#/components/schemas/MessageDeltaContentTextAnnotationsFilePathObject" + x-oaiExpandable: true + required: + - index + - type + + MessageDeltaContentRefusalObject: + title: Refusal + type: object + description: The refusal content that is part of a message. + properties: + index: + type: integer + description: The index of the refusal part in the message. + type: + description: Always `refusal`. type: string - enum: ["vector_store.files_batch"] + enum: ["refusal"] + refusal: + type: string + required: + - index + - type + + + MessageDeltaContentTextAnnotationsFileCitationObject: + title: File citation + type: object + description: A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the "file_search" tool to search files. + properties: + index: + type: integer + description: The index of the annotation in the text content part. + type: + description: Always `file_citation`. + type: string + enum: ["file_citation"] + text: + description: The text in the message content that needs to be replaced. + type: string + file_citation: + type: object + properties: + file_id: + description: The ID of the specific File the citation is from. + type: string + quote: + description: The specific quote in the file. + type: string + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 + required: + - index + - type + + MessageDeltaContentTextAnnotationsFilePathObject: + title: File path + type: object + description: A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file. + properties: + index: + type: integer + description: The index of the annotation in the text content part. + type: + description: Always `file_path`. + type: string + enum: ["file_path"] + text: + description: The text in the message content that needs to be replaced. + type: string + file_path: + type: object + properties: + file_id: + description: The ID of the file that was generated. + type: string + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 + required: + - index + - type + + RunStepObject: + type: object + title: Run steps + description: | + Represents a step in execution of a run. + properties: + id: + description: The identifier of the run step, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread.run.step`. + type: string + enum: ["thread.run.step"] created_at: - description: The Unix timestamp (in seconds) for when the vector store files batch was created. + description: The Unix timestamp (in seconds) for when the run step was created. type: integer - vector_store_id: - description: The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to. + assistant_id: + description: The ID of the [assistant](/docs/api-reference/assistants) associated with the run step. + type: string + thread_id: + description: The ID of the [thread](/docs/api-reference/threads) that was run. + type: string + run_id: + description: The ID of the [run](/docs/api-reference/runs) that this run step is a part of. type: string + type: + description: The type of run step, which can be either `message_creation` or `tool_calls`. + type: string + enum: ["message_creation", "tool_calls"] status: - description: The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. + description: The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`. type: string - enum: ["in_progress", "completed", "cancelled", "failed"] - file_counts: + enum: ["in_progress", "cancelled", "failed", "completed", "expired"] + step_details: + type: object + description: The details of the run step. + oneOf: + - $ref: "#/components/schemas/RunStepDetailsMessageCreationObject" + - $ref: "#/components/schemas/RunStepDetailsToolCallsObject" + x-oaiExpandable: true + last_error: type: object + description: The last error associated with this run step. Will be `null` if there are no errors. + nullable: true properties: - in_progress: - description: The number of files that are currently being processed. - type: integer - completed: - description: The number of files that have been processed. - type: integer - failed: - description: The number of files that have failed to process. - type: integer - cancelled: - description: The number of files that where cancelled. - type: integer - total: - description: The total number of files. - type: integer + code: + type: string + description: One of `server_error` or `rate_limit_exceeded`. + enum: ["server_error", "rate_limit_exceeded"] + message: + type: string + description: A human-readable description of the error. required: - - in_progress - - completed - - cancelled - - failed - - total + - code + - message + expired_at: + description: The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired. + type: integer + nullable: true + cancelled_at: + description: The Unix timestamp (in seconds) for when the run step was cancelled. + type: integer + nullable: true + failed_at: + description: The Unix timestamp (in seconds) for when the run step failed. + type: integer + nullable: true + completed_at: + description: The Unix timestamp (in seconds) for when the run step completed. + type: integer + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + usage: + $ref: "#/components/schemas/RunStepCompletionUsage" required: - id - object - created_at - - vector_store_id + - assistant_id + - thread_id + - run_id + - type - status - - file_counts + - step_details + - last_error + - expired_at + - cancelled_at + - failed_at + - completed_at + - metadata + - usage x-oaiMeta: - name: The vector store files batch object + name: The run step object beta: true - example: | - { - "id": "vsfb_123", - "object": "vector_store.files_batch", - "created_at": 1698107661, - "vector_store_id": "vs_abc123", - "status": "completed", - "file_counts": { - "in_progress": 0, - "completed": 100, - "failed": 0, - "cancelled": 0, - "total": 100 - } - } + example: *run_step_object_example - CreateVectorStoreFileBatchRequest: + RunStepDeltaObject: type: object - additionalProperties: false + title: Run step delta object + description: | + Represents a run step delta i.e. any changed fields on a run step during streaming. properties: - file_ids: - description: A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. - type: array - minItems: 1 - maxItems: 500 - items: - type: string - chunking_strategy: - $ref: "#/components/schemas/ChunkingStrategyRequestParam" + id: + description: The identifier of the run step, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread.run.step.delta`. + type: string + enum: ["thread.run.step.delta"] + delta: + description: The delta containing the fields that have changed on the run step. + type: object + properties: + step_details: + type: object + description: The details of the run step. + oneOf: + - $ref: "#/components/schemas/RunStepDeltaStepDetailsMessageCreationObject" + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsObject" + x-oaiExpandable: true required: - - file_ids + - id + - object + - delta + x-oaiMeta: + name: The run step delta object + beta: true + example: | + { + "id": "step_123", + "object": "thread.run.step.delta", + "delta": { + "step_details": { + "type": "tool_calls", + "tool_calls": [ + { + "index": 0, + "id": "call_123", + "type": "code_interpreter", + "code_interpreter": { "input": "", "outputs": [] } + } + ] + } + } + } - AssistantStreamEvent: - description: | - Represents an event emitted when streaming a Run. + ListRunStepsResponse: + properties: + object: + type: string + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/RunStepObject" + first_id: + type: string + example: "step_abc123" + last_id: + type: string + example: "step_abc456" + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more - Each event in a server-sent events stream has an `event` and `data` property: + RunStepDetailsMessageCreationObject: + title: Message creation + type: object + description: Details of the message creation by the run step. + properties: + type: + description: Always `message_creation`. + type: string + enum: ["message_creation"] + message_creation: + type: object + properties: + message_id: + type: string + description: The ID of the message that was created by this run step. + required: + - message_id + required: + - type + - message_creation - ``` - event: thread.created - data: {"id": "thread_123", "object": "thread", ...} - ``` + RunStepDeltaStepDetailsMessageCreationObject: + title: Message creation + type: object + description: Details of the message creation by the run step. + properties: + type: + description: Always `message_creation`. + type: string + enum: ["message_creation"] + message_creation: + type: object + properties: + message_id: + type: string + description: The ID of the message that was created by this run step. + required: + - type - We emit events whenever a new object is created, transitions to a new state, or is being - streamed in parts (deltas). For example, we emit `thread.run.created` when a new run - is created, `thread.run.completed` when a run completes, and so on. When an Assistant chooses - to create a message during a run, we emit a `thread.message.created event`, a - `thread.message.in_progress` event, many `thread.message.delta` events, and finally a - `thread.message.completed` event. + RunStepDetailsToolCallsObject: + title: Tool calls + type: object + description: Details of the tool call. + properties: + type: + description: Always `tool_calls`. + type: string + enum: ["tool_calls"] + tool_calls: + type: array + description: | + An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`. + items: + oneOf: + - $ref: "#/components/schemas/RunStepDetailsToolCallsCodeObject" + - $ref: "#/components/schemas/RunStepDetailsToolCallsFileSearchObject" + - $ref: "#/components/schemas/RunStepDetailsToolCallsFunctionObject" + x-oaiExpandable: true + required: + - type + - tool_calls - We may add additional events over time, so we recommend handling unknown events gracefully - in your code. See the [Assistants API quickstart](/docs/assistants/overview) to learn how to - integrate the Assistants API with streaming. - oneOf: - - $ref: "#/components/schemas/ThreadStreamEvent" - - $ref: "#/components/schemas/RunStreamEvent" - - $ref: "#/components/schemas/RunStepStreamEvent" - - $ref: "#/components/schemas/MessageStreamEvent" - - $ref: "#/components/schemas/ErrorEvent" - - $ref: "#/components/schemas/DoneEvent" - x-oaiMeta: - name: Assistant stream events - beta: true + RunStepDeltaStepDetailsToolCallsObject: + title: Tool calls + type: object + description: Details of the tool call. + properties: + type: + description: Always `tool_calls`. + type: string + enum: ["tool_calls"] + tool_calls: + type: array + description: | + An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`. + items: + oneOf: + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeObject" + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsFileSearchObject" + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsFunctionObject" + x-oaiExpandable: true + required: + - type - ThreadStreamEvent: - oneOf: - - type: object - properties: - event: - type: string - enum: ["thread.created"] - data: - $ref: "#/components/schemas/ThreadObject" - required: - - event - - data - description: Occurs when a new [thread](/docs/api-reference/threads/object) is created. - x-oaiMeta: - dataDescription: "`data` is a [thread](/docs/api-reference/threads/object)" + RunStepDetailsToolCallsCodeObject: + title: Code Interpreter tool call + type: object + description: Details of the Code Interpreter tool call the run step was involved in. + properties: + id: + type: string + description: The ID of the tool call. + type: + type: string + description: The type of tool call. This is always going to be `code_interpreter` for this type of tool call. + enum: ["code_interpreter"] + code_interpreter: + type: object + description: The Code Interpreter tool call definition. + required: + - input + - outputs + properties: + input: + type: string + description: The input to the Code Interpreter tool call. + outputs: + type: array + description: The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type. + items: + type: object + oneOf: + - $ref: "#/components/schemas/RunStepDetailsToolCallsCodeOutputLogsObject" + - $ref: "#/components/schemas/RunStepDetailsToolCallsCodeOutputImageObject" + x-oaiExpandable: true + required: + - id + - type + - code_interpreter - RunStreamEvent: - oneOf: - - type: object - properties: - event: - type: string - enum: ["thread.run.created"] - data: - $ref: "#/components/schemas/RunObject" - required: - - event - - data - description: Occurs when a new [run](/docs/api-reference/runs/object) is created. - x-oaiMeta: - dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" - - type: object - properties: - event: - type: string - enum: ["thread.run.queued"] - data: - $ref: "#/components/schemas/RunObject" - required: - - event - - data - description: Occurs when a [run](/docs/api-reference/runs/object) moves to a `queued` status. - x-oaiMeta: - dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" - - type: object - properties: - event: - type: string - enum: ["thread.run.in_progress"] - data: - $ref: "#/components/schemas/RunObject" - required: - - event - - data - description: Occurs when a [run](/docs/api-reference/runs/object) moves to an `in_progress` status. - x-oaiMeta: - dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" - - type: object - properties: - event: - type: string - enum: ["thread.run.requires_action"] - data: - $ref: "#/components/schemas/RunObject" - required: - - event + RunStepDeltaStepDetailsToolCallsCodeObject: + title: Code interpreter tool call + type: object + description: Details of the Code Interpreter tool call the run step was involved in. + properties: + index: + type: integer + description: The index of the tool call in the tool calls array. + id: + type: string + description: The ID of the tool call. + type: + type: string + description: The type of tool call. This is always going to be `code_interpreter` for this type of tool call. + enum: ["code_interpreter"] + code_interpreter: + type: object + description: The Code Interpreter tool call definition. + properties: + input: + type: string + description: The input to the Code Interpreter tool call. + outputs: + type: array + description: The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type. + items: + type: object + oneOf: + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject" + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputImageObject" + x-oaiExpandable: true + required: + - index + - type + + RunStepDetailsToolCallsCodeOutputLogsObject: + title: Code Interpreter log output + type: object + description: Text output from the Code Interpreter tool call as part of a run step. + properties: + type: + description: Always `logs`. + type: string + enum: ["logs"] + logs: + type: string + description: The text output from the Code Interpreter tool call. + required: + - type + - logs + + RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject: + title: Code interpreter log output + type: object + description: Text output from the Code Interpreter tool call as part of a run step. + properties: + index: + type: integer + description: The index of the output in the outputs array. + type: + description: Always `logs`. + type: string + enum: ["logs"] + logs: + type: string + description: The text output from the Code Interpreter tool call. + required: + - index + - type + + RunStepDetailsToolCallsCodeOutputImageObject: + title: Code Interpreter image output + type: object + properties: + type: + description: Always `image`. + type: string + enum: ["image"] + image: + type: object + properties: + file_id: + description: The [file](/docs/api-reference/files) ID of the image. + type: string + required: + - file_id + required: + - type + - image + + RunStepDeltaStepDetailsToolCallsCodeOutputImageObject: + title: Code interpreter image output + type: object + properties: + index: + type: integer + description: The index of the output in the outputs array. + type: + description: Always `image`. + type: string + enum: ["image"] + image: + type: object + properties: + file_id: + description: The [file](/docs/api-reference/files) ID of the image. + type: string + required: + - index + - type + + RunStepDetailsToolCallsFileSearchObject: + title: File search tool call + type: object + properties: + id: + type: string + description: The ID of the tool call object. + type: + type: string + description: The type of tool call. This is always going to be `file_search` for this type of tool call. + enum: ["file_search"] + file_search: + type: object + description: For now, this is always going to be an empty object. + x-oaiTypeLabel: map + required: + - id + - type + - file_search + + RunStepDeltaStepDetailsToolCallsFileSearchObject: + title: File search tool call + type: object + properties: + index: + type: integer + description: The index of the tool call in the tool calls array. + id: + type: string + description: The ID of the tool call object. + type: + type: string + description: The type of tool call. This is always going to be `file_search` for this type of tool call. + enum: ["file_search"] + file_search: + type: object + description: For now, this is always going to be an empty object. + x-oaiTypeLabel: map + required: + - index + - type + - file_search + + RunStepDetailsToolCallsFunctionObject: + type: object + title: Function tool call + properties: + id: + type: string + description: The ID of the tool call object. + type: + type: string + description: The type of tool call. This is always going to be `function` for this type of tool call. + enum: ["function"] + function: + type: object + description: The definition of the function that was called. + properties: + name: + type: string + description: The name of the function. + arguments: + type: string + description: The arguments passed to the function. + output: + type: string + description: The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet. + nullable: true + required: + - name + - arguments + - output + required: + - id + - type + - function + + RunStepDeltaStepDetailsToolCallsFunctionObject: + type: object + title: Function tool call + properties: + index: + type: integer + description: The index of the tool call in the tool calls array. + id: + type: string + description: The ID of the tool call object. + type: + type: string + description: The type of tool call. This is always going to be `function` for this type of tool call. + enum: ["function"] + function: + type: object + description: The definition of the function that was called. + properties: + name: + type: string + description: The name of the function. + arguments: + type: string + description: The arguments passed to the function. + output: + type: string + description: The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet. + nullable: true + required: + - index + - type + + VectorStoreExpirationAfter: + type: object + title: Vector store expiration policy + description: The expiration policy for a vector store. + properties: + anchor: + description: "Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`." + type: string + enum: ["last_active_at"] + days: + description: The number of days after the anchor time that the vector store will expire. + type: integer + minimum: 1 + maximum: 365 + required: + - anchor + - days + + VectorStoreObject: + type: object + title: Vector store + description: A vector store is a collection of processed files can be used by the `file_search` tool. + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `vector_store`. + type: string + enum: ["vector_store"] + created_at: + description: The Unix timestamp (in seconds) for when the vector store was created. + type: integer + name: + description: The name of the vector store. + type: string + usage_bytes: + description: The total number of bytes used by the files in the vector store. + type: integer + file_counts: + type: object + properties: + in_progress: + description: The number of files that are currently being processed. + type: integer + completed: + description: The number of files that have been successfully processed. + type: integer + failed: + description: The number of files that have failed to process. + type: integer + cancelled: + description: The number of files that were cancelled. + type: integer + total: + description: The total number of files. + type: integer + required: + - in_progress + - completed + - failed + - cancelled + - total + status: + description: The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. + type: string + enum: ["expired", "in_progress", "completed"] + expires_after: + $ref: "#/components/schemas/VectorStoreExpirationAfter" + expires_at: + description: The Unix timestamp (in seconds) for when the vector store will expire. + type: integer + nullable: true + last_active_at: + description: The Unix timestamp (in seconds) for when the vector store was last active. + type: integer + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + required: + - id + - object + - usage_bytes + - created_at + - status + - last_active_at + - name + - file_counts + - metadata + x-oaiMeta: + name: The vector store object + beta: true + example: | + { + "id": "vs_123", + "object": "vector_store", + "created_at": 1698107661, + "usage_bytes": 123456, + "last_active_at": 1698107661, + "name": "my_vector_store", + "status": "completed", + "file_counts": { + "in_progress": 0, + "completed": 100, + "cancelled": 0, + "failed": 0, + "total": 100 + }, + "metadata": {}, + "last_used_at": 1698107661 + } + + CreateVectorStoreRequest: + type: object + additionalProperties: false + properties: + file_ids: + description: A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. + type: array + maxItems: 500 + items: + type: string + name: + description: The name of the vector store. + type: string + expires_after: + $ref: "#/components/schemas/VectorStoreExpirationAfter" + chunking_strategy: + type: object + description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. + oneOf: + - $ref: "#/components/schemas/AutoChunkingStrategyRequestParam" + - $ref: "#/components/schemas/StaticChunkingStrategyRequestParam" + x-oaiExpandable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + + UpdateVectorStoreRequest: + type: object + additionalProperties: false + properties: + name: + description: The name of the vector store. + type: string + nullable: true + expires_after: + $ref: "#/components/schemas/VectorStoreExpirationAfter" + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + + ListVectorStoresResponse: + properties: + object: + type: string + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/VectorStoreObject" + first_id: + type: string + example: "vs_abc123" + last_id: + type: string + example: "vs_abc456" + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + + DeleteVectorStoreResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: [vector_store.deleted] + required: + - id + - object + - deleted + + VectorStoreFileObject: + type: object + title: Vector store files + description: A list of files attached to a vector store. + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `vector_store.file`. + type: string + enum: ["vector_store.file"] + usage_bytes: + description: The total vector store usage in bytes. Note that this may be different from the original file size. + type: integer + created_at: + description: The Unix timestamp (in seconds) for when the vector store file was created. + type: integer + vector_store_id: + description: The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to. + type: string + status: + description: The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. + type: string + enum: ["in_progress", "completed", "cancelled", "failed"] + last_error: + type: object + description: The last error associated with this vector store file. Will be `null` if there are no errors. + nullable: true + properties: + code: + type: string + description: One of `server_error` or `rate_limit_exceeded`. + enum: + [ + "server_error", + "unsupported_file", + "invalid_file", + ] + message: + type: string + description: A human-readable description of the error. + required: + - code + - message + chunking_strategy: + type: object + description: The strategy used to chunk the file. + oneOf: + - $ref: "#/components/schemas/StaticChunkingStrategyResponseParam" + - $ref: "#/components/schemas/OtherChunkingStrategyResponseParam" + x-oaiExpandable: true + required: + - id + - object + - usage_bytes + - created_at + - vector_store_id + - status + - last_error + x-oaiMeta: + name: The vector store file object + beta: true + example: | + { + "id": "file-abc123", + "object": "vector_store.file", + "usage_bytes": 1234, + "created_at": 1698107661, + "vector_store_id": "vs_abc123", + "status": "completed", + "last_error": null, + "chunking_strategy": { + "type": "static", + "static": { + "max_chunk_size_tokens": 800, + "chunk_overlap_tokens": 400 + } + } + } + + OtherChunkingStrategyResponseParam: + type: object + title: Other Chunking Strategy + description: This is returned when the chunking strategy is unknown. Typically, this is because the file was indexed before the `chunking_strategy` concept was introduced in the API. + additionalProperties: false + properties: + type: + type: string + description: Always `other`. + enum: ["other"] + required: + - type + + StaticChunkingStrategyResponseParam: + type: object + title: Static Chunking Strategy + additionalProperties: false + properties: + type: + type: string + description: Always `static`. + enum: ["static"] + static: + $ref: "#/components/schemas/StaticChunkingStrategy" + required: + - type + - static + + StaticChunkingStrategy: + type: object + additionalProperties: false + properties: + max_chunk_size_tokens: + type: integer + minimum: 100 + maximum: 4096 + description: The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`. + chunk_overlap_tokens: + type: integer + description: | + The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + required: + - max_chunk_size_tokens + - chunk_overlap_tokens + + AutoChunkingStrategyRequestParam: + type: object + title: Auto Chunking Strategy + description: The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. + additionalProperties: false + properties: + type: + type: string + description: Always `auto`. + enum: ["auto"] + required: + - type + + StaticChunkingStrategyRequestParam: + type: object + title: Static Chunking Strategy + additionalProperties: false + properties: + type: + type: string + description: Always `static`. + enum: ["static"] + static: + $ref: "#/components/schemas/StaticChunkingStrategy" + required: + - type + - static + + ChunkingStrategyRequestParam: + type: object + description: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + oneOf: + - $ref: "#/components/schemas/AutoChunkingStrategyRequestParam" + - $ref: "#/components/schemas/StaticChunkingStrategyRequestParam" + x-oaiExpandable: true + + CreateVectorStoreFileRequest: + type: object + additionalProperties: false + properties: + file_id: + description: A [File](/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files. + type: string + chunking_strategy: + $ref: "#/components/schemas/ChunkingStrategyRequestParam" + required: + - file_id + + ListVectorStoreFilesResponse: + properties: + object: + type: string + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/VectorStoreFileObject" + first_id: + type: string + example: "file-abc123" + last_id: + type: string + example: "file-abc456" + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + + DeleteVectorStoreFileResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: [vector_store.file.deleted] + required: + - id + - object + - deleted + + VectorStoreFileBatchObject: + type: object + title: Vector store file batch + description: A batch of files attached to a vector store. + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `vector_store.file_batch`. + type: string + enum: ["vector_store.files_batch"] + created_at: + description: The Unix timestamp (in seconds) for when the vector store files batch was created. + type: integer + vector_store_id: + description: The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to. + type: string + status: + description: The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. + type: string + enum: ["in_progress", "completed", "cancelled", "failed"] + file_counts: + type: object + properties: + in_progress: + description: The number of files that are currently being processed. + type: integer + completed: + description: The number of files that have been processed. + type: integer + failed: + description: The number of files that have failed to process. + type: integer + cancelled: + description: The number of files that where cancelled. + type: integer + total: + description: The total number of files. + type: integer + required: + - in_progress + - completed + - cancelled + - failed + - total + required: + - id + - object + - created_at + - vector_store_id + - status + - file_counts + x-oaiMeta: + name: The vector store files batch object + beta: true + example: | + { + "id": "vsfb_123", + "object": "vector_store.files_batch", + "created_at": 1698107661, + "vector_store_id": "vs_abc123", + "status": "completed", + "file_counts": { + "in_progress": 0, + "completed": 100, + "failed": 0, + "cancelled": 0, + "total": 100 + } + } + + CreateVectorStoreFileBatchRequest: + type: object + additionalProperties: false + properties: + file_ids: + description: A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. + type: array + minItems: 1 + maxItems: 500 + items: + type: string + chunking_strategy: + $ref: "#/components/schemas/ChunkingStrategyRequestParam" + required: + - file_ids + + AssistantStreamEvent: + description: | + Represents an event emitted when streaming a Run. + + Each event in a server-sent events stream has an `event` and `data` property: + + ``` + event: thread.created + data: {"id": "thread_123", "object": "thread", ...} + ``` + + We emit events whenever a new object is created, transitions to a new state, or is being + streamed in parts (deltas). For example, we emit `thread.run.created` when a new run + is created, `thread.run.completed` when a run completes, and so on. When an Assistant chooses + to create a message during a run, we emit a `thread.message.created event`, a + `thread.message.in_progress` event, many `thread.message.delta` events, and finally a + `thread.message.completed` event. + + We may add additional events over time, so we recommend handling unknown events gracefully + in your code. See the [Assistants API quickstart](/docs/assistants/overview) to learn how to + integrate the Assistants API with streaming. + oneOf: + - $ref: "#/components/schemas/ThreadStreamEvent" + - $ref: "#/components/schemas/RunStreamEvent" + - $ref: "#/components/schemas/RunStepStreamEvent" + - $ref: "#/components/schemas/MessageStreamEvent" + - $ref: "#/components/schemas/ErrorEvent" + - $ref: "#/components/schemas/DoneEvent" + x-oaiMeta: + name: Assistant stream events + beta: true + + ThreadStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: ["thread.created"] + data: + $ref: "#/components/schemas/ThreadObject" + required: + - event + - data + description: Occurs when a new [thread](/docs/api-reference/threads/object) is created. + x-oaiMeta: + dataDescription: "`data` is a [thread](/docs/api-reference/threads/object)" + + RunStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: ["thread.run.created"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a new [run](/docs/api-reference/runs/object) is created. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.queued"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) moves to a `queued` status. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.in_progress"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) moves to an `in_progress` status. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.requires_action"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) moves to a `requires_action` status. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.completed"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) is completed. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: [ "thread.run.incomplete" ] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) ends with status `incomplete`. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.failed"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) fails. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.cancelling"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) moves to a `cancelling` status. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.cancelled"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) is cancelled. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.expired"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) expires. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + + RunStepStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: ["thread.run.step.created"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) is created. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.in_progress"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) moves to an `in_progress` state. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.delta"] + data: + $ref: "#/components/schemas/RunStepDeltaObject" + required: + - event + - data + description: Occurs when parts of a [run step](/docs/api-reference/runs/step-object) are being streamed. + x-oaiMeta: + dataDescription: "`data` is a [run step delta](/docs/api-reference/assistants-streaming/run-step-delta-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.completed"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) is completed. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.failed"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event - data - description: Occurs when a [run](/docs/api-reference/runs/object) moves to a `requires_action` status. + description: Occurs when a [run step](/docs/api-reference/runs/step-object) fails. x-oaiMeta: - dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" - type: object properties: event: type: string - enum: ["thread.run.completed"] + enum: ["thread.run.step.cancelled"] data: - $ref: "#/components/schemas/RunObject" + $ref: "#/components/schemas/RunStepObject" required: - event - data - description: Occurs when a [run](/docs/api-reference/runs/object) is completed. + description: Occurs when a [run step](/docs/api-reference/runs/step-object) is cancelled. x-oaiMeta: - dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" - type: object properties: event: type: string - enum: [ "thread.run.incomplete" ] + enum: ["thread.run.step.expired"] data: - $ref: "#/components/schemas/RunObject" + $ref: "#/components/schemas/RunStepObject" required: - event - data - description: Occurs when a [run](/docs/api-reference/runs/object) ends with status `incomplete`. + description: Occurs when a [run step](/docs/api-reference/runs/step-object) expires. x-oaiMeta: - dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + + MessageStreamEvent: + oneOf: - type: object properties: event: type: string - enum: ["thread.run.failed"] + enum: ["thread.message.created"] data: - $ref: "#/components/schemas/RunObject" + $ref: "#/components/schemas/MessageObject" required: - event - data - description: Occurs when a [run](/docs/api-reference/runs/object) fails. + description: Occurs when a [message](/docs/api-reference/messages/object) is created. x-oaiMeta: - dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" - type: object properties: event: type: string - enum: ["thread.run.cancelling"] + enum: ["thread.message.in_progress"] data: - $ref: "#/components/schemas/RunObject" + $ref: "#/components/schemas/MessageObject" required: - event - data - description: Occurs when a [run](/docs/api-reference/runs/object) moves to a `cancelling` status. + description: Occurs when a [message](/docs/api-reference/messages/object) moves to an `in_progress` state. x-oaiMeta: - dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" - type: object properties: event: type: string - enum: ["thread.run.cancelled"] + enum: ["thread.message.delta"] data: - $ref: "#/components/schemas/RunObject" + $ref: "#/components/schemas/MessageDeltaObject" required: - event - data - description: Occurs when a [run](/docs/api-reference/runs/object) is cancelled. + description: Occurs when parts of a [Message](/docs/api-reference/messages/object) are being streamed. x-oaiMeta: - dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + dataDescription: "`data` is a [message delta](/docs/api-reference/assistants-streaming/message-delta-object)" - type: object properties: event: type: string - enum: ["thread.run.expired"] + enum: ["thread.message.completed"] data: - $ref: "#/components/schemas/RunObject" + $ref: "#/components/schemas/MessageObject" required: - event - data - description: Occurs when a [run](/docs/api-reference/runs/object) expires. + description: Occurs when a [message](/docs/api-reference/messages/object) is completed. x-oaiMeta: - dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" + - type: object + properties: + event: + type: string + enum: ["thread.message.incomplete"] + data: + $ref: "#/components/schemas/MessageObject" + required: + - event + - data + description: Occurs when a [message](/docs/api-reference/messages/object) ends before it is completed. + x-oaiMeta: + dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" + + ErrorEvent: + type: object + properties: + event: + type: string + enum: ["error"] + data: + $ref: "#/components/schemas/Error" + required: + - event + - data + description: Occurs when an [error](/docs/guides/error-codes/api-errors) occurs. This can happen due to an internal server error or a timeout. + x-oaiMeta: + dataDescription: "`data` is an [error](/docs/guides/error-codes/api-errors)" + + DoneEvent: + type: object + properties: + event: + type: string + enum: ["done"] + data: + type: string + enum: ["[DONE]"] + required: + - event + - data + description: Occurs when a stream ends. + x-oaiMeta: + dataDescription: "`data` is `[DONE]`" + + Batch: + type: object + properties: + id: + type: string + object: + type: string + enum: [batch] + description: The object type, which is always `batch`. + endpoint: + type: string + description: The OpenAI API endpoint used by the batch. + + errors: + type: object + properties: + object: + type: string + description: The object type, which is always `list`. + data: + type: array + items: + type: object + properties: + code: + type: string + description: An error code identifying the error type. + message: + type: string + description: A human-readable message providing more details about the error. + param: + type: string + description: The name of the parameter that caused the error, if applicable. + nullable: true + line: + type: integer + description: The line number of the input file where the error occurred, if applicable. + nullable: true + input_file_id: + type: string + description: The ID of the input file for the batch. + completion_window: + type: string + description: The time frame within which the batch should be processed. + status: + type: string + description: The current status of the batch. + enum: + - validating + - failed + - in_progress + - finalizing + - completed + - expired + - cancelling + - cancelled + output_file_id: + type: string + description: The ID of the file containing the outputs of successfully executed requests. + error_file_id: + type: string + description: The ID of the file containing the outputs of requests with errors. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch was created. + in_progress_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch started processing. + expires_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch will expire. + finalizing_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch started finalizing. + completed_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch was completed. + failed_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch failed. + expired_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch expired. + cancelling_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch started cancelling. + cancelled_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch was cancelled. + request_counts: + type: object + properties: + total: + type: integer + description: Total number of requests in the batch. + completed: + type: integer + description: Number of requests that have been completed successfully. + failed: + type: integer + description: Number of requests that have failed. + required: + - total + - completed + - failed + description: The request counts for different statuses within the batch. + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + required: + - id + - object + - endpoint + - input_file_id + - completion_window + - status + - created_at + x-oaiMeta: + name: The batch object + example: *batch_object + + BatchRequestInput: + type: object + description: The per-line object of the batch input file + properties: + custom_id: + type: string + description: A developer-provided per-request id that will be used to match outputs to inputs. Must be unique for each request in a batch. + method: + type: string + enum: ["POST"] + description: The HTTP method to be used for the request. Currently only `POST` is supported. + url: + type: string + description: The OpenAI API relative URL to be used for the request. Currently `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. + x-oaiMeta: + name: The request input object + example: | + {"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is 2+2?"}]}} + + BatchRequestOutput: + type: object + description: The per-line object of the batch output and error files + properties: + id: + type: string + custom_id: + type: string + description: A developer-provided per-request id that will be used to match outputs to inputs. + response: + type: object + nullable: true + properties: + status_code: + type: integer + description: The HTTP status code of the response + request_id: + type: string + description: An unique identifier for the OpenAI API request. Please include this request ID when contacting support. + body: + type: object + x-oaiTypeLabel: map + description: The JSON body of the response + error: + type: object + nullable: true + description: For requests that failed with a non-HTTP error, this will contain more information on the cause of the failure. + properties: + code: + type: string + description: A machine-readable error code. + message: + type: string + description: A human-readable error message. + x-oaiMeta: + name: The request output object + example: | + {"id": "batch_req_wnaDys", "custom_id": "request-2", "response": {"status_code": 200, "request_id": "req_c187b3", "body": {"id": "chatcmpl-9758Iw", "object": "chat.completion", "created": 1711475054, "model": "gpt-4o-mini", "choices": [{"index": 0, "message": {"role": "assistant", "content": "2 + 2 equals 4."}, "finish_reason": "stop"}], "usage": {"prompt_tokens": 24, "completion_tokens": 15, "total_tokens": 39}, "system_fingerprint": null}}, "error": null} + + ListBatchesResponse: + type: object + properties: + data: + type: array + items: + $ref: "#/components/schemas/Batch" + first_id: + type: string + example: "batch_abc123" + last_id: + type: string + example: "batch_abc456" + has_more: + type: boolean + object: + type: string + enum: [list] + required: + - object + - data + - has_more + + AuditLogActorServiceAccount: + type: object + description: The service account that performed the audit logged action. + properties: + id: + type: string + description: The service account id. + + AuditLogActorUser: + type: object + description: The user who performed the audit logged action. + properties: + id: + type: string + description: The user id. + email: + type: string + description: The user email. + + AuditLogActorApiKey: + type: object + description: The API Key used to perform the audit logged action. + properties: + id: + type: string + description: The tracking id of the API key. + type: + type: string + description: The type of API key. Can be either `user` or `service_account`. + enum: ["user", "service_account"] + user: + $ref: "#/components/schemas/AuditLogActorUser" + service_account: + $ref: "#/components/schemas/AuditLogActorServiceAccount" + + AuditLogActorSession: + type: object + description: The session in which the audit logged action was performed. + properties: + user: + $ref: "#/components/schemas/AuditLogActorUser" + ip_address: + type: string + description: The IP address from which the action was performed. + + AuditLogActor: + type: object + description: The actor who performed the audit logged action. + properties: + type: + type: string + description: The type of actor. Is either `session` or `api_key`. + enum: ["session", "api_key"] + session: + type: object + $ref: "#/components/schemas/AuditLogActorSession" + api_key: + type: object + $ref: "#/components/schemas/AuditLogActorApiKey" + + + AuditLogEventType: + type: string + description: The event type. + x-oaiExpandable: true + enum: + - api_key.created + - api_key.updated + - api_key.deleted + - invite.sent + - invite.accepted + - invite.deleted + - login.succeeded + - login.failed + - logout.succeeded + - logout.failed + - organization.updated + - project.created + - project.updated + - project.archived + - service_account.created + - service_account.updated + - service_account.deleted + - user.added + - user.updated + - user.deleted + + AuditLog: + type: object + description: A log of a user action or configuration change within this organization. + properties: + id: + type: string + description: The ID of this log. + type: + $ref: "#/components/schemas/AuditLogEventType" + + effective_at: + type: integer + description: The Unix timestamp (in seconds) of the event. + project: + type: object + description: The project that the action was scoped to. Absent for actions not scoped to projects. + properties: + id: + type: string + description: The project ID. + name: + type: string + description: The project title. + actor: + $ref: "#/components/schemas/AuditLogActor" + api_key.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The tracking ID of the API key. + data: + type: object + description: The payload used to create the API key. + properties: + scopes: + type: array + items: + type: string + description: A list of scopes allowed for the API key, e.g. `["api.model.request"]` + api_key.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The tracking ID of the API key. + changes_requested: + type: object + description: The payload used to update the API key. + properties: + scopes: + type: array + items: + type: string + description: A list of scopes allowed for the API key, e.g. `["api.model.request"]` + api_key.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The tracking ID of the API key. + invite.sent: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the invite. + data: + type: object + description: The payload used to create the invite. + properties: + email: + type: string + description: The email invited to the organization. + role: + type: string + description: The role the email was invited to be. Is either `owner` or `member`. + invite.accepted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the invite. + invite.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the invite. + login.failed: + type: object + description: The details for events with this `type`. + properties: + error_code: + type: string + description: The error code of the failure. + error_message: + type: string + description: The error message of the failure. + logout.failed: + type: object + description: The details for events with this `type`. + properties: + error_code: + type: string + description: The error code of the failure. + error_message: + type: string + description: The error message of the failure. + organization.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The organization ID. + changes_requested: + type: object + description: The payload used to update the organization settings. + properties: + title: + type: string + description: The organization title. + description: + type: string + description: The organization description. + name: + type: string + description: The organization name. + settings: + type: object + properties: + threads_ui_visibility: + type: string + description: Visibility of the threads page which shows messages created with the Assistants API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`. + usage_dashboard_visibility: + type: string + description: Visibility of the usage dashboard which shows activity and costs for your organization. One of `ANY_ROLE` or `OWNERS`. + project.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The project ID. + data: + type: object + description: The payload used to create the project. + properties: + name: + type: string + description: The project name. + title: + type: string + description: The title of the project as seen on the dashboard. + project.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The project ID. + changes_requested: + type: object + description: The payload used to update the project. + properties: + title: + type: string + description: The title of the project as seen on the dashboard. + project.archived: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The project ID. + service_account.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The service account ID. + data: + type: object + description: The payload used to create the service account. + properties: + role: + type: string + description: The role of the service account. Is either `owner` or `member`. + service_account.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The service account ID. + changes_requested: + type: object + description: The payload used to updated the service account. + properties: + role: + type: string + description: The role of the service account. Is either `owner` or `member`. + service_account.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The service account ID. + user.added: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The user ID. + data: + type: object + description: The payload used to add the user to the project. + properties: + role: + type: string + description: The role of the user. Is either `owner` or `member`. + user.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The project ID. + changes_requested: + type: object + description: The payload used to update the user. + properties: + role: + type: string + description: The role of the user. Is either `owner` or `member`. + user.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The user ID. + required: + - id + - type + - effective_at + - actor + x-oaiMeta: + name: The audit log object + example: | + { + "id": "req_xxx_20240101", + "type": "api_key.created", + "effective_at": 1720804090, + "actor": { + "type": "session", + "session": { + "user": { + "id": "user-xxx", + "email": "user@example.com" + }, + "ip_address": "127.0.0.1", + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" + } + }, + "api_key.created": { + "id": "key_xxxx", + "data": { + "scopes": ["resource.operation"] + } + } + } + + ListAuditLogsResponse: + type: object + properties: + object: + type: string + enum: [list] + data: + type: array + items: + $ref: "#/components/schemas/AuditLog" + first_id: + type: string + example: "audit_log-defb456h8dks" + last_id: + type: string + example: "audit_log-hnbkd8s93s" + has_more: + type: boolean + + required: + - object + - data + - first_id + - last_id + - has_more + + Invite: + type: object + description: Represents an individual `invite` to the organization. + properties: + object: + type: string + enum: [organization.invite] + description: The object type, which is always `organization.invite` + id: + type: string + description: The identifier, which can be referenced in API endpoints + email: + type: string + description: The email address of the individual to whom the invite was sent + role: + type: string + enum: [owner, reader] + description: "`owner` or `reader`" + status: + type: string + enum: [accepted, expired, pending] + description: "`accepted`,`expired`, or `pending`" + invited_at: + type: integer + description: The Unix timestamp (in seconds) of when the invite was sent. + expires_at: + type: integer + description: The Unix timestamp (in seconds) of when the invite expires. + accepted_at: + type: integer + description: The Unix timestamp (in seconds) of when the invite was accepted. + + required: + - object + - id + - email + - role + - status + - invited_at + - expires_at + x-oaiMeta: + name: The invite object + example: | + { + "object": "organization.invite", + "id": "invite-abc", + "email": "user@example.com", + "role": "owner", + "status": "accepted", + "invited_at": 1711471533, + "expires_at": 1711471533, + "accepted_at": 1711471533 + } - RunStepStreamEvent: - oneOf: - - type: object - properties: - event: - type: string - enum: ["thread.run.step.created"] - data: - $ref: "#/components/schemas/RunStepObject" - required: - - event - - data - description: Occurs when a [run step](/docs/api-reference/runs/step-object) is created. - x-oaiMeta: - dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" - - type: object - properties: - event: - type: string - enum: ["thread.run.step.in_progress"] - data: - $ref: "#/components/schemas/RunStepObject" - required: - - event - - data - description: Occurs when a [run step](/docs/api-reference/runs/step-object) moves to an `in_progress` state. - x-oaiMeta: - dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" - - type: object - properties: - event: - type: string - enum: ["thread.run.step.delta"] - data: - $ref: "#/components/schemas/RunStepDeltaObject" - required: - - event - - data - description: Occurs when parts of a [run step](/docs/api-reference/runs/step-object) are being streamed. - x-oaiMeta: - dataDescription: "`data` is a [run step delta](/docs/api-reference/assistants-streaming/run-step-delta-object)" - - type: object - properties: - event: - type: string - enum: ["thread.run.step.completed"] - data: - $ref: "#/components/schemas/RunStepObject" - required: - - event - - data - description: Occurs when a [run step](/docs/api-reference/runs/step-object) is completed. - x-oaiMeta: - dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" - - type: object - properties: - event: - type: string - enum: ["thread.run.step.failed"] - data: - $ref: "#/components/schemas/RunStepObject" - required: - - event - - data - description: Occurs when a [run step](/docs/api-reference/runs/step-object) fails. - x-oaiMeta: - dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" - - type: object - properties: - event: - type: string - enum: ["thread.run.step.cancelled"] - data: - $ref: "#/components/schemas/RunStepObject" - required: - - event - - data - description: Occurs when a [run step](/docs/api-reference/runs/step-object) is cancelled. - x-oaiMeta: - dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" - - type: object - properties: - event: - type: string - enum: ["thread.run.step.expired"] - data: - $ref: "#/components/schemas/RunStepObject" - required: - - event - - data - description: Occurs when a [run step](/docs/api-reference/runs/step-object) expires. - x-oaiMeta: - dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + InviteListResponse: + type: object + properties: + object: + type: string + enum: [list] + description: The object type, which is always `list` + data: + type: array + items: + $ref: '#/components/schemas/Invite' + first_id: + type: string + description: The first `invite_id` in the retrieved `list` + last_id: + type: string + description: The last `invite_id` in the retrieved `list` + has_more: + type: boolean + description: The `has_more` property is used for pagination to indicate there are additional results. + required: + - object + - data - MessageStreamEvent: - oneOf: - - type: object - properties: - event: - type: string - enum: ["thread.message.created"] - data: - $ref: "#/components/schemas/MessageObject" - required: - - event - - data - description: Occurs when a [message](/docs/api-reference/messages/object) is created. - x-oaiMeta: - dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" - - type: object - properties: - event: - type: string - enum: ["thread.message.in_progress"] - data: - $ref: "#/components/schemas/MessageObject" - required: - - event - - data - description: Occurs when a [message](/docs/api-reference/messages/object) moves to an `in_progress` state. - x-oaiMeta: - dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" - - type: object - properties: - event: - type: string - enum: ["thread.message.delta"] - data: - $ref: "#/components/schemas/MessageDeltaObject" - required: - - event - - data - description: Occurs when parts of a [Message](/docs/api-reference/messages/object) are being streamed. - x-oaiMeta: - dataDescription: "`data` is a [message delta](/docs/api-reference/assistants-streaming/message-delta-object)" - - type: object - properties: - event: - type: string - enum: ["thread.message.completed"] - data: - $ref: "#/components/schemas/MessageObject" - required: - - event - - data - description: Occurs when a [message](/docs/api-reference/messages/object) is completed. - x-oaiMeta: - dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" - - type: object - properties: - event: - type: string - enum: ["thread.message.incomplete"] - data: - $ref: "#/components/schemas/MessageObject" - required: - - event - - data - description: Occurs when a [message](/docs/api-reference/messages/object) ends before it is completed. - x-oaiMeta: - dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" + InviteRequest: + type: object + properties: + email: + type: string + description: "Send an email to this address" + role: + type: string + enum: [reader, owner] + description: "`owner` or `reader`" + required: + - email + - role + + InviteDeleteResponse: + type: object + properties: + object: + type: string + enum: [organization.invite.deleted] + description: The object type, which is always `organization.invite.deleted` + id: + type: string + deleted: + type: boolean + required: + - object + - id + - deleted + + User: + type: object + description: Represents an individual `user` within an organization. + properties: + object: + type: string + enum: [organization.user] + description: The object type, which is always `organization.user` + id: + type: string + description: The identifier, which can be referenced in API endpoints + name: + type: string + description: The name of the user + email: + type: string + description: The email address of the user + role: + type: string + enum: [owner, reader] + description: "`owner` or `reader`" + added_at: + type: integer + description: The Unix timestamp (in seconds) of when the user was added. + required: + - object + - id + - name + - email + - role + - added_at + x-oaiMeta: + name: The user object + example: | + { + "object": "organization.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + + UserListResponse: + type: object + properties: + object: + type: string + enum: [list] + data: + type: array + items: + $ref: '#/components/schemas/User' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + required: + - object + - data + - first_id + - last_id + - has_more + + UserRoleUpdateRequest: + type: object + properties: + role: + type: string + enum: [owner,reader] + description: "`owner` or `reader`" + required: + - role + + UserDeleteResponse: + type: object + properties: + object: + type: string + enum: [organization.user.deleted] + id: + type: string + deleted: + type: boolean + required: + - object + - id + - deleted - ErrorEvent: + Project: type: object + description: Represents an individual project. properties: - event: + id: type: string - enum: ["error"] + description: The identifier, which can be referenced in API endpoints + object: + type: string + enum: [organization.project] + description: The object type, which is always `organization.project` + name: + type: string + description: The name of the project. This appears in reporting. + created_at: + type: integer + description: The Unix timestamp (in seconds) of when the project was created. + archived_at: + type: integer + nullable: true + description: The Unix timestamp (in seconds) of when the project was archived or `null`. + status: + type: string + enum: [active, archived] + description: "`active` or `archived`" + required: + - id + - object + - name + - created_at + - status + x-oaiMeta: + name: The project object + example: | + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project example", + "created_at": 1711471533, + "archived_at": null, + "status": "active" + } + + ProjectListResponse: + type: object + properties: + object: + type: string + enum: [list] data: - $ref: "#/components/schemas/Error" + type: array + items: + $ref: '#/components/schemas/Project' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean required: - - event + - object - data - description: Occurs when an [error](/docs/guides/error-codes/api-errors) occurs. This can happen due to an internal server error or a timeout. + - first_id + - last_id + - has_more + + ProjectCreateRequest: + type: object + properties: + name: + type: string + description: The friendly name of the project, this name appears in reports. + required: + - name + + ProjectUpdateRequest: + type: object + properties: + name: + type: string + description: The updated name of the project, this name appears in reports. + required: + - name + + DefaultProjectErrorResponse: + type: object + properties: + code: + type: integer + message: + type: string + required: + - code + - message + + ProjectUser: + type: object + description: Represents an individual user in a project. + properties: + object: + type: string + enum: [organization.project.user] + description: The object type, which is always `organization.project.user` + id: + type: string + description: The identifier, which can be referenced in API endpoints + name: + type: string + description: The name of the user + email: + type: string + description: The email address of the user + role: + type: string + enum: [owner, member] + description: "`owner` or `member`" + added_at: + type: integer + description: The Unix timestamp (in seconds) of when the project was added. + + required: + - object + - id + - name + - email + - role + - added_at x-oaiMeta: - dataDescription: "`data` is an [error](/docs/guides/error-codes/api-errors)" + name: The project user object + example: | + { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } - DoneEvent: + ProjectUserListResponse: type: object properties: - event: + object: type: string - enum: ["done"] data: + type: array + items: + $ref: '#/components/schemas/ProjectUser' + first_id: type: string - enum: ["[DONE]"] + last_id: + type: string + has_more: + type: boolean required: - - event + - object - data - description: Occurs when a stream ends. - x-oaiMeta: - dataDescription: "`data` is `[DONE]`" + - first_id + - last_id + - has_more - Batch: + ProjectUserCreateRequest: type: object properties: - id: + user_id: type: string - object: + description: The ID of the user. + role: type: string - enum: [batch] - description: The object type, which is always `batch`. - endpoint: + enum: [owner, member] + description: "`owner` or `member`" + required: + - user_id + - role + + ProjectUserUpdateRequest: + type: object + properties: + role: type: string - description: The OpenAI API endpoint used by the batch. + enum: [owner, member] + description: "`owner` or `member`" + required: + - role - errors: - type: object - properties: - object: - type: string - description: The object type, which is always `list`. - data: - type: array - items: - type: object - properties: - code: - type: string - description: An error code identifying the error type. - message: - type: string - description: A human-readable message providing more details about the error. - param: - type: string - description: The name of the parameter that caused the error, if applicable. - nullable: true - line: - type: integer - description: The line number of the input file where the error occurred, if applicable. - nullable: true - input_file_id: + ProjectUserDeleteResponse: + type: object + properties: + object: type: string - description: The ID of the input file for the batch. - completion_window: + enum: [organization.project.user.deleted] + id: type: string - description: The time frame within which the batch should be processed. - status: + deleted: + type: boolean + required: + - object + - id + - deleted + + ProjectServiceAccount: + type: object + description: Represents an individual service account in a project. + properties: + object: type: string - description: The current status of the batch. - enum: - - validating - - failed - - in_progress - - finalizing - - completed - - expired - - cancelling - - cancelled - output_file_id: + enum: [organization.project.service_account] + description: The object type, which is always `organization.project.service_account` + id: type: string - description: The ID of the file containing the outputs of successfully executed requests. - error_file_id: + description: The identifier, which can be referenced in API endpoints + name: type: string - description: The ID of the file containing the outputs of requests with errors. + description: The name of the service account + role: + type: string + enum: [owner, member] + description: "`owner` or `member`" created_at: type: integer - description: The Unix timestamp (in seconds) for when the batch was created. - in_progress_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch started processing. - expires_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch will expire. - finalizing_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch started finalizing. - completed_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch was completed. - failed_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch failed. - expired_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch expired. - cancelling_at: - type: integer - description: The Unix timestamp (in seconds) for when the batch started cancelling. - cancelled_at: + description: The Unix timestamp (in seconds) of when the service account was created + required: + - object + - id + - name + - role + - created_at + x-oaiMeta: + name: The project service account object + example: | + { + "object": "organization.project.service_account", + "id": "svc_acct_abc", + "name": "Service Account", + "role": "owner", + "created_at": 1711471533 + } + + ProjectServiceAccountListResponse: + type: object + properties: + object: + type: string + enum: [list] + data: + type: array + items: + $ref: '#/components/schemas/ProjectServiceAccount' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + required: + - object + - data + - first_id + - last_id + - has_more + + ProjectServiceAccountCreateRequest: + type: object + properties: + name: + type: string + description: The name of the service account being created. + required: + - name + + ProjectServiceAccountCreateResponse: + type: object + properties: + object: + type: string + enum: [organization.project.service_account] + id: + type: string + name: + type: string + role: + type: string + enum: [member] + description: Service accounts can only have one role of type `member` + created_at: type: integer - description: The Unix timestamp (in seconds) for when the batch was cancelled. - request_counts: - type: object - properties: - total: - type: integer - description: Total number of requests in the batch. - completed: - type: integer - description: Number of requests that have been completed successfully. - failed: - type: integer - description: Number of requests that have failed. - required: - - total - - completed - - failed - description: The request counts for different statuses within the batch. - metadata: - description: *metadata_description - type: object - x-oaiTypeLabel: map - nullable: true + api_key: + $ref: '#/components/schemas/ProjectServiceAccountApiKey' required: - - id - object - - endpoint - - input_file_id - - completion_window - - status + - id + - name + - role - created_at - x-oaiMeta: - name: The batch object - example: *batch_object + - api_key - BatchRequestInput: + ProjectServiceAccountApiKey: type: object - description: The per-line object of the batch input file properties: - custom_id: + object: type: string - description: A developer-provided per-request id that will be used to match outputs to inputs. Must be unique for each request in a batch. - method: + enum: [organization.project.service_account.api_key] + description: The object type, which is always `organization.project.service_account.api_key` + + value: type: string - enum: ["POST"] - description: The HTTP method to be used for the request. Currently only `POST` is supported. - url: + name: type: string - description: The OpenAI API relative URL to be used for the request. Currently `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. - x-oaiMeta: - name: The request input object - example: | - {"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-3.5-turbo", "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is 2+2?"}]}} + created_at: + type: integer + id: + type: string + required: + - object + - value + - name + - created_at + - id - BatchRequestOutput: + ProjectServiceAccountDeleteResponse: type: object - description: The per-line object of the batch output and error files properties: + object: + type: string + enum: [organization.project.service_account.deleted] id: type: string - custom_id: + deleted: + type: boolean + required: + - object + - id + - deleted + + ProjectApiKey: + type: object + description: Represents an individual API key in a project. + properties: + object: type: string - description: A developer-provided per-request id that will be used to match outputs to inputs. - response: - type: object - nullable: true - properties: - status_code: - type: integer - description: The HTTP status code of the response - request_id: - type: string - description: An unique identifier for the OpenAI API request. Please include this request ID when contacting support. - body: - type: object - x-oaiTypeLabel: map - description: The JSON body of the response - error: + enum: [organization.project.api_key] + description: The object type, which is always `organization.project.api_key` + redacted_value: + type: string + description: The redacted value of the API key + name: + type: string + description: The name of the API key + created_at: + type: integer + description: The Unix timestamp (in seconds) of when the API key was created + id: + type: string + description: The identifier, which can be referenced in API endpoints + owner: type: object - nullable: true - description: For requests that failed with a non-HTTP error, this will contain more information on the cause of the failure. properties: - code: - type: string - description: A machine-readable error code. - message: + type: type: string - description: A human-readable error message. + enum: [user, service_account] + description: "`user` or `service_account`" + user: + $ref: '#/components/schemas/ProjectUser' + service_account: + $ref: '#/components/schemas/ProjectServiceAccount' + required: + - object + - redacted_value + - name + - created_at + - id + - owner x-oaiMeta: - name: The request output object + name: The project API key object example: | - {"id": "batch_req_wnaDys", "custom_id": "request-2", "response": {"status_code": 200, "request_id": "req_c187b3", "body": {"id": "chatcmpl-9758Iw", "object": "chat.completion", "created": 1711475054, "model": "gpt-3.5-turbo", "choices": [{"index": 0, "message": {"role": "assistant", "content": "2 + 2 equals 4."}, "finish_reason": "stop"}], "usage": {"prompt_tokens": 24, "completion_tokens": 15, "total_tokens": 39}, "system_fingerprint": null}}, "error": null} + { + "object": "organization.project.api_key", + "redacted_value": "sk-abc...def", + "name": "My API Key", + "created_at": 1711471533, + "id": "key_abc", + "owner": { + "type": "user", + "user": { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + } + } - ListBatchesResponse: + ProjectApiKeyListResponse: type: object properties: + object: + type: string + enum: [list] data: type: array items: - $ref: "#/components/schemas/Batch" + $ref: '#/components/schemas/ProjectApiKey' first_id: type: string - example: "batch_abc123" last_id: type: string - example: "batch_abc456" has_more: type: boolean - object: - type: string - enum: [list] required: - object - data + - first_id + - last_id - has_more + ProjectApiKeyDeleteResponse: + type: object + properties: + object: + type: string + enum: [organization.project.api_key.deleted] + id: + type: string + deleted: + type: boolean + required: + - object + - id + - deleted + security: - ApiKeyAuth: [] @@ -13381,6 +16410,8 @@ x-oaiMeta: title: Endpoints - id: assistants title: Assistants + - id: administration + title: Administration - id: legacy title: Legacy groups: @@ -13553,6 +16584,30 @@ x-oaiMeta: - type: object key: OpenAIFile path: object + - id: uploads + title: Uploads + description: | + Allows you to upload large files in multiple parts. + navigationGroup: endpoints + sections: + - type: endpoint + key: createUpload + path: create + - type: endpoint + key: addUploadPart + path: add-part + - type: endpoint + key: completeUpload + path: complete + - type: endpoint + key: cancelUpload + path: cancel + - type: object + key: Upload + path: object + - type: object + key: UploadPart + path: part-object - id: images title: Images description: | @@ -13605,6 +16660,8 @@ x-oaiMeta: - type: object key: CreateModerationResponse path: object + + - id: assistants title: Assistants beta: true @@ -13832,6 +16889,175 @@ x-oaiMeta: - type: object key: AssistantStreamEvent path: events + + - id: administration + title: Overview + description: | + Programmatically manage your organization. + + The Audit Logs endpoint provides a log of all actions taken in the + organization for security and monitoring purposes. + + To access these endpoints please generate an Admin API Key through the [API Platform Organization overview](/organization/admin-keys). Admin API keys cannot be used for non-administration endpoints. + + For best practices on setting up your organization, please refer to this [guide](/docs/guides/production-best-practices/setting-up-your-organization) + navigationGroup: administration + + - id: invite + title: Invites + description: Invite and manage invitations for an organization. Invited users are automatically added to the Default project. + navigationGroup: administration + sections: + - type: endpoint + key: list-invites + path: list + - type: endpoint + key: inviteUser + path: create + - type: endpoint + key: retrieve-invite + path: retrieve + - type: endpoint + key: delete-invite + path: delete + - type: object + key: Invite + path: object + + - id: users + title: Users + description: | + Manage users and their role in an organization. Users will be automatically added to the Default project. + navigationGroup: administration + sections: + - type: endpoint + key: list-users + path: list + - type: endpoint + key: modify-user + path: modify + - type: endpoint + key: retrieve-user + path: retrieve + - type: endpoint + key: delete-user + path: delete + - type: object + key: User + path: object + + - id: projects + title: Projects + description: | + Manage the projects within an orgnanization includes creation, updating, and archiving or projects. + The Default project cannot be modified or archived. + navigationGroup: administration + sections: + - type: endpoint + key: list-projects + path: list + - type: endpoint + key: create-project + path: create + - type: endpoint + key: retrieve-project + path: retrieve + - type: endpoint + key: modify-project + path: modify + - type: endpoint + key: archive-project + path: archive + - type: object + key: Project + path: object + + - id: project-users + title: Project Users + description: | + Manage users within a project, including adding, updating roles, and removing users. + Users cannot be removed from the Default project, unless they are being removed from the organization. + navigationGroup: administration + sections: + - type: endpoint + key: list-project-users + path: list + - type: endpoint + key: create-project-user + path: creeate + - type: endpoint + key: retrieve-project-user + path: retrieve + - type: endpoint + key: modify-project-user + path: modify + - type: endpoint + key: delete-project-user + path: delete + - type: object + key: ProjectUser + path: object + + - id: project-service-accounts + title: Project Service Accounts + description: | + Manage service accounts within a project. A service account is a bot user that is not associated with a user. + If a user leaves an organization, their keys and membership in projects will no longer work. Service accounts + do not have this limitation. However, service accounts can also be deleted from a project. + navigationGroup: administration + sections: + - type: endpoint + key: list-project-service-accounts + path: list + - type: endpoint + key: create-project-service-account + path: create + - type: endpoint + key: retrieve-project-service-account + path: retrieve + - type: endpoint + key: delete-project-service-account + path: delete + - type: object + key: ProjectServiceAccount + path: object + + - id: project-api-keys + title: Project API Keys + description: | + Manage API keys for a given project. Supports listing and deleting keys for users. + This API does not allow issuing keys for users, as users need to authorize themselves to generate keys. + navigationGroup: administration + sections: + - type: endpoint + key: list-project-api-keys + path: list + - type: endpoint + key: retrieve-project-api-key + path: retrieve + - type: endpoint + key: delete-project-api-key + path: delete + - type: object + key: ProjectApiKey + path: object + + - id: audit-logs + title: Audit Logs + description: | + Logs of user actions and configuration changes within this organization. + + To log events, you must activate logging in the [Organization Settings](/settings/organization/general). + Once activated, for security reasons, logging cannot be deactivated. + navigationGroup: administration + sections: + - type: endpoint + key: list-audit-logs + path: list + - type: object + key: AuditLog + path: object + - id: completions title: Completions legacy: true