MyApp

<back to all web services

ChatCompletion

AI

Chat Completions API (OpenAI-Compatible)

The following routes are available for this service:
POST/v1/chat/completions
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using ServiceStack;
using ServiceStack.DataAnnotations;
using ServiceStack.AI;

namespace ServiceStack.AI
{
    ///<summary>
    ///Parameters for audio output. Required when audio output is requested with modalities: [audio]
    ///</summary>
    [DataContract]
    public partial class AiChatAudio
    {
        ///<summary>
        ///Specifies the output audio format. Must be one of wav, mp3, flac, opus, or pcm16.
        ///</summary>
        [DataMember(Name="format")]
        public virtual string Format { get; set; }

        ///<summary>
        ///The voice the model uses to respond. Supported voices are alloy, ash, ballad, coral, echo, fable, nova, onyx, sage, and shimmer.
        ///</summary>
        [DataMember(Name="voice")]
        public virtual string Voice { get; set; }
    }

    ///<summary>
    ///Usage statistics for the completion request.
    ///</summary>
    [DataContract]
    public partial class AiCompletionUsage
    {
        ///<summary>
        ///When using Predicted Outputs, the number of tokens in the prediction that appeared in the completion.
        ///</summary>
        [DataMember(Name="accepted_prediction_tokens")]
        public virtual int AcceptedPredictionTokens { get; set; }

        ///<summary>
        ///Audio input tokens generated by the model.
        ///</summary>
        [DataMember(Name="audio_tokens")]
        public virtual int AudioTokens { get; set; }

        ///<summary>
        ///Tokens generated by the model for reasoning.
        ///</summary>
        [DataMember(Name="reasoning_tokens")]
        public virtual int ReasoningTokens { get; set; }

        ///<summary>
        ///When using Predicted Outputs, the number of tokens in the prediction that did not appear in the completion.
        ///</summary>
        [DataMember(Name="rejected_prediction_tokens")]
        public virtual int RejectedPredictionTokens { get; set; }
    }

    [DataContract]
    public partial class AiContent
    {
        ///<summary>
        ///The type of the content part.
        ///</summary>
        [DataMember(Name="type")]
        public virtual string Type { get; set; }
    }

    ///<summary>
    ///A list of messages comprising the conversation so far.
    ///</summary>
    [DataContract]
    public partial class AiMessage
    {
        ///<summary>
        ///The contents of the message.
        ///</summary>
        [DataMember(Name="content")]
        public virtual List<AiContent>? Content { get; set; }

        ///<summary>
        ///The role of the author of this message. Valid values are `system`, `user`, `assistant` and `tool`.
        ///</summary>
        [DataMember(Name="role")]
        public virtual string Role { get; set; }

        ///<summary>
        ///An optional name for the participant. Provides the model information to differentiate between participants of the same role.
        ///</summary>
        [DataMember(Name="name")]
        public virtual string? Name { get; set; }

        ///<summary>
        ///The tool calls generated by the model, such as function calls.
        ///</summary>
        [DataMember(Name="tool_calls")]
        public virtual List<ToolCall>? ToolCalls { get; set; }

        ///<summary>
        ///Tool call that this message is responding to.
        ///</summary>
        [DataMember(Name="tool_call_id")]
        public virtual string? ToolCallId { get; set; }
    }

    ///<summary>
    ///Breakdown of tokens used in the prompt.
    ///</summary>
    [DataContract]
    public partial class AiPromptUsage
    {
        ///<summary>
        ///When using Predicted Outputs, the number of tokens in the prediction that appeared in the completion.
        ///</summary>
        [DataMember(Name="accepted_prediction_tokens")]
        public virtual int AcceptedPredictionTokens { get; set; }

        ///<summary>
        ///Audio input tokens present in the prompt.
        ///</summary>
        [DataMember(Name="audio_tokens")]
        public virtual int AudioTokens { get; set; }

        ///<summary>
        ///Cached tokens present in the prompt.
        ///</summary>
        [DataMember(Name="cached_tokens")]
        public virtual int CachedTokens { get; set; }
    }

