Python Library for Accessing the Cohere API

Overview

ci badge version badge license badge

Cohere Python SDK

This package provides functionality developed to simplify interfacing with the Cohere API in Python 3.

Documentation

See the API's documentation.

Installation

The package can be installed with pip:

pip install --upgrade cohere

Install from source:

python setup.py install

Requirements

  • Python 3.6+

Quick Start

To use this library, you must have an API key and specify it as a string when creating the cohere.Client object. API keys can be created through the platform. This is a basic example of the creating the client and using the generate endpoint.

import cohere

# initialize the Cohere Client with an API Key
co = cohere.Client('YOUR_API_KEY')

# generate a prediction for a prompt 
prediction = co.generate(
            model='large',
            prompt='co:here',
            max_tokens=10)
            
# print the predicted text          
print('prediction: {}'.format(prediction.generations[0].text))

Versioning

To use the SDK with a specific API version, you can specify it when creating the Cohere Client:

import cohere

co = cohere.Client('YOUR_API_KEY', '2021-11-08')

Endpoints

For a full breakdown of endpoints and arguments, please consult the Cohere Docs.

Cohere Endpoint Function
/generate co.generate()
/choose-best co.choose_best()
/embed co.embed()
/likelihood co.likelihood()

Models

To view an up-to-date list of available models please consult the models section in the platform. To get started try out large for Generate, Choose Best, and Likelihood or small for Embed.

Responses

All of the endpoint functions will return a Cohere object corresponding to the endpoint (e.g. for generation, it would be Generation). The responses can be found as instance variables of the object (e.g. generation would be Generation.text). The names of these instance variables and a detailed breakdown of the response body can be found in the Cohere Docs. Printing the Cohere response object itself will display an organized view of the instance variables.

Exceptions

Unsuccessful API calls from the SDK will raise an exception. Please see the documentation's page on errors for more information about what the errors mean.

