Skip to content
  • Auto
  • Light
  • Dark

Create

Creates a model response for the given chat conversation.
chat.completions.create(CompletionCreateParams**kwargs) -> idstrchoiceslistcreatedintmodelstrobjectliteralusageCompletionUsageCompletionCreateResponse
post/chat/completions

Creates a model response for the given chat conversation.

Parameters
messagesiterable

A list of messages comprising the conversation so far.

Hide ParametersShow Parameters
MessageChatCompletionRequestSystemMessageclass

System-provided instructions that the model should follow, regardless of messages sent by the user.

Hide ParametersShow Parameters
contentunion
Union[str, List[str]]

The contents of the system message.

Hide ParametersShow Parameters
MessageChatCompletionRequestSystemMessageContentTextContenttype
str

The contents of the system message.

MessageChatCompletionRequestSystemMessageContentArrayOfContentPartstype
List[str]

An array of content parts with a defined type. For system messages, only type text is supported.

roleliteral
Literal["system"]

The role of the messages author, in this case system.

Hide ParametersShow Parameters
"system"
MessageChatCompletionRequestDeveloperMessageclass

Developer-provided instructions that the model should follow, regardless of messages sent by the user.

Hide ParametersShow Parameters
contentunion
Union[str, List[str]]

The contents of the developer message.

Hide ParametersShow Parameters
MessageChatCompletionRequestDeveloperMessageContentTextContenttype
str

The contents of the developer message.

MessageChatCompletionRequestDeveloperMessageContentArrayOfContentPartstype
List[str]

An array of content parts with a defined type. For developer messages, only type text is supported.

roleliteral
Literal["developer"]

The role of the messages author, in this case developer.

Hide ParametersShow Parameters
"developer"
MessageChatCompletionRequestUserMessageclass

Messages sent by an end user, containing prompts or additional context information.

Hide ParametersShow Parameters
contentunion
Union[str, List[str]]

The contents of the user message.

Hide ParametersShow Parameters
MessageChatCompletionRequestUserMessageContentTextContenttype
str

The text contents of the message.

MessageChatCompletionRequestUserMessageContentArrayOfContentPartstype
List[str]

An array of content parts with a defined type. Supported options differ based on the model being used to generate the response.

roleliteral
Literal["user"]

The role of the messages author, in this case user.

Hide ParametersShow Parameters
"user"
MessageChatCompletionRequestAssistantMessageclass

Messages sent by the model in response to user messages.

Hide ParametersShow Parameters
roleliteral
Literal["assistant"]

The role of the messages author, in this case assistant.

Hide ParametersShow Parameters
"assistant"
contentunion
optional
Union[str, List[str], null]

The contents of the assistant message.

Hide ParametersShow Parameters
MessageChatCompletionRequestAssistantMessageContentTextContenttype
str

The contents of the assistant message.

MessageChatCompletionRequestAssistantMessageContentArrayOfContentPartstype
List[str]

An array of content parts with a defined type. Can be one or more of type text, or exactly one of type refusal.

tool_callsiterable
optional

The tool calls generated by the model, such as function calls.

Hide ParametersShow Parameters
idstr

The ID of the tool call.

The function that the model called.

Hide ParametersShow Parameters
argumentsstr

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.

namestr

The name of the function to call.

typeliteral
Literal["function"]

The type of the tool. Currently, only function is supported.

Hide ParametersShow Parameters
"function"
MessageChatCompletionRequestToolMessageclass
Hide ParametersShow Parameters
contentstr

The contents of the tool message.

roleliteral
Literal["tool"]

The role of the messages author, in this case tool.

Hide ParametersShow Parameters
"tool"
tool_call_idstr

Tool call that this message is responding to.

modelstr

Model ID used to generate the response.

frequency_penaltyfloat
optional

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.

minimum-2
maximum2
logit_biasDict[str, int]
optional
Optional[Dict[str, int]]

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.

logprobsbool
optional

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.

max_completion_tokensint
optional

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.

minimum256
max_tokensint
optional

The maximum number of tokens that can be generated in the completion.

The token count of your prompt plus max_tokens cannot exceed the model's context length.

minimum0
metadataDict[str, str]
optional
Optional[Dict[str, str]]

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, and querying for objects via API or the dashboard.

Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters.

nint
optional

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.

minimum1
maximum128
presence_penaltyfloat
optional

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.

minimum-2
maximum2
stopunion
optional
Union[Optional[str], List[str], null]

Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence.

Hide ParametersShow Parameters
StopUnionMember0type
Optional[str]
StopUnionMember1type
List[str]
streamliteral
optional
Optional[Literal[false]]

If set to true, the model response data will be streamed to the client as it is generated using server-sent events.

Hide ParametersShow Parameters
false
stream_optionsinclude_usageboolStreamOptions
optional

Options for streaming response. Only set this when you set stream: true.

Hide ParametersShow Parameters
include_usagebool
optional

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. NOTE: If the stream is interrupted, you may not receive the final usage chunk which contains the total token usage for the request.

temperaturefloat
optional

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.

minimum0
maximum2
tool_choiceToolChoiceUnionMember0literalToolChoice
optional

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.

Hide ParametersShow Parameters
ToolChoiceUnionMember0type
Literal["none", "auto", "required"]

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.

Hide ParametersShow Parameters
"none"
"auto"
"required"
ToolChoiceChatCompletionNamedToolChoiceclass