    [DataContract]
    public partial class AiResponseFormat
    {
        ///<summary>
        ///An object specifying the format that the model must output. Compatible with GPT-4 Turbo and all GPT-3.5 Turbo models newer than gpt-3.5-turbo-1106.
        ///</summary>
        [DataMember(Name="response_format")]
        public virtual ResponseFormat Type { get; set; }
    }

    ///<summary>
    ///Usage statistics for the completion request.
    ///</summary>
    [DataContract]
    public partial class AiUsage
    {
        ///<summary>
        ///Number of tokens in the generated completion.
        ///</summary>
        [DataMember(Name="completion_tokens")]
        public virtual int CompletionTokens { get; set; }

        ///<summary>
        ///Number of tokens in the prompt.
        ///</summary>
        [DataMember(Name="prompt_tokens")]
        public virtual int PromptTokens { get; set; }

        ///<summary>
        ///Total number of tokens used in the request (prompt + completion).
        ///</summary>
        [DataMember(Name="total_tokens")]
        public virtual int TotalTokens { get; set; }

        ///<summary>
        ///Breakdown of tokens used in a completion.
        ///</summary>
        [DataMember(Name="completion_tokens_details")]
        public virtual AiCompletionUsage? CompletionTokensDetails { get; set; }

        ///<summary>
        ///Breakdown of tokens used in the prompt.
        ///</summary>
        [DataMember(Name="prompt_tokens_details")]
        public virtual AiPromptUsage? PromptTokensDetails { get; set; }
    }