Comments
  • Asyncio support?

    Asyncio support?

    Is there any interest for an async/aiohttp based client?

    Advantages:

    • Much lower overhead than threadpools
    • Users who use the api as a step in their async codebase (e.g. fastapi) are not forced to block

    Disadvantages:

    • Needs significant refactoring to not end up with code duplication
    • Extra (optional?) dependency
    opened by sanderland 4
  • Classification.confidence as a float not a list

    Classification.confidence as a float not a list

    Before:

    res = co.classify(...)
    res.classifications[0].confidence # [ Confidence(label: __, confidence: 0.8), Confidence(label: __, confidence: ___), ...)
    

    After

    res = co.classify(...)
    res.classifications[0].confidence # 0.8
    
    opened by mkozakov 2
  • Make co.generate call async

    Make co.generate call async

    • Adds co.batch_{generate/tokenize/detokenize}
    • Makes the Generations/Detokenize/Tokenize objects all (optionally) lazy in the sense that they can be constructed and manipulated without the REST call response they represent being complete yet. As soon as a class attribute that depends on the REST call is accessed it will block until that attribute is resolved.
    • Generation object is now a subclass of str so that it can be thrown into code as though it were one.
    • Improved the Generations object so that is can be more easily sliced/indexed into without needing to access an ugly next of attributes.
    • Converted a bunch of bloat objects that were actually just NamedTuples
    • Remove the "one time iterator" design decision that was made: Previously, if you wrote:
    generations = co.generate(...)
    for g in generations:
        print(g)
    # the lines above will print the generations successfully
    for g in generations:
        print(g)
    # the loop above won't be executed because the iterator in generations can only be run once
    

    This PR removes that strange behaviour.

    enhancement 
    opened by aidangomez 2
  • Add Extract V0 API

    Add Extract V0 API

    This PR adds Extract to the Python SDK.

    Usage:

    import cohere
    from cohere.extract import Entity, Example
    
    co = cohere.Client('API_KEY')
    
    result = co.extract(
        model="large",
        examples=[
            Example(
                text="hello my name is John, and I like to play ping pong",
                entities=[
                    Entity(type="Name", value="John"),
                    Entity(type="Game", value="ping pong")
                ]
            ),
            Example(
                text="Jon Ke from work is amazing at chess!",
                entities=[
                    Entity(type="Name", value="Jon Ke"),
                    Entity(type="Game", value="chess")
                ]
            ),
            Example(
                text="David won't stop talking about playing tennis!",
                entities=[
                    Entity(type="Name", value="David"),
                    Entity(type="Game", value="tennis")
                ]
            ),
        ],
        texts=[
            "David will be playing soccer?"
        ]
    )
    
    print(result)
    '''
    cohere.Extractions {
            extractions: [
              {'id': 'caf0d948-57e8-4d48-849c-007a0c13b4cb',
              'text': 'David will be playing soccer?',
              'entities': [{'type': 'Name', 'value': 'David'}, {'type': 'Game', 'value': 'soccer'}]}]
    }
    '''
    
    opened by rodrigue-h 2
  • Update SDK to use updated casing for parameters

    Update SDK to use updated casing for parameters

    the Classify parameters taskDescription and outputIndicator are being replaced with task_description and output_indicator respectively to be consistent with the casing of other parameters.

    This PR updates the SDK to use these new params.

    opened by mkozakov 1
  • Add language param to Generate API

    Add language param to Generate API

    As part of https://github.com/cohere-ai/blobheart/pull/3680 the Generate API now accepts a "language" parameter. This PR updates the SDK to accept "language" as an argument and include it in the API request.

    opened by mkozakov 1
  • what if we just asynced all the model calls

    what if we just asynced all the model calls

    • when making requests spin up the thread to request and return immediately
    • give all the cohere response objects a mutex, when a request is running a thread should hold onto that mutex
    • if accessed, block <-- this is the spooky part
    opened by kipply 1
  • CI to Publish Our PyPi Server

    CI to Publish Our PyPi Server

    CI to Publish Our PyPi Server on all merges/pushes to main so that we dont need to manually build and upload every time.

    • Github Action
    • https://pythonprogramming.org/automatically-building-python-package-using-github-actions/

    cc: @jimwu6 @choicallum

    opened by OrenLeung 1
  • Add Jupyter Lite support for SDK

    Add Jupyter Lite support for SDK

    How to reproduce:

    1. Go to: https://cohere-ai.github.io/jupyter_lite/repl/?toolbar=1&kernel=python
    2. Add the following code snippet
    import piplite
    await piplite.install("cohere")
    import cohere
    co = cohere.Client('<your_prod_api_key>')
    prediction = co.generate(
      model='xlarge-20220301',
      prompt='The table lists the following professions as artistic careers:\n1. Painter\n2.',
      max_tokens=50,
      temperature=1,
      k=0,
      p=0.75,
      frequency_penalty=0,
      presence_penalty=0,
      stop_sequences=[],
      return_likelihoods='NONE')
    print('Prediction: {}'.format(prediction.generations[0].text))
    
    1. It fails due to the stdlib used for performing HTTP requests, which is not compatible with Pyodide (Python port for WASM)

    Expected behavior:

    1. We should support using the SDK in a Pyodide environment, by either allowing passing a custom http client or building a separate SDK for Pyodide.
    enhancement 
    opened by knajjars 1
  • Initial change from dicts to objects

    Initial change from dicts to objects

    Don't know about how we should name objects yet.

    Originally, I wanted to have one "catch all" CohereResponse object, but the names were confusing because we had "likelihood" and "likelihoods", thus designing it this way.

    This should also be refactored into bzz and docs

    closes #8

    opened by jimwu6 1
  • AsyncClient for cohere endpoints.

    AsyncClient for cohere endpoints.

    Hello, I implemented async style for cohere client. All methods are implemented with the same parameter signatures and response type. Added tests for each method.

    Example of usage:

    co = await cohere.async_client.AsyncClient.create(API_KEY)
    
    response = await co.generate(
        model="xlarge",
        prompt="""Summarize this dialogue:
            Customer: Please connect me with a support agent.
            AI: Hi there, how can I assist you today?
            Customer: I forgot my password and lost access to the email affiliated to my account. Can you please help me?
            AI: Yes of course. First I\'ll need to confirm your identity and then I can connect you with one of our support agents.
            TLDR: A customer lost access to their account.
             --
            Summarize this dialogue:
            AI: Hi there, how can I assist you today?
            Customer: I want to book a product demo.
            AI: Sounds great. What country are you located in?
            Customer: I\'ll connect you with a support agent who can get something scheduled for you.
            TLDR: A customer wants to book a product demo.
            --
            Summarize this dialogue:
            AI: Hi there, how can I assist you today?
            Customer: I want to get more information about your pricing.
            AI: I can pull this for you, just a moment.
            TLDR:""",
        max_tokens=20,
        temperature=0.6,
        k=0,
        p=1,
        stop_sequences=["--"])
    
    response
    cohere.Generations {
    	generations: [cohere.Generation {
    	text:  A customer wants to get more information about pricing.
      --
    	likelihood: None
    	token_likelihoods: None
    }]
    	return_likelihoods: None
    }
    
    opened by zaebee 2
  • Support for Token Streaming

    Support for Token Streaming

    Add token streaming support for python sdk, add stream and chunk_size optional params to co.generate()

    Sample use case

    import cohere
    import os
    
    co = cohere.Client(os.environ["CO_API_KEY"])
    
    response_generator = co.generate("Today I went to the park", stream=True)
    
    for gen in response_generator.stream():
       # do something with gen
    
    final_response = response_generator.response()
    
    opened by abdurj 1
  • Support for paint endpoint

    Support for paint endpoint

    Sample client

    import cohere
    import os
    import base64
    
    API_KEY = os.getenv('COHERE_API_KEY')
    cohere.COHERE_API_URL = "https://dev.api.cohere.ai/"
    co = cohere.Client(API_KEY)
    
    # x = co.whisper(file_paths=<INSERT_FILE_PATH>)
    x = co.image(<INSERT_PROMPT>)
    with open("image.png", "wb") as f:
        f.write(base64.b64decode(x.image))
    
    opened by CoderHam 1
  • Provide an enum type for api errors to distiguish them

    Provide an enum type for api errors to distiguish them

    Hello, Will it be possible to provide an enum for different message errors types so we can check against ? or at least provide the message error type in the documentation. Thanks

    opened by mauriyouth 0