Specifies a tool the model should use. Use to force the model to call a specific function.

Hide ParametersShow Parameters
Hide ParametersShow Parameters
namestr

The name of the function to call.

typeliteral
Literal["function"]

The type of the tool. Currently, only function is supported.

Hide ParametersShow Parameters
"function"
toolsiterable
optional
functionToolFunctiontypeliteralIterable[Tool]

A list of tools the model may call. Currently, only functions are supported as a tool.

Hide ParametersShow Parameters
functionnamestrdescriptionstrparametersDict[str, object]ToolFunction
Hide ParametersShow Parameters
namestr

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.

descriptionstr
optional

A description of what the function does, used by the model to choose when and how to call the function.

parametersDict[str, object]
optional
Dict[str, object]

The parameters the functions accepts, described as a JSON Schema object. See the guide for examples, and the JSON Schema reference for documentation about the format.

Omitting parameters defines a function with an empty parameter list.

typeliteral
Literal["function"]

The type of the tool. Currently, only function is supported.

Hide ParametersShow Parameters
"function"
top_logprobsint
optional

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.

minimum0
maximum20
top_pfloat
optional

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.

minimum0
maximum1
userstr
optional

A unique identifier representing your end-user, which can help DigitalOcean to monitor and detect abuse.

Returns
CompletionCreateResponseclass

Represents a chat completion response returned by model, based on the provided input.

Hide ParametersShow Parameters
idstr

A unique identifier for the chat completion.

choiceslist
List[Choice]

A list of chat completion choices. Can be more than one if n is greater than 1.

Hide ParametersShow Parameters
finish_reasonliteral
Literal["stop", "length", "tool_calls"]

The reason the model stopped generating tokens. This will be stop if the model hit a natural stop point or a provided stop sequence, or length if the maximum number of tokens specified in the request was reached, tool_calls if the model called a tool.

Hide ParametersShow Parameters
"stop"
"length"
"tool_calls"
indexint

The index of the choice in the list of choices.

logprobscontentlistrefusallistChoiceLogprobs

Log probability information for the choice.

Hide ParametersShow Parameters
contentlist
Optional[List[tokenstrbyteslistlogprobfloattop_logprobslistChatCompletionTokenLogprob]]

A list of message content tokens with log probability information.

Hide ParametersShow Parameters
tokenstr

The token.

byteslist
Optional[List[int]]

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.

logprobfloat

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.

top_logprobslist

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.

Hide ParametersShow Parameters
tokenstr

The token.

byteslist
Optional[List[int]]

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.

logprobfloat

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.

refusallist
Optional[List[tokenstrbyteslistlogprobfloattop_logprobslistChatCompletionTokenLogprob]]

A list of message refusal tokens with log probability information.

Hide ParametersShow Parameters
tokenstr

The token.

byteslist
Optional[List[int]]

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.

logprobfloat

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.

top_logprobslist

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.

Hide ParametersShow Parameters
tokenstr

The token.

byteslist
Optional[List[int]]

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.

logprobfloat

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.

messagecontentstrrefusalstrroleliteraltool_callslistChoiceMessage

A chat completion message generated by the model.

Hide ParametersShow Parameters
contentstr

The contents of the message.

refusalstr

The refusal message generated by the model.

roleliteral
Literal["assistant"]

The role of the author of this message.

Hide ParametersShow Parameters
"assistant"
tool_callslist
optional
Optional[List[ChoiceMessageToolCall]]

The tool calls generated by the model, such as function calls.

Hide ParametersShow Parameters
idstr

The ID of the tool call.

functionargumentsstrnamestrChoiceMessageToolCallFunction

The function that the model called.

Hide ParametersShow Parameters
argumentsstr

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.

namestr

The name of the function to call.

typeliteral
Literal["function"]

The type of the tool. Currently, only function is supported.

Hide ParametersShow Parameters
"function"
createdint

The Unix timestamp (in seconds) of when the chat completion was created.

modelstr

The model used for the chat completion.

objectliteral
Literal["chat.completion"]

The object type, which is always chat.completion.

Hide ParametersShow Parameters
"chat.completion"
usageCompletionUsage
optional

Usage statistics for the completion request.

from do_gradientai import GradientAI

client = GradientAI(
    api_key="My API Key",
)
completion = client.chat.completions.create(
    messages=[{
        "content": "string",
        "role": "system",
    }],
    model="llama3-8b-instruct",
)
print(completion.id)
200 Example
{
  "id": "id",
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": {
        "content": [
          {
            "token": "token",
            "bytes": [
              0
            ],
            "logprob": 0,
            "top_logprobs": [
              {
                "token": "token",
                "bytes": [
                  0
                ],
                "logprob": 0
              }
            ]
          }
        ],
        "refusal": [
          {
            "token": "token",
            "bytes": [
              0
            ],
            "logprob": 0,
            "top_logprobs": [
              {
                "token": "token",
                "bytes": [
                  0
                ],
                "logprob": 0
              }
            ]
          }
        ]
      },
      "message": {
        "content": "content",
        "refusal": "refusal",
        "role": "assistant",
        "tool_calls": [
          {
            "id": "id",
            "function": {
              "arguments": "arguments",
              "name": "name"
            },
            "type": "function"
          }
        ]
      }
    }
  ],
  "created": 0,
  "model": "model",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 0,
    "prompt_tokens": 0,
    "total_tokens": 0
  }
}