PYTHON - COHERE - API
Simon-Pierre Boucher
2024-09-14
In [1]:
import os
import requests
import json
def call_cohere_api(
message,
chat_history=None,
model="command-light-nightly",
temperature=0.3,
max_tokens=1000,
max_input_tokens=1000,
frequency_penalty=0,
presence_penalty=0,
k=0,
p=0,
preamble=None
):
# Get the API key from environment variables
api_key = os.getenv("COHERE_API_KEY")
if not api_key:
raise ValueError("API key not found in environment variables. Please set COHERE_API_KEY.")
url = "https://api.cohere.com/v1/chat"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"Accept": "application/json"
}
body = {
"message": message,
"model": model,
"temperature": temperature,
"max_tokens": max_tokens,
"max_input_tokens": max_input_tokens,
"frequency_penalty": frequency_penalty,
"presence_penalty": presence_penalty,
"k": k,
"p": p
}
# Add optional parameters if they are not None
if chat_history is not None:
body["chat_history"] = chat_history
if preamble is not None:
body["preamble"] = preamble
response = requests.post(url, headers=headers, json=body)
if response.status_code != 200:
raise ValueError(f"API request failed: {response.text}")
result = response.json()
return result
In [2]:
# Define the chat history
chat_history = [
{"message": "allo", "role": "USER"},
{
"message": "I'm your friendly AI chatbot assistant! I'm here to help you with questions, provide me with your queries, and I'll do my best to assist and provide helpful answers and information for you.",
"role": "CHATBOT"
}
]
In [3]:
# Call the function
response = call_cohere_api(
message="give me a list of gift ideas for my girlfriend",
chat_history=chat_history,
model="command-light-nightly",
temperature=0.3,
max_tokens=1000,
max_input_tokens=1000,
frequency_penalty=0,
presence_penalty=0,
k=0,
p=0,
preamble="You are an AI-assistant chatbot. You are trained to assist users by providing thorough and helpful responses to their queries."
)
# Display the chatbot's response
print(response['text'])