Chat

Supported Providers - Chat
  • AI21

  • Anthropic

  • Anyscale

  • Azure OpenAI

  • AWS Bedrock

  • Cohere

  • Deepinfra

  • Fireworks AI

  • Google Vertex AI

  • Google Gemini

  • Groq

  • Lingyi (01.ai)

  • Mistral AI

  • Monster API

  • Moonshot.cn

  • Novita AI

  • Ollama

  • OpenAI

  • Openrouter

  • Perplexity AI

  • Predibase

  • Reka AI

  • Together AI

  • Cloudflare Workers AI

  • Zhipu AI

  • DeepSeek

Supported Providers - Chat Tools
  • Anthropic

  • Anyscale

  • Azure OpenAI

  • AWS Bedrock

  • Fireworks AI

  • Google Vertex AI

  • Google Gemini

  • Groq

  • Novita AI

  • OpenAI

  • Together AI

Supported Providers - Chat Vision
  • Anthropic

  • Azure OpenAI

  • AWS Bedrock

  • Google Gemini

Create Chat Completion

POST /chat/completions

Generate a chat message completion from the selected LLM.

Chat

post
Authorizations
Header parameters
x-portkey-trace-idstringOptional

An ID you can pass to refer to one or more requests later on. If not provided, Portkey generates a trace ID automatically for each request. Docs

x-portkey-span-idstringOptional

An ID you can pass to refer to a span under a trace.

x-portkey-parent-span-idstringOptional

Link a child span to a parent span

x-portkey-span-namestringOptional

Name for the Span ID

x-portkey-metadataobjectOptional

Pass any arbitrary metadata along with your request

x-portkey-cache-namespacestringOptional

Partition your Portkey cache store based on custom strings, ignoring metadata and other headers

x-portkey-cache-force-refreshbooleanOptional

Forces a cache refresh for your request by making a new API call and storing the updated value

Body
modelany ofRequired

ID of the model to use. See the model endpoint compatibility table for details on which models work with the Chat API.

Example: gpt-4-turbo
stringOptional
or
string · enumOptionalPossible values:
frequency_penaltynumber | nullableOptional

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.

Default: 0
logprobsboolean | nullableOptional

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.

Default: false
top_logprobsinteger | nullableOptional

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.

max_tokensinteger | nullableOptional

The maximum number of tokens 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 for counting tokens.

ninteger | nullableOptional

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.

Default: 1Example: 1
presence_penaltynumber | nullableOptional

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.

See more information about frequency and presence penalties.

Default: 0
response_formatone ofOptional

An object specifying the format that the model must output.

Setting to { "type": "json_schema", "json_schema": {...} }enables Structured Outputs which ensures the model will match your supplied JSON schema. Works across all the providers that support this functionality. OpenAI & Azure OpenAI, Gemini & Vertex AI.

Setting to { "type": "json_object" } enables the older JSON mode, which ensures the message the model generates is valid JSON.

Using json_schema is preferred for models that support it.

or
or
seedinteger | nullableOptional

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.

stopone ofOptional

Up to 4 sequences where the API will stop generating further tokens.

Default: null
string | nullableOptional
or
string[] · min: 1 · max: 4Optional
streamboolean | nullableOptional

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. Example Python code.

Default: false
temperaturenumber | nullableOptional

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.

Default: 1Example: 1
top_pnumber | nullableOptional

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.

Default: 1Example: 1
tool_choiceone ofOptional

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.

string · enumOptional

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.

Possible values:
or
parallel_tool_callsbooleanOptional

Whether to enable parallel function calling during tool use.

Default: true
userstringOptional

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

Example: user-1234
function_callone ofOptionalDeprecated

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.

string · enumOptional

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.

Possible values:
or
Responses
200
OK
application/json
post
curl https://api.portkey.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "x-portkey-api-key: $PORTKEY_API_KEY" \
  -H "x-portkey-virtual-key: $PORTKEY_PROVIDER_VIRTUAL_KEY" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "Hello!"
      }
    ]
  }'
200

OK

{
  "id": "text",
  "choices": [
    {
      "finish_reason": "stop",
      "index": 1,
      "message": {
        "content": "text",
        "tool_calls": [
          {
            "id": "text",
            "type": "function",
            "function": {
              "name": "text",
              "arguments": "text"
            }
          }
        ],
        "role": "assistant",
        "content_blocks": [
          {
            "type": "text",
            "text": "text"
          }
        ]
      },
      "logprobs": {
        "content": [
          {
            "token": "text",
            "logprob": 1,
            "bytes": [
              1
            ],
            "top_logprobs": [
              {
                "token": "text",
                "logprob": 1,
                "bytes": [
                  1
                ]
              }
            ]
          }
        ]
      }
    }
  ],
  "created": 1,
  "model": "text",
  "system_fingerprint": "text",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 1,
    "prompt_tokens": 1,
    "total_tokens": 1
  }
}

