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.
# with only request paramsportkey.chat.completions.create(**requestParams);# with request and config paramsportkey.with_options(**configParams).chat.completions.create(**requestParams);
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.
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 clientconstportkey=newPortkey({ apiKey:"PORTKEY_API_KEY",// Replace with your Portkey API key virtualKey:"VIRTUAL_KEY"// Optional: For virtual key management});// Generate a chat completionasyncfunctiongetChatCompletion() {constchatCompletion=awaitportkey.chat.completions.create({ messages: [{ role:'user', content:'Say this is a test' }], model:'gpt-3.5-turbo', });console.log(chatCompletion);}awaitgetChatCompletion();
from portkey_ai import Portkey# Initialize the Portkey clientportkey =Portkey( api_key="PORTKEY_API_KEY", # Replace with your Portkey API key virtual_key="VIRTUAL_KEY"# Optional: For virtual key management)# Generate a chat completiondefget_chat_completion(): chat_completion = portkey.chat.completions.create( messages=[{'role': 'user', 'content': 'Say this is a test'}], model='gpt-3.5-turbo' )print(chat_completion)get_chat_completion()
In REST calls, x-portkey-api-key is a compulsory header, it can be paired with the following options for sending provider details:
x-portkey-provider & Authorization (or similar auth headers)
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 streamingasyncfunctiongetChatCompletionStream(){constchatCompletion=awaitportkey.chat.completions.create({ messages: [{ role:'user', content:'Say this is a test' }], model:'gpt-3.5-turbo', stream:true });forawait (constchunkof chatCompletion) {console.log(chunk.choices[0].delta.content); }}awaitgetChatCompletionStream();
# Generate a streaming chat completiondefget_chat_completion_stream(): chat_completion_stream = portkey.with_options(config='sample-7g5tr4').chat.completions.create( messages=[{'role': 'user', 'content': 'Say this is a test'}], model='gpt-3.5-turbo', stream=True )for chunk in chat_completion_stream:print(chunk.choices[0].delta)get_chat_completion_stream()
The tools parameter accepts functions which can be sent specifically for models that support function calling.
// Generate a chat completion with streamingasyncfunctiongetChatCompletionFunctions(){constmessages= [{"role":"user","content":"What's the weather like in Boston today?"}];consttools= [ {"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"], }, } } ];constresponse=awaitopenai.chat.completions.create({ model:"gpt-3.5-turbo", messages: messages, tools: tools, tool_choice:"auto", });console.log(response)}awaitgetChatCompletionFunctions();
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"],},}}]messages = [{"role":"user","content":"What's the weather like in Boston today?"}]completion = portkey.chat.completions.create( model="gpt-3.5-turbo", messages=messages, tools=tools, tool_choice="auto")print(completion)
curl"https://api.portkey.ai/v1/chat/completions" \-H"Content-Type: application/json" \-H"x-portkey-api-key: $PORTKEY_API_KEY" \-H"x-portkey-provider: openai" \-H"Authorization: Bearer $OPENAI_API_KEY" \-d'{ "model": "gpt-3.5-turbo", "messages": [ { "role": "user", "content": "What is the weather like in Boston?" } ], "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"] } } } ], "tool_choice": "auto"}'
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 paramsasyncfunctiongetChatCompletionWithConfig() {constchatCompletion=awaitportkey.chat.completions.create({ messages: [{ role:'user', content:'Say this is a test' }], model:'gpt-3.5-turbo', }, {config:"sample-7g5tr4"});forawait (constchunkof chatCompletion) {console.log(chunk.choices[0].delta.content); }}awaitgetChatCompletionWithConfig();
# Example with config parametersdefget_chat_completion_with_config(): chat_completion = portkey.with_options(config='sample-7g5tr4').chat.completions.create( messages=[{'role': 'user', 'content': 'Say this is a test'}], model='gpt-3.5-turbo' )print(chat_completion)get_chat_completion_with_config()
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"
frequency_penaltynullable number
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.
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.
logprobsnullable boolean
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.
top_logprobsnullable integer
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_tokensnullable integer
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.
nnullable integer
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.
Example: 1
presence_penaltynullable number
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.
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 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.
seednullable integer
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 of
Up to 4 sequences where the API will stop generating further tokens.
streamnullable boolean
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.
Options for streaming response. Only set this when you set stream: true.
temperaturenullable number
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.
Example: 1
top_pnullable number
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.
Example: 1
toolsarray of ChatCompletionTool (object)
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.
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.