In this guide, I will explain how to use cohere AI APIs with Python.
Table of Contents
Requirements
You are going to need to cohere AI API Key. You can get a free account from here.
After logging in, go to Dashboard -> API Keys.
While you are developing and testing, you can use a trial API key. cohere doesn’t charge you when you use the Trial API Key. However, it is recommended to use a Production API key for an app that you will release publicly.
Setup
The first thing you need to do is install cohere’s Python package. You can do that by running the below command:
pip install cohere
Your first call to cohere AI APIs with Python
Create a new python file, a Jupyter Notebook, or a Google Colab Notebook
First, we import the cohere python package and initiate a new cohere client with our cohere API key. import cohere cohere_api_key = "your cohere API key" co = cohere.Client(cohere_api_key)
Below we are defining a method for calling the cohere API’s generate endpoint. Generate endpoint takes a text prompt and outputs generated text based on that prompt.
def generate_text(user_prompt): response = co.generate( model='command-xlarge-nightly', prompt= user_prompt max_tokens=300, temperature=0.9, k=0, p=0.75, frequency_penalty=0, presence_penalty=0, stop_sequences=[], return_likelihoods='NONE') return response.generations[0].text
The main parameter to pay attention in this is the prompt. You can ignore the rest right now.
Next call this method with your own prompt. For example
cohere_api_output = geenrate_text("Write a blog post title on Space Travel in 2023") print(cohere_api_output)
This will give you the generated text from the cohere AI APIs with Python.
Conclusion
In this guide, I covered just one endpoint for using cohere AI APIs with Python. However, there are multiple endpoints. Check for more cohere AI posts here.