The body is similar to the chat completion request of OpenAI and the response will be the Chat Completion Object. When choosing stream:true the response will be a stream of Chat Completion Chunk objects.

Portkey automatically transforms the parameters for LLMs other than OpenAI. If some parameters don't exist in the other LLMs, they will be dropped.

SDK Usage

The chat.completions.create method in the Portkey SDK enables you to generate chat completions using various Large Language Models (LLMs). This method is designed to be similar to the OpenAI chat completions API, offering a familiar interface for those accustomed to OpenAI's services.

Method Signature

portkey.chat.completions.create(requestParams[, configParams]);

For REST API examples, scroll here.

Parameters

  1. requestParams (Object): Parameters for the chat completion request, detailing the chat interaction. These are similar to the OpenAI request signature. Portkey automatically transforms the parameters for LLMs other than OpenAI. If some parameters don't exist in the other LLMs, they will be dropped. Portkey is multimodal by-default, so parameters relevant to vision models, like image_url, base64 data are also supported.

  2. configParams(Object): Additional configuration options for the request. This is an optional parameter that can include custom config options for this specific request. These will override the configs set in the Portkey Client. A full list of these config parameters can be found here.

Example Usage

1. Default

The chat completions endpoint accepts an array of message objects and returns the completion in a chat message format.

import Portkey from 'portkey-ai';

// Initialize the Portkey client
const portkey = new Portkey({
    apiKey: "PORTKEY_API_KEY",  // Replace with your Portkey API key
    virtualKey: "VIRTUAL_KEY"   // Optional: For virtual key management
});

// Generate a chat completion
async function getChatCompletion() {
    const chatCompletion = await portkey.chat.completions.create({
        messages: [{ role: 'user', content: 'Say this is a test' }],
        model: 'gpt-3.5-turbo',
    });

    console.log(chatCompletion);
}
await getChatCompletion();

To send chat requests to locally or privately hosted models, check out the guide on Ollama.

2. Image Input (Vision Models)

The chat completions API also supports adding images to the request for vision models (GPT-4V, Gemini, etc).

// Generate a chat completion with streaming
async function getChatCompletionVision(){
    const chatCompletion = await portkey.chat.completions.create({
        model: "gpt-4-vision-preview",
        messages: [
          {
            role: "user",
            content: [
              { type: "text", text: "What’s in this image?" },
              {
                type: "image_url",
                image_url:
                  "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
              },
            ],
          },
        ],
    });

    console.log(response.choices[0]);
}
await getChatCompletionVision();

3. Streaming Chat Completions

Pass the stream parameter as true in the request to enable streaming responses from the Chat completions API.

The chat completions endpoint accepts an array of message objects and returns the completion in a chat message format.

// Generate a chat completion with streaming
async function getChatCompletionStream(){
    const chatCompletion = await portkey.chat.completions.create({
        messages: [{ role: 'user', content: 'Say this is a test' }],
        model: 'gpt-3.5-turbo',
        stream: true
    });

    for await (const chunk of chatCompletion) {
        console.log(chunk.choices[0].delta.content);
    }
}
await getChatCompletionStream();

4. Functions

The tools parameter accepts functions which can be sent specifically for models that support function calling.

// Generate a chat completion with streaming
async function getChatCompletionFunctions(){
  const messages = [{"role": "user", "content": "What's the weather like in Boston today?"}];
  const 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"],
          },
        }
      }
  ];

    const response = await openai.chat.completions.create({
    model: "gpt-3.5-turbo",
    messages: messages,
    tools: tools,
    tool_choice: "auto",
  });
  
  console.log(response)

}
await getChatCompletionFunctions();

5. Custom configuration for each request

There might be a need to override config values per request, or send options for trace id and metadata as part of the request being made. This is possible by attaching adding these parameters along with the request being made.

// Generate chat completion with config params
async function getChatCompletionWithConfig() {
    const chatCompletion = await portkey.chat.completions.create({
        messages: [{ role: 'user', content: 'Say this is a test' }],
        model: 'gpt-3.5-turbo',
    }, {config: "sample-7g5tr4"});

    for await (const chunk of chatCompletion) {
        console.log(chunk.choices[0].delta.content);
    }
}
await getChatCompletionWithConfig();

Response Format

The response will conform to the Chat Completions Object schema from the Portkey API, typically including generated messages and relevant metadata.

Last updated

Was this helpful?