    ///<summary>
    ///Chat Completions API (OpenAI-Compatible)
    ///</summary>
    [DataContract]
    public partial class ChatCompletion
        : IPost
    {
        ///<summary>
        ///The messages to generate chat completions for.
        ///</summary>
        [DataMember(Name="messages")]
        public virtual List<AiMessage> Messages { get; set; } = [];

        ///<summary>
        ///ID of the model to use. See the model endpoint compatibility table for details on which models work with the Chat API
        ///</summary>
        [DataMember(Name="model")]
        public virtual string Model { get; set; }

        ///<summary>
        ///Parameters for audio output. Required when audio output is requested with modalities: [audio]
        ///</summary>
        [DataMember(Name="audio")]
        public virtual AiChatAudio? Audio { get; set; }

        ///<summary>
        ///Modify the likelihood of specified tokens appearing in the completion.
        ///</summary>
        [DataMember(Name="logit_bias")]
        public virtual Dictionary<int, int>? LogitBias { get; set; }

        ///<summary>
        ///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.
        ///</summary>
        [DataMember(Name="metadata")]
        public virtual Dictionary<string, string>? Metadata { get; set; }

        ///<summary>
        ///Constrains effort on reasoning for reasoning models. Currently supported values are minimal, low, medium, and high (none, default). Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response.
        ///</summary>
        [DataMember(Name="reasoning_effort")]
        public virtual string? ReasoningEffort { get; set; }

        ///<summary>
        ///An object specifying the format that the model must output. Compatible with GPT-4 Turbo and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting Type to ResponseFormat.JsonObject enables JSON mode, which guarantees the message the model generates is valid JSON.
        ///</summary>
        [DataMember(Name="response_format")]
        public virtual AiResponseFormat? ResponseFormat { get; set; }

        ///<summary>
        ///Specifies the processing type used for serving the request.
        ///</summary>
        [DataMember(Name="service_tier")]
        public virtual string? ServiceTier { get; set; }

        ///<summary>
        ///A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies. The IDs should be a string that uniquely identifies each user.
        ///</summary>
        [DataMember(Name="safety_identifier")]
        public virtual string? SafetyIdentifier { get; set; }

        ///<summary>
        ///Up to 4 sequences where the API will stop generating further tokens.
        ///</summary>
        [DataMember(Name="stop")]
        public virtual List<string>? Stop { get; set; }

        ///<summary>
        ///Output types that you would like the model to generate. Most models are capable of generating text, which is the default:
        ///</summary>
        [DataMember(Name="modalities")]
        public virtual List<string>? Modalities { get; set; }

        ///<summary>
        ///Used by OpenAI to cache responses for similar requests to optimize your cache hit rates.
        ///</summary>
        [DataMember(Name="prompt_cache_key")]
        public virtual string? PromptCacheKey { get; set; }

        ///<summary>
        ///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.
        ///</summary>
        [DataMember(Name="tools")]
        public virtual List<Tool>? Tools { get; set; }

        ///<summary>
        ///Constrains the verbosity of the model's response. Lower values will result in more concise responses, while higher values will result in more verbose responses. Currently supported values are low, medium, and high.
        ///</summary>
        [DataMember(Name="verbosity")]
        public virtual string? Verbosity { get; set; }

        ///<summary>
        ///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.
        ///</summary>
        [DataMember(Name="temperature")]
        public virtual double? Temperature { get; set; }

        ///<summary>
        ///An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and reasoning tokens.
        ///</summary>
        [DataMember(Name="max_completion_tokens")]
        public virtual int? MaxCompletionTokens { get; set; }

        ///<summary>
        ///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.
        ///</summary>
        [DataMember(Name="top_logprobs")]
        public virtual int? TopLogprobs { get; set; }

        ///<summary>
        ///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.
        ///</summary>
        [DataMember(Name="top_p")]
        public virtual double? TopP { get; set; }

        ///<summary>
        ///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.
        ///</summary>
        [DataMember(Name="frequency_penalty")]
        public virtual double? FrequencyPenalty { get; set; }

        ///<summary>
        ///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.
        ///</summary>
        [DataMember(Name="presence_penalty")]
        public virtual double? PresencePenalty { get; set; }

        ///<summary>
        ///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.
        ///</summary>
        [DataMember(Name="seed")]
        public virtual int? Seed { get; set; }

        ///<summary>
        ///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.
        ///</summary>
        [DataMember(Name="n")]
        public virtual int? N { get; set; }

        ///<summary>
        ///Whether or not to store the output of this chat completion request for use in our model distillation or evals products.
        ///</summary>
        [DataMember(Name="store")]
        public virtual bool? Store { get; set; }

        ///<summary>
        ///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.
        ///</summary>
        [DataMember(Name="logprobs")]
        public virtual bool? Logprobs { get; set; }

        ///<summary>
        ///Whether to enable parallel function calling during tool use.
        ///</summary>
        [DataMember(Name="parallel_tool_calls")]
        public virtual bool? ParallelToolCalls { get; set; }

        ///<summary>
        ///Whether to enable thinking mode for some Qwen models and providers.
        ///</summary>
        [DataMember(Name="enable_thinking")]
        public virtual bool? EnableThinking { get; set; }

        ///<summary>
        ///If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a `data: [DONE]` message.
        ///</summary>
        [DataMember(Name="stream")]
        public virtual bool? Stream { get; set; }
    }

    [DataContract]
    public partial class ChatResponse
    {
        ///<summary>
        ///A unique identifier for the chat completion.
        ///</summary>
        [DataMember(Name="id")]
        public virtual string Id { get; set; }

        ///<summary>
        ///A list of chat completion choices. Can be more than one if n is greater than 1.
        ///</summary>
        [DataMember(Name="choices")]
        public virtual List<Choice> Choices { get; set; } = [];

        ///<summary>
        ///The Unix timestamp (in seconds) of when the chat completion was created.
        ///</summary>
        [DataMember(Name="created")]
        public virtual long Created { get; set; }

        ///<summary>
        ///The model used for the chat completion.
        ///</summary>
        [DataMember(Name="model")]
        public virtual string Model { get; set; }

        ///<summary>
        ///This fingerprint represents the backend configuration that the model runs with.
        ///</summary>
        [DataMember(Name="system_fingerprint")]
        public virtual string? SystemFingerprint { get; set; }

        ///<summary>
        ///The object type, which is always chat.completion.
        ///</summary>
        [DataMember(Name="object")]
        public virtual string Object { get; set; }

