To ensure secure access to Portkey's APIs, authentication is required for all requests. This guide provides the necessary steps to authenticate your requests using the Portkey API key, regardless of whether you are using the SDKs for Python and JavaScript, the OpenAI SDK, or making REST API calls directly.
Obtaining Your API Key
Create or log in to your Portkey account. Grab your account's API key from the "Settings" page -> "API Keys" tab.
Authentication with SDKs
Portkey SDKs
import Portkey from'portkey-ai'constportkey=newPortkey({ apiKey:"PORTKEY_API_KEY",// Replace with your actual API key virtualKey:"VIRTUAL_KEY"// Optional: Use for virtual key management})constchatCompletion=awaitportkey.chat.completions.create({ messages: [{ role:'user', content:'Say this is a test' }], model:'gpt-3.5-turbo',});console.log(chatCompletion.choices);
from portkey_ai import Portkeyclient =Portkey( api_key="PORTKEY_API_KEY", # Replace with your actual API key virtual_key="VIRTUAL_KEY"# Optional: Use if virtual keys are set up)chat_completion = client.chat.completions.create( messages=[{"role": "user", "content": "Say this is a test"}], model='gpt-3.5-turbo')print(chat_completion.choices[0].message["content"])
When integrating Portkey through the OpenAI SDK, modify the base URL and add the x-portkey-api-key header for authentication. Here's an example of how to do it:
import openai from'openai';import { PORTKEY_GATEWAY_URL, createHeaders } from'portkey-ai';openai.api_base =PORTKEY_GATEWAY_URL;constheaders=createHeaders({ provider:"openai", apiKey:"PORTKEY_API_KEY"// Replace with your actual Portkey API key});// Continue with your OpenAI SDK usage, utilizing the headers for authentication
from openai import OpenAIfrom portkey_ai import PORTKEY_GATEWAY_URL, createHeadersopenai_client =OpenAI( base_url=PORTKEY_GATEWAY_URL, default_headers=createHeaders( api_key="PORTKEY-API-KEY", provider="openai" ))response = openai_client.chat.completions.create( messages=[{'role': 'user', 'content': 'Say this is a test'}], model='gpt-3.5-turbo')