Skip to main content

An unofficial asynchronous api wrapper for Character AI.

Project description

PyCharacterAI

An asynchronous Python api wrapper for Character AI using curl-cffi.

[!WARNING] This is an unofficial library made by an enthusiast who has no relation to the CharacterAI development team. CharacterAI has no official api and all breakpoints were found manually using reverse proxy. The author is not responsible for possible consequences of using this library.

The library is under constant development, trying to match the functionality of the website. Anything that isn't described in the documentation may be changed or removed without backward compatibility!


📚 Documentation.


TO-DO:

  • Exceptions.
  • Logging?
  • Finish the docs.


If you have any questions, problems, suggestions, please open an issue or contact me:

Tag


Getting started

First, you need to install the library:

pip install PyCharacterAI


Import the Client class from the library and create a new instance of it:

from PyCharacterAI import Client
client = Client()

Then you need to authenticate client using token:

await client.authenticate("TOKEN")

if you want to be able to upload your avatar you also need to specify web_next_auth token as an additional argument (only this way for now, this may change in the future):

await client.authenticate("TOKEN", web_next_auth="WEB_NEXT_AUTH")


Or you can just call get_client() method:

from PyCharacterAI import get_client

client = await get_client(token="TOKEN", web_next_auth="WEB_NEXT_AUTH")

After authentication, we can use all available library methods.


About tokens and how to get them

⚠️ WARNING, DO NOT SHARE THESE TOKENS WITH ANYONE! Anyone with your tokens has full access to your account!

This library uses two types of tokens: a common token and web_next_auth. The first one is required for almost all methods here and the second one only and only for upload_avatar() method (may change in the future).

Instructions for getting a token

  1. Open the Character.AI website in your browser
  2. Open the developer tools (F12, Ctrl+Shift+I, or Cmd+J)
  3. Go to the Nerwork tab
  4. Interact with website in some way, for example, go to your profile and look for Authorization in the request header
  5. Copy the value after Token

For example, token in https://plus.character.ai/chat/user/public/following/ request headers: img

Instructions for getting a web_next_auth token

  1. Open the Character.AI website in your browser
  2. Open the developer tools (F12, Ctrl+Shift+I, or Cmd+J)
  3. Go to the Storage section and click on Cookies
  4. Look for the web-next-auth key
  5. Copy its value

img


Examples

Here are just some examples of the library's features. If you want to know about all methods and types with explanations, go to methods and types documentation sections.

Simple chatting example

import asyncio

from PyCharacterAI import get_client
from PyCharacterAI.exceptions import SessionClosedError

token = "TOKEN"
character_id = "ID"


async def main():
    client = await get_client(token=token)

    me = await client.account.fetch_me()
    print(f"Authenticated as @{me.username}")

    chat, greeting_message = await client.chat.create_chat(character_id)

    print(f"{greeting_message.author_name}: {greeting_message.get_primary_candidate().text}")

    try:
        while True:
            # NOTE: input() is blocking function!
            message = input(f"[{me.name}]: ")

            answer = await client.chat.send_message(character_id, chat.chat_id, message)
            print(f"[{answer.author_name}]: {answer.get_primary_candidate().text}")

    except SessionClosedError:
        print("session closed. Bye!")

    finally:
        # Don't forget to explicitly close the session
        await client.close_session()

asyncio.run(main())

A more advanced example. You can use so-called streaming to receive a message in parts, as is done on a website, instead of waiting for it to be completely generated:

import asyncio

from PyCharacterAI import get_client
from PyCharacterAI.exceptions import SessionClosedError

token = "TOKEN"
character_id = "ID"


async def main():
    client = await get_client(token=token)

    me = await client.account.fetch_me()
    print(f'Authenticated as @{me.username}')

    chat, greeting_message = await client.chat.create_chat(character_id)

    print(f"[{greeting_message.author_name}]: {greeting_message.get_primary_candidate().text}")

    try:
        while True:
            # NOTE: input() is blocking function!
            message = input(f"[{me.name}]: ")

            answer = await client.chat.send_message(character_id, chat.chat_id, message, streaming=True)

            printed_length = 0
            async for message in answer:
                if printed_length == 0:
                    print(f"[{message.author_name}]: ", end="")

                text = message.get_primary_candidate().text
                print(text[printed_length:], end="")

                printed_length = len(text)
            print("\n")

    except SessionClosedError:
        print("session closed. Bye!")

    finally:
        # Don't forget to explicitly close the session
        await client.close_session()

asyncio.run(main())

Working with images

# We can generate images from a prompt
# (It will return list of urls)
images = await client.utils.generate_image("prompt")

# We can upload an image to use it as an 
# avatar for character/persona/profile

# NOTE: This method requires the specified web_next_auth token
avatar_file = "path to file or url"
avatar = await client.utils.upload_avatar(avatar_file)

Working with voices

# We can search for voices
voices = await client.utils.search_voices("name")

# We can upload the audio as a voice
voice_file = "path to file or url"
voice = await client.utils.upload_voice(voice_file, "voice name")

# We can set and unset a voice for character  
await client.account.set_voice("character_id", "voice_id")
await client.account.unset_voice("character_id")

# And we can use voice to generate speech from the character's messages
speech = await client.utils.generate_speech("chat_id", "turn_id", "candidate_id", "voice_id")

# It will return bytes, so we can use it for example like this:
filepath = "voice.mp3"

with open(filepath, 'wb') as f:
  f.write(speech)
# or we can get just the url.
speech_url = await client.utils.generate_speech("chat_id", "turn_id", "candidate_id", 
                                            "voice_id", return_url=True)

Special Thanks

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pycharacterai-2.2.45.tar.gz (371.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pycharacterai-2.2.45-py3-none-any.whl (25.1 kB view details)

Uploaded Python 3

File details

Details for the file pycharacterai-2.2.45.tar.gz.

File metadata

  • Download URL: pycharacterai-2.2.45.tar.gz
  • Upload date:
  • Size: 371.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for pycharacterai-2.2.45.tar.gz
Algorithm Hash digest
SHA256 0584d2fdc6c6cfd2980b1886783c50cec19088792f08f1a99b529ccc4fb37526
MD5 82313a2e2866a2b78da6f732b161ee0d
BLAKE2b-256 a9ea3b218d7982ceb4768d2cee6f073f6cfaa2fbf03fb1f1b78a51de590282fb

See more details on using hashes here.

File details

Details for the file pycharacterai-2.2.45-py3-none-any.whl.

File metadata

  • Download URL: pycharacterai-2.2.45-py3-none-any.whl
  • Upload date:
  • Size: 25.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for pycharacterai-2.2.45-py3-none-any.whl
Algorithm Hash digest
SHA256 bce1394490d9d586f2b2a4494c1c287b3fe11605931cc44d795dceb7c711d579
MD5 5a6bd92aea738ff1a9bcb19ebf5deb9b
BLAKE2b-256 14a973ba580b385bd4f3899b2c951dbac91c19bb23933b1fccc4d3409c133c20

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page