        ///<summary>
        ///Specifies the processing type used for serving the request.
        ///</summary>
        [DataMember(Name="service_tier")]
        public virtual string? ServiceTier { get; set; }

        ///<summary>
        ///Usage statistics for the completion request.
        ///</summary>
        [DataMember(Name="usage")]
        public virtual AiUsage Usage { get; set; }

        ///<summary>
        ///The provider used for the chat completion.
        ///</summary>
        [DataMember(Name="provider")]
        public virtual string? Provider { get; set; }

        ///<summary>
        ///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.
        ///</summary>
        [DataMember(Name="metadata")]
        public virtual Dictionary<string, string>? Metadata { get; set; }

        [DataMember(Name="responseStatus")]
        public virtual ResponseStatus? ResponseStatus { get; set; }
    }

    [DataContract]
    public partial class Choice
    {
        ///<summary>
        ///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
        ///</summary>
        [DataMember(Name="finish_reason")]
        public virtual string FinishReason { get; set; }

        ///<summary>
        ///The index of the choice in the list of choices.
        ///</summary>
        [DataMember(Name="index")]
        public virtual int Index { get; set; }

        ///<summary>
        ///A chat completion message generated by the model.
        ///</summary>
        [DataMember(Name="message")]
        public virtual ChoiceMessage Message { get; set; }
    }

    ///<summary>
    ///Annotations for the message, when applicable, as when using the web search tool.
    ///</summary>
    [DataContract]
    public partial class ChoiceAnnotation
    {
        ///<summary>
        ///The type of the URL citation. Always url_citation.
        ///</summary>
        [DataMember(Name="type")]
        public virtual string Type { get; set; }

        ///<summary>
        ///A URL citation when using web search.
        ///</summary>
        [DataMember(Name="url_citation")]
        public virtual UrlCitation UrlCitation { get; set; }
    }

    ///<summary>
    ///If the audio output modality is requested, this object contains data about the audio response from the model.
    ///</summary>
    [DataContract]
    public partial class ChoiceAudio
    {
        ///<summary>
        ///Base64 encoded audio bytes generated by the model, in the format specified in the request.
        ///</summary>
        [DataMember(Name="data")]
        public virtual string Data { get; set; }

        ///<summary>
        ///The Unix timestamp (in seconds) for when this audio response will no longer be accessible on the server for use in multi-turn conversations.
        ///</summary>
        [DataMember(Name="expires_at")]
        public virtual int ExpiresAt { get; set; }

        ///<summary>
        ///Unique identifier for this audio response.
        ///</summary>
        [DataMember(Name="id")]
        public virtual string Id { get; set; }

        ///<summary>
        ///Transcript of the audio generated by the model.
        ///</summary>
        [DataMember(Name="transcript")]
        public virtual string Transcript { get; set; }
    }

    [DataContract]
    public partial class ChoiceMessage
    {
        ///<summary>
        ///The contents of the message.
        ///</summary>
        [DataMember(Name="content")]
        public virtual string Content { get; set; }

        ///<summary>
        ///The refusal message generated by the model.
        ///</summary>
        [DataMember(Name="refusal")]
        public virtual string? Refusal { get; set; }

        ///<summary>
        ///The reasoning process used by the model.
        ///</summary>
        [DataMember(Name="reasoning")]
        public virtual string? Reasoning { get; set; }

        ///<summary>
        ///The role of the author of this message.
        ///</summary>
        [DataMember(Name="role")]
        public virtual string Role { get; set; }

        ///<summary>
        ///Annotations for the message, when applicable, as when using the web search tool.
        ///</summary>
        [DataMember(Name="annotations")]
        public virtual List<ChoiceAnnotation>? Annotations { get; set; }

        ///<summary>
        ///If the audio output modality is requested, this object contains data about the audio response from the model.
        ///</summary>
        [DataMember(Name="audio")]
        public virtual ChoiceAudio? Audio { get; set; }

        ///<summary>
        ///The tool calls generated by the model, such as function calls.
        ///</summary>
        [DataMember(Name="tool_calls")]
        public virtual List<ToolCall>? ToolCalls { get; set; }
    }