Client library for accessing IQM quantum computers

IQM Client Client-side library for connecting to an IQM quantum computer. Installation IQM client is not intended to be used directly by human users.

IQM 10 Dec 21, 2022
A command line interface for accessing google drive

Drive Cli Get the ability to access Google Drive without leaving your terminal. Inspiration Google Drive has become a vital part of our day to day lif

Chirag Shetty 538 Dec 12, 2022
A tool for creating credentials for accessing S3 buckets

s3-credentials A tool for creating credentials for accessing S3 buckets For project background, see s3-credentials: a tool for creating credentials fo

Simon Willison 138 Jan 6, 2023
A part of HyRiver software stack for accessing hydrology data through web services

Package Description Status PyNHD Navigate and subset NHDPlus (MR and HR) using web services Py3DEP Access topographic data through National Map's 3DEP

Taher Chegini 51 Dec 10, 2022
alpaca-trade-api-python is a python library for the Alpaca Commission Free Trading API.

alpaca-trade-api-python is a python library for the Alpaca Commission Free Trading API. It allows rapid trading algo development easily, with support for both REST and streaming data interfaces

Alpaca 1.5k Jan 9, 2023
Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Harun Mbaabu Mwenda 46 Sep 1, 2022
Python API wrapper library for Convex Value API

convex-value-python Python API wrapper library for Convex Value API. Further Links: Convex Value homepage @ConvexValue on Twitter JB on Twitter Authen

Aaron DeVera 2 May 11, 2022
This an API wrapper library for the OpenSea API written in Python 3.

OpenSea NFT API Python 3 wrapper This an API wrapper library for the OpenSea API written in Python 3. The library provides a simplified interface to f

Attila Tóth 159 Dec 26, 2022
Aio-binance-library - Async library for connecting to the Binance API on Python

aio-binance-library Async library for connecting to the Binance API on Python Th

GRinvest 10 Nov 21, 2022
PRAW, an acronym for "Python Reddit API Wrapper", is a python package that allows for simple access to Reddit's API.

PRAW: The Python Reddit API Wrapper PRAW, an acronym for "Python Reddit API Wrapper", is a Python package that allows for simple access to Reddit's AP

Python Reddit API Wrapper Development 3k Dec 29, 2022
PRAW, an acronym for "Python Reddit API Wrapper", is a python package that allows for simple access to Reddit's API.

PRAW: The Python Reddit API Wrapper PRAW, an acronym for "Python Reddit API Wrapper", is a Python package that allows for simple access to Reddit's AP

Python Reddit API Wrapper Development 3k Dec 29, 2022
WhatsApp Api Python - This documentation aims to exemplify the use of Moorse Whatsapp API in Python

WhatsApp API Python ChatBot Este repositório contém uma aplicação que se utiliza

Moorse.io 3 Jan 8, 2022
Official python API for Phish.AI public and private API to detect zero-day phishing websites

phish-ai-api Summary Official python API for Phish.AI public and private API to detect zero-day phishing websites How it Works (TLDR) Essentially we h

Phish.AI 168 May 17, 2022
Python API wrapper around Trello's API

A wrapper around the Trello API written in Python. Each Trello object is represented by a corresponding Python object. The attributes of these objects

Richard Kolkovich 904 Jan 2, 2023
A python to scratch API connector. Can fetch data from the API and send it back in cloud variables.

Scratch2py Scratch2py or S2py is a easy to use, versatile tool to communicate with the Scratch API Based of scratchclient by Raihan142857 Installation

null 20 Jun 18, 2022
Async ready API wrapper for Revolt API written in Python.

Mutiny Async ready API wrapper for Revolt API written in Python. Installation Python 3.9 or higher is required To install the library, you can just ru

null 16 Mar 29, 2022
🚀 An asynchronous python API wrapper meant to replace discord.py - Snappy discord api wrapper written with aiohttp & websockets

Pincer An asynchronous python API wrapper meant to replace discord.py ❗ The package is currently within the planning phase ?? Links |Join the discord

Pincer 125 Dec 26, 2022
wyscoutapi is an extremely basic API client for the Wyscout API (v2 & v3) for Python

wyscoutapi wyscoutapi is an extremely basic API client for the Wyscout API (v2 & v3). Usage Install with pip install wyscoutapi. To connect to the Wys

Ben Torvaney 11 Nov 22, 2022
A Python API wrapper for the Twitter API!

PyTweet PyTweet is an api wrapper made for twitter using twitter's api version 2! Installation Windows py3 -m pip install PyTweet Linux python -m pip

TheFarGG 1 Nov 19, 2022