    public enum ResponseFormat
    {
        [EnumMember(Value="text")]
        Text,
        [EnumMember(Value="json_object")]
        JsonObject,
    }

    [DataContract]
    public partial class Tool
    {
        ///<summary>
        ///The type of the tool. Currently, only function is supported.
        ///</summary>
        [DataMember(Name="type")]
        public virtual ToolType Type { get; set; }
    }

    ///<summary>
    ///The tool calls generated by the model, such as function calls.
    ///</summary>
    [DataContract]
    public partial class ToolCall
    {
        ///<summary>
        ///The ID of the tool call.
        ///</summary>
        [DataMember(Name="id")]
        public virtual string Id { get; set; }

        ///<summary>
        ///The type of the tool. Currently, only `function` is supported.
        ///</summary>
        [DataMember(Name="type")]
        public virtual string Type { get; set; }

        ///<summary>
        ///The function that the model called.
        ///</summary>
        [DataMember(Name="function")]
        public virtual string Function { get; set; }
    }

    public enum ToolType
    {
        [EnumMember(Value="function")]
        Function,
    }

    ///<summary>
    ///Annotations for the message, when applicable, as when using the web search tool.
    ///</summary>
    [DataContract]
    public partial class UrlCitation
    {
        ///<summary>
        ///The index of the last character of the URL citation in the message.
        ///</summary>
        [DataMember(Name="end_index")]
        public virtual int EndIndex { get; set; }

        ///<summary>
        ///The index of the first character of the URL citation in the message.
        ///</summary>
        [DataMember(Name="start_index")]
        public virtual int StartIndex { get; set; }

        ///<summary>
        ///The title of the web resource.
        ///</summary>
        [DataMember(Name="title")]
        public virtual string Title { get; set; }

        ///<summary>
        ///The URL of the web resource.
        ///</summary>
        [DataMember(Name="url")]
        public virtual string Url { get; set; }
    }

}

C# ChatCompletion DTOs

To override the Content-type in your clients, use the HTTP Accept Header, append the .csv suffix or ?format=csv

HTTP + CSV

The following are sample HTTP requests and responses. The placeholders shown need to be replaced with actual values.

POST /v1/chat/completions HTTP/1.1 
Host: blazor-vue.web-templates.io 
Accept: text/csv
Content-Type: text/csv
Content-Length: length

{"messages":[{"content":[{}],"role":"String","name":"String","tool_calls":[{"id":"String","type":"String","function":"String"}],"tool_call_id":"String"}],"model":"String","audio":{"format":"String","voice":"String"},"logit_bias":{"0":0},"metadata":{"String":"String"},"reasoning_effort":"String","response_format":{"response_format":"text"},"service_tier":"String","safety_identifier":"String","stop":["String"],"modalities":["String"],"prompt_cache_key":"String","tools":[{"type":"function"}],"verbosity":"String","temperature":0,"max_completion_tokens":0,"top_logprobs":0,"top_p":0,"frequency_penalty":0,"presence_penalty":0,"seed":0,"n":0,"store":false,"logprobs":false,"parallel_tool_calls":false,"enable_thinking":false,"stream":false}
HTTP/1.1 200 OK
Content-Type: text/csv
Content-Length: length

{"id":"String","choices":[{"finish_reason":"String","index":0,"message":{"content":"String","refusal":"String","reasoning":"String","role":"String","annotations":[{"type":"String","url_citation":{"end_index":0,"start_index":0,"title":"String","url":"String"}}],"audio":{"data":"String","expires_at":0,"id":"String","transcript":"String"},"tool_calls":[{"id":"String","type":"String","function":"String"}]}}],"created":0,"model":"String","system_fingerprint":"String","object":"String","service_tier":"String","usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"cached_tokens":0}},"provider":"String","metadata":{"String":"String"},"responseStatus":{"errorCode":"String","message":"String","stackTrace":"String","errors":[{"errorCode":"String","fieldName":"String","message":"String","meta":{"String":"String"}}],"meta":{"String":"String"}}}