### Install PyCharacterAI Library Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/getting_started.md Installs the PyCharacterAI library using pip. This is the first step to using the library's functionalities. ```bash pip install PyCharacterAI ``` -------------------------------- ### Generate Image from Prompt Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/utils.md Generates images based on a text prompt. Accepts a prompt string and returns a list of URLs for the generated images. Example shows printing the image URLs. ```Python async def generate_image(prompt: str) -> List[str]: # generates the images for given prompt. # Returns a list of links to generated images. pass # Example: # prompt = "moon and sea" # # images = await client.utils.generate_image(prompt) # # print(f"generated images by the prompt \"{prompt}\": ") # # for image_url in images: # print(image_url) ``` -------------------------------- ### Search Voices by Name Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/utils.md Searches for voices based on a provided name. Takes a voice_name string and returns a list of matching Voice objects. Example demonstrates iterating through results. ```Python async def search_voices(voice_name: str) -> List[Voice]: # searches for voices by given name. pass # Example: # voice_name = "girl" # voices = await client.utils.search_voices(voice_name) # # print(f"search results for {voice_name}: ") # # for voice in voices: # print(f"{voice.name} [{voice.voice_id}]") ``` -------------------------------- ### Get Authenticated Client Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/getting_started.md Provides an alternative method to obtain an authenticated client instance by directly calling 'get_client' with the necessary tokens. ```python from PyCharacterAI import get_client client = await get_client(token="TOKEN", web_next_auth="WEB_NEXT_AUTH") ``` -------------------------------- ### Stream Messages with PyCharacterAI Source: https://context7.com/xtr4f/pycharacterai/llms.txt This example demonstrates how to receive character responses in real-time using the streaming feature. Messages are printed as they are generated, mimicking the user experience on the Character.AI website. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") character_id = "YOUR_CHARACTER_ID" chat, greeting = await client.chat.create_chat(character_id) print(f"[{greeting.author_name}]: {greeting.get_primary_candidate().text}") # Send message with streaming enabled answer = await client.chat.send_message( character_id, chat.chat_id, "Tell me a story about a dragon", 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="", flush=True) printed_length = len(text) print("\n") await client.close_session() asyncio.run(main()) ``` -------------------------------- ### GET /fetch_following_messages Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/chat.md Fetches all messages following a specific turn in a character chat. ```APIDOC ## GET /fetch_following_messages ### Description Fetches all the messages following a given message in the chat with a character. ### Method GET ### Endpoint /fetch_following_messages ### Parameters #### Query Parameters - **chat_id** (str) - Required - id of the chat. - **turn_id** (str) - Required - id of the message relative to which you're trying to fetch the following ones. - **pinned_only** (bool) - Optional (default: False) - whether to fetch only the messages you have been pinned. ### Response #### Success Response (200) - **List[Turn]** (List) - A list of message turns. ``` -------------------------------- ### GET /characters/search Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/character.md Search for characters by name. ```APIDOC ## GET /characters/search ### Description Searches for characters based on a provided name string. ### Method GET ### Endpoint /characters/search ### Parameters #### Query Parameters - **character_name** (string) - Required - The name of the character to search for. ### Response #### Success Response (200) - **results** (List[CharacterShort]) - List of matching characters. #### Response Example [ {"name": "Catgirl", "character_id": "abc-123"} ] ``` -------------------------------- ### GET /characters/categories Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/character.md Fetches characters grouped by their respective categories. ```APIDOC ## GET /characters/categories ### Description Fetches characters by categories. Returns a dictionary where the key is the category name and the value is a list of characters. ### Method GET ### Endpoint /characters/categories ### Response #### Success Response (200) - **data** (Dict[str, List[CharacterShort]]) - Map of categories to character lists. #### Response Example { "Anime": [{"name": "Example", "character_id": "123"}] } ``` -------------------------------- ### Get Avatar URL - Python Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/types/media.md Generates a URL for an avatar image, with options for size and animation. This method is part of the Avatar class and returns a string URL. It accepts integer size and boolean animated parameters. ```Python def get_url(size: int = 400, animated: bool = False) -> str: """returns link to the avatar image.""" pass ``` -------------------------------- ### Get Avatar File Name - Python Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/types/media.md Retrieves the relative file path for an avatar. This method is part of the Avatar class and returns a string representing the avatar's file name. ```Python def get_file_name() -> str: """returns avatar file name (a.k.a. avatar_rel_path)""" pass ``` -------------------------------- ### Search Characters (Python) Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/character.md Searches for characters based on a provided name. Takes a character name string as input and returns a list of CharacterShort objects that match the search query. Includes an example of how to use the function and print results. This is an asynchronous operation. ```Python async def search_characters(character_name: str) -> List[CharacterShort]: # searches for characters. # Params: # - character_name: str - name of the character. pass # Example: # name = "Catgirl" # Why not. # characters = await client.character.search_characters(name) # print(f"Search results for {name}:") # for character in characters: # print(f"Name: {character.name}. Id: {character.character_id}") ``` -------------------------------- ### Initialize and Authenticate Client Source: https://github.com/xtr4f/pycharacterai/blob/main/README.md Demonstrates how to import the Client class, instantiate it, and authenticate using the required authorization tokens. Authentication is a prerequisite for accessing library methods. ```python from PyCharacterAI import Client client = Client() await client.authenticate("TOKEN") # With optional avatar upload support await client.authenticate("TOKEN", web_next_auth="WEB_NEXT_AUTH") ``` -------------------------------- ### Authenticate Client with Token Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/getting_started.md Demonstrates how to authenticate the Client instance using an authentication token. This is a prerequisite for most library operations. ```python from PyCharacterAI import Client client = Client() await client.authenticate("TOKEN") ``` -------------------------------- ### Fetch User Voices Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/account.md Retrieves a list of all voice configurations created by the user. Returns a list of Voice objects. ```Python voices = await client.account.fetch_my_voices() ``` -------------------------------- ### Fetch Account Settings Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/account.md Retrieves user settings including default persona IDs, persona overrides, and voice overrides for specific characters. Returns a dictionary containing these configurations. ```Python settings = await client.account.fetch_my_settings() default_persona_id = settings.get("default_persona_id") persona_overrides = settings.get("personaOverrides", {}) voice_overrides = settings.get("voiceOverrides", {}) print(f"My default_persona_id: {default_persona_id}") for char_id, persona_id in persona_overrides.items(): if persona_id: print(f"{char_id} -> {persona_id}") ``` -------------------------------- ### Initialize and Authenticate PyCharacterAI Client Source: https://context7.com/xtr4f/pycharacterai/llms.txt Demonstrates how to initialize the PyCharacterAI Client and authenticate using a provided token. It shows two methods: separate authentication and a one-step helper function. The `web_next_auth` token is optional for avatar uploads. Remember to close the session when done. ```python import asyncio from PyCharacterAI import Client, get_client async def main(): # Method 1: Create client and authenticate separately client = Client() await client.authenticate("YOUR_TOKEN") # Method 2: Use get_client() helper for one-step initialization client = await get_client(token="YOUR_TOKEN") # With web_next_auth for avatar upload capability client = await get_client(token="YOUR_TOKEN", web_next_auth="WEB_NEXT_AUTH") # Always close the session when done await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Authenticate Client with Token and Web Next Auth Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/getting_started.md Shows how to authenticate the Client instance with both a primary token and a 'web_next_auth' token. The 'web_next_auth' token is specifically required for avatar uploads. ```python from PyCharacterAI import Client client = Client() await client.authenticate("TOKEN", web_next_auth="WEB_NEXT_AUTH") ``` -------------------------------- ### Fetch Followers and Following Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/account.md Retrieves lists of usernames for users following the account or users being followed by the account. ```Python followers = await client.account.fetch_my_followers() for follower_username in followers: print(follower_username) following = await client.account.fetch_my_following() for following_username in following: print(following_username) ``` -------------------------------- ### Manage Chat Sessions with PyCharacterAI Source: https://github.com/xtr4f/pycharacterai/blob/main/README.md Demonstrates how to authenticate, create a chat session, and send messages to a character. Includes both standard synchronous-style message handling and advanced streaming responses for real-time output. ```Python 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) chat, greeting_message = await client.chat.create_chat(character_id) try: while True: message = input("Message: ") 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") finally: await client.close_session() asyncio.run(main()) ``` ```Python # Streaming example answer = await client.chat.send_message(character_id, chat.chat_id, message, streaming=True) printed_length = 0 async for message in answer: text = message.get_primary_candidate().text print(text[printed_length:], end="") printed_length = len(text) ``` -------------------------------- ### Create new chat session in Python Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/chat.md Initializes a new chat with a character. Optionally generates a greeting message, returning a tuple containing the chat object and the greeting turn. ```python async def create_chat(character_id: str, greeting: bool = True) -> Tuple[Chat, Optional[Turn]]: # Example usage: chat, greeting_message = await client.chat.create_chat("character_id") ``` -------------------------------- ### Fetch Account Information Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/account.md Retrieves the current user's account details such as name, username, and bio. Returns an Account object. ```Python account = await client.account.fetch_me() print(f"My name: {account.name}\n" f"My firstname: {account.first_name}\n" f"My username: {account.username}\n" f"My bio: {account.bio}") ``` -------------------------------- ### Handle Images and Avatars Source: https://github.com/xtr4f/pycharacterai/blob/main/README.md Utilities for generating images from text prompts and uploading files to serve as character or profile avatars. Requires appropriate authentication tokens for upload operations. ```Python images = await client.utils.generate_image("prompt") avatar = await client.utils.upload_avatar("path/to/file") ``` -------------------------------- ### Upload Voice Data Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/utils.md Uploads audio data to create a new voice. Requires a voice file path/URL, a name (3-20 chars), and optionally a description (max 120 chars) and visibility ('public' or 'private'). Returns the created Voice object. ```Python async def upload_voice(voice: str, name: str, description: str = "", visibility: str = "private") -> Voice: # uploads your audio as a voice for characters. pass # Example: # voice_file = "path to file or url" # voice = await client.utils.upload_voice(voice_file, "voice name", "voice description") # # print(f"voice uploaded successfully.\n" # f"voice_id: {voice.voice_id}\n" # f"preview: {voice.preview_audio_url}") ``` -------------------------------- ### Chat with Characters using PyCharacterAI Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/getting_started.md Demonstrates how to authenticate, initialize a chat session, and send messages to a character. Includes both standard response handling and real-time streaming of character messages. ```Python 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() chat, greeting_message = await client.chat.create_chat(character_id) try: while True: 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: await client.close_session() asyncio.run(main()) ``` ```Python import asyncio from PyCharacterAI import get_client from PyCharacterAI.exceptions import SessionClosedError async def main(): client = await get_client(token="TOKEN") chat, greeting_message = await client.chat.create_chat("ID") answer = await client.chat.send_message("ID", chat.chat_id, "Hello", streaming=True) printed_length = 0 async for message in answer: text = message.get_primary_candidate().text print(text[printed_length:], end="") printed_length = len(text) await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Fetch Personas Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/account.md Retrieves details for a specific persona by ID or lists all personas associated with the account. Returns Persona objects. ```Python my_personas = await client.account.fetch_my_personas() for persona in my_personas: print(f"Persona name: {persona.name}\nPersona id: {persona.persona_id}") ``` -------------------------------- ### Fetch Recommended Characters (Python) Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/character.md Fetches a list of recommended characters. This is an asynchronous function that returns a list of CharacterShort objects, representing characters suggested by the platform. It requires an active client connection. ```Python async def fetch_recommended_characters() -> List[CharacterShort]: # fetches recommended characters. pass ``` -------------------------------- ### Manage Voices and Speech Synthesis Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/getting_started.md Functions to search for voices, upload custom audio as voices, assign voices to characters, and generate speech audio from chat messages. ```Python # Search and upload voices voices = await client.utils.search_voices("name") voice = await client.utils.upload_voice("path/to/file", "voice name") # Assign voice to character await client.account.set_voice("character_id", "voice_id") # Generate speech speech = await client.utils.generate_speech("chat_id", "turn_id", "candidate_id", "voice_id") with open("voice.mp3", 'wb') as f: f.write(speech) ``` -------------------------------- ### Upload Avatar Image Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/utils.md Uploads an image to be used as an avatar. Accepts a file path or URL for the image and an optional boolean to check image validity. Requires a web_next_auth token. Returns an Avatar object. ```Python async def upload_avatar(image: str, check_image: bool = True) -> Avatar: # uploads your image to use it as an avatar for character/persona/profile. # NOTE: This method requires the specified web_next_auth token pass # Example: # avatar_file = "path to file or url" # # avatar = await client.utils.upload_avatar(avatar_file) # # print(f"avatar uploaded successfully. Url: {avatar.get_url()}\n") # # # You can use this as an avatar_rel_path # filename = avatar.get_file_name() # print(f"avatar rel path: {filename}") ``` -------------------------------- ### Create a New AI Character Source: https://context7.com/xtr4f/pycharacterai/llms.txt Allows the creation of a new character by providing parameters like name, greeting, description, and visibility settings. Returns the created character object containing the new character ID. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") character = await client.character.create_character( name="My Assistant", greeting="Hello! I'm your helpful assistant.", title="A friendly AI helper", description="An assistant that helps with various tasks", definition="{{char}} is a helpful and friendly assistant.", copyable=False, visibility="private" ) print(f"Created character: {character.name}") await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Fetch Account Information with PyCharacterAI Source: https://context7.com/xtr4f/pycharacterai/llms.txt This code snippet shows how to retrieve the authenticated user's account details, including their name, first name, username, and bio, using the `fetch_me` method. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") account = await client.account.fetch_me() print(f"Name: {account.name}") print(f"First name: {account.first_name}") print(f"Username: {account.username}") print(f"Bio: {account.bio}") await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Create and Manage User Personas Source: https://context7.com/xtr4f/pycharacterai/llms.txt Provides functionality to create, list, set as default, assign to specific characters, and delete user personas. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") # Create a new persona persona = await client.account.create_persona( name="Explorer", definition="I am an adventurous explorer who loves discovering new places and learning about different cultures.", avatar_rel_path="" # Optional avatar filename ) print(f"Created persona: {persona.name} (ID: {persona.persona_id})") # Fetch all personas my_personas = await client.account.fetch_my_personas() print("\nMy personas:") for p in my_personas: print(f" {p.name} - {p.title} [{p.persona_id}]") # Set as default persona await client.account.set_default_persona(persona.persona_id) print(f"\nSet '{persona.name}' as default persona") # Set persona for specific character character_id = "YOUR_CHARACTER_ID" await client.account.set_persona(character_id, persona.persona_id) # Unset persona from character await client.account.unset_persona(character_id) # Delete persona await client.account.delete_persona(persona.persona_id) print(f"Deleted persona: {persona.name}") await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Implement Voice Synthesis and Management Source: https://github.com/xtr4f/pycharacterai/blob/main/README.md Functions to search for voices, upload custom audio, assign voices to characters, and generate speech from chat messages. Supports returning raw audio bytes or direct URLs. ```Python voices = await client.utils.search_voices("name") await client.account.set_voice("character_id", "voice_id") speech = await client.utils.generate_speech("chat_id", "turn_id", "candidate_id", "voice_id") with open("voice.mp3", 'wb') as f: f.write(speech) ``` -------------------------------- ### Configure Character Personas and Voices Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/account.md Assigns or removes specific personas and voices for individual characters using their unique identifiers. Passing None to the set methods removes the current assignment. ```Python async def set_persona(character_id: str, persona_id: Union[str, None]) -> bool async def unset_persona(character_id: str) -> bool async def set_voice(character_id: str, voice_id: Union[str, None]) -> bool async def unset_voice(character_id: str) -> bool ``` -------------------------------- ### Fetch Account Settings using PyCharacterAI Source: https://context7.com/xtr4f/pycharacterai/llms.txt Retrieves the authenticated user's settings, including default persona and character-specific persona or voice overrides. It requires a valid authentication token and returns a dictionary of settings. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") settings = await client.account.fetch_my_settings() default_persona_id = settings.get("default_persona_id") persona_overrides = settings.get("personaOverrides", {}) voice_overrides = settings.get("voiceOverrides", {}) print(f"Default persona ID: {default_persona_id}") print("\nPersona overrides for characters:") for char_id, persona_id in persona_overrides.items(): if persona_id: print(f" {char_id} -> {persona_id}") print("\nVoice overrides for characters:") for char_id, voice_id in voice_overrides.items(): if voice_id: print(f" {char_id} -> {voice_id}") await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Fetch Voice by ID Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/utils.md Fetches a specific voice using its unique identifier. Requires a voice_id string and returns a Voice object. ```Python async def fetch_voice(voice_id: str) -> Voice: # fetches a voice by given voice id. pass ``` -------------------------------- ### Manage Images with PyCharacterAI Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/getting_started.md Utilities for generating images from text prompts and uploading files to serve as avatars for characters or user profiles. ```Python # Generate images by prompt images = await client.utils.generate_image("prompt") # Upload avatar (requires web_next_auth token) avatar = await client.utils.upload_avatar("path/to/file") ``` -------------------------------- ### Manage Personas Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/account.md Provides functionality to create, edit, and delete user personas. These methods return a Persona object representing the state of the modified persona. ```Python async def create_persona(name: str, definition: str, avatar_rel_path: str) -> Persona async def edit_persona(persona_id: str, name: str, definition: str, avatar_rel_path: str) -> Persona async def delete_persona(persona_id: str) -> bool ``` -------------------------------- ### POST /create_chat Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/chat.md Creates a new chat session with a specific character. ```APIDOC ## POST /create_chat ### Description Creates a new chat with the character. Returns a tuple containing the chat object and the greeting message. ### Method POST ### Endpoint /create_chat ### Parameters #### Request Body - **character_id** (str) - Required - id of the character you're trying to create a chat with. - **greeting** (bool) - Optional (default: True) - whether to generate a greeting message. ### Response #### Success Response (200) - **chat** (Chat) - The created chat object. - **greeting_message** (Optional[Turn]) - The initial greeting message. ``` -------------------------------- ### Configure Default Personas Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/account.md Sets or unsets a global default persona for characters. Passing None to the set method clears the current default. ```Python async def set_default_persona(persona_id: Union[str, None]) -> bool async def unset_default_persona() -> bool ``` -------------------------------- ### POST /characters/create Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/character.md Creates a new character on the platform. ```APIDOC ## POST /characters/create ### Description Creates a new character with specified attributes like name, greeting, and visibility. ### Method POST ### Endpoint /characters/create ### Parameters #### Request Body - **name** (string) - Required - Character name (3-20 chars). - **greeting** (string) - Required - Initial greeting (3-2048 chars). - **visibility** (string) - Optional - Visibility status (public, unlisted, private). ### Response #### Success Response (200) - **character** (Character) - The created character object. #### Response Example { "name": "New Character", "character_id": "xyz-789" } ``` -------------------------------- ### Fetch User Voices by Username Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/user.md Fetches a list of all voices associated with a specific user, identified by their username. The function is asynchronous and returns a list of Voice objects. It requires the username as a string parameter. ```Python async def fetch_user_voices(username: str) -> List[Voice]: # fetches information about user's voices. ``` -------------------------------- ### POST /utils/generate_speech Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/utils.md Generates speech audio from a specific character message candidate. Supports returning either raw audio bytes or a direct URL. ```APIDOC ## POST /utils/generate_speech ### Description Generates speech from the character's message candidate. This method allows retrieving the audio data directly as bytes or as a URL. ### Method POST ### Endpoint utils.generate_speech(chat_id, turn_id, candidate_id, voice_id, **kwargs) ### Parameters #### Path Parameters - **chat_id** (str) - Required - The unique identifier of the chat. - **turn_id** (str) - Required - The unique identifier of the message turn. - **candidate_id** (str) - Required - The unique identifier of the message candidate. - **voice_id** (str) - Required - The unique identifier of the voice to be used. #### Query Parameters - **return_url** (bool) - Optional (default: False) - If set to True, returns the URL to the generated speech instead of raw bytes. ### Request Example ```python # Requesting raw audio bytes speech = await client.utils.generate_speech("chat_id", "turn_id", "candidate_id", "voice_id") # Requesting audio URL speech_url = await client.utils.generate_speech("chat_id", "turn_id", "candidate_id", "voice_id", return_url=True) ``` ### Response #### Success Response (200) - **result** (bytes | str) - Returns the audio binary data or the URL string depending on the return_url parameter. #### Response Example ```python # Bytes response b'\xff\xfb\x90...' # URL response "https://example.com/audio/speech.mp3" ``` ``` -------------------------------- ### Send and Stream Messages in PyCharacterAI Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/chat.md Demonstrates how to send a message to a character and handle the response using streaming. It iterates through the async generator to print the response in real-time as it is generated. ```python while True: my_message = input(f"my message: ") answer = await client.chat.send_message("character_id", "chat_id", my_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") ``` -------------------------------- ### Search Creators (Python) Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/character.md Searches for creators based on a provided name. Takes a creator name string as input and returns a list of creator usernames (strings). This asynchronous function is useful for finding users who have created characters. ```Python async def search_creators(creator_name: str) -> List[str]: # searches for creators. # Returns list of creator usernames. # Params: # - creator_name: str - name of the creator. pass ``` -------------------------------- ### Fetch Characters and Upvoted Content Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/account.md Retrieves lists of characters created by the user or characters the user has upvoted. Returns a list of CharacterShort objects. ```Python my_characters = await client.account.fetch_my_characters() for character in my_characters: print(f"Character name: {character.name}\nCharacter id: {character.character_id}") ``` -------------------------------- ### Fetch Characters by Category Source: https://context7.com/xtr4f/pycharacterai/llms.txt Retrieves a dictionary of characters organized by platform categories such as Featured or Recommended. Useful for building discovery interfaces. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") characters = await client.character.fetch_characters_by_category() for category in characters: print(f"\n{category}:") for character in characters[category][:3]: print(f" {character.name} [{character.character_id}]") await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Fetch Chat History and Sessions in Python Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/chat.md Methods for retrieving historical chat data, specific chat sessions, and recent interactions with characters. These functions return lists of Chat or ChatHistory objects based on the provided character or chat IDs. ```Python async def fetch_histories(character_id: str, amount: int = 50) -> List[ChatHistory]: async def fetch_chats(character_id: str) -> List[Chat]: async def fetch_chat(chat_id: str) -> Chat async def fetch_recent_chats() -> List[Chat]: chats = await client.chat.fetch_recent_chats() print("I have recent chats with:") for chat in chats: print(f"{chat.character_name} - [{chat.character_id}]") ``` -------------------------------- ### Ping Service Availability Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/utils.md Sends a ping request to check the service availability. Returns a boolean indicating success. ```Python async def ping() -> bool: # sends a ping request. pass ``` -------------------------------- ### Generate Alternative Character Responses Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/chat.md Shows how to generate alternative turn candidates for a specific message. Supports both standard and streaming modes to fetch new responses from the character. ```python # without streaming answer = await client.chat.send_message("character_id", "chat_id", "message") for counter in range(1, 4): alternative_answer = await client.chat.another_response("character_id", "chat_id", answer.turn_id) print(f"alternative character response #{counter}: \n{alternative_answer.get_primary_candidate().text}\n") ``` ```python # with streaming async def print_and_return_answer(answer): printed_length = 0 answer_turn = None async for message in answer: text = message.get_primary_candidate().text print(text[printed_length:], end="") printed_length = len(text) answer_turn = message print("\n") return answer_turn answer = await client.chat.send_message("character_id", "chat_id", "message", streaming=True) answer = await print_and_return_answer(answer) for counter in range(1, 4): alternative_answer = await client.chat.another_response("character_id", "chat_id", answer.turn_id, streaming=True) await print_and_return_answer(alternative_answer) ``` -------------------------------- ### Create Character (Python) Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/character.md Creates a new character with specified attributes. This asynchronous function allows customization of name, greeting, title, description, definition, copyability, visibility, avatar, and default voice. It returns the created Character object. Input validation for parameters like name length and description limits is enforced. ```Python async def create_character(name: str, greeting: str, title: str = "", description: str = "", definition: str = "", copyable: bool = False, visibility: str = "PRIVATE", avatar_rel_path: str = "", default_voice_id: str = "") -> Character: # creates new character. # Params: # - name: str - character name (must be at least 3 characters and no more than 20). # - greeting: str - character greeting (must be at least 3 characters and no more than 2048). # - title: str (optional) - character title (must be at least 3 characters and no more than 50). # - description: str (optional) - character description (must be no more than 500 characters). # - definition: str (optional) - character definition (must be no more than 32000 characters). # - copyable: bool (optional, default: False) - whether the character can be copied. In other words, whether its definition is visible. # - visibility: str (optional, default: "private") - character visibility (public, unlisted or private). # - avatar_rel_path: str (optional) - avatar filename on c.ai server. # - default_voice_id: str (optional) - id of the voice that will be the default character voice. pass ``` -------------------------------- ### Fetch Featured Characters (Python) Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/character.md Fetches a list of featured characters. This asynchronous function returns a list of CharacterShort objects, highlighting prominent or curated characters. An active client connection is necessary. ```Python async def fetch_featured_characters() -> List[CharacterShort]: # fetches featured characters. pass ``` -------------------------------- ### Follow User by Username Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/user.md Allows the current user to follow another user specified by their username. This is an asynchronous operation that returns a boolean value indicating success (True) or failure (False). The username must be provided as a string. ```Python async def follow_user(username: str) -> bool: # follows you to the user. ``` -------------------------------- ### Generate Alternative Responses Source: https://context7.com/xtr4f/pycharacterai/llms.txt Generates alternative character responses for a specific message turn, effectively utilizing the swipe feature. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") character_id = "YOUR_CHARACTER_ID" chat, _ = await client.chat.create_chat(character_id) # Send initial message answer = await client.chat.send_message(character_id, chat.chat_id, "Tell me a joke") print(f"Response 1: {answer.get_primary_candidate().text}") # Generate alternative responses (swipe feature) for i in range(2): alternative = await client.chat.another_response( character_id, chat.chat_id, answer.turn_id ) print(f"Response {i+2}: {alternative.get_primary_candidate().text}") await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Upload and Manage Custom Voices with PyCharacterAI Source: https://context7.com/xtr4f/pycharacterai/llms.txt Uploads an audio file to create a custom voice, allows editing its name and description, and deleting it. Requires a user token. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") # Upload a voice from file or URL voice_file = "path/to/voice.mp3" # or URL voice = await client.utils.upload_voice( voice=voice_file, name="My Custom Voice", description="A custom voice for my characters", visibility="private" # "public" or "private" ) print(f"Voice uploaded successfully!") print(f"Voice ID: {voice.voice_id}") print(f"Preview: {voice.preview_audio_url}") # Edit the voice edited_voice = await client.utils.edit_voice( voice=voice.voice_id, name="Renamed Voice", description="Updated description" ) # Delete the voice await client.utils.delete_voice(voice.voice_id) print("Voice deleted") await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Generate speech from character messages in Python Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/utils.md The generate_speech method converts a specific message candidate into audio data. It accepts chat, turn, candidate, and voice identifiers, returning either the raw audio bytes or a URL depending on the return_url parameter. ```Python speech = await client.utils.generate_speech("chat_id", "turn_id", "candidate_id", "voice_id") filepath = "voice.mp3" with open(filepath, 'wb') as f: f.write(speech) ``` ```Python # or you can get just the url. speech_url = await client.utils.generate_speech("chat_id", "turn_id", "candidate_id", "voice_id", return_url=True) ``` -------------------------------- ### Generate Images with PyCharacterAI Source: https://context7.com/xtr4f/pycharacterai/llms.txt Generates images from a text prompt using Character.AI's image generation service. Requires a user token. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") prompt = "A beautiful sunset over the ocean with sailing boats" images = await client.utils.generate_image(prompt) print(f"Generated images for prompt: '{prompt}'") for i, image_url in enumerate(images, 1): print(f" Image {i}: {image_url}") await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Manage Social Connections with PyCharacterAI Source: https://context7.com/xtr4f/pycharacterai/llms.txt Demonstrates how to follow or unfollow users and retrieve lists of followers and following. It utilizes the client's user and account modules to manage social state. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") username = "example_user" # Follow a user success = await client.user.follow_user(username) print(f"Followed {username}: {success}") # Check followers/following followers = await client.account.fetch_my_followers() following = await client.account.fetch_my_following() print(f"\nFollowers ({len(followers)}):") for follower in followers: print(f" {follower}") print(f"\nFollowing ({len(following)}):") for user in following: print(f" {user}") # Unfollow a user success = await client.user.unfollow_user(username) print(f"\nUnfollowed {username}: {success}") await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Fetch Chat Messages and Pinned Content in Python Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/chat.md Functions to retrieve messages from a specific chat, supporting pagination via tokens and filtering for pinned messages. These methods return Turn objects representing individual messages within a conversation. ```Python async def fetch_messages(chat_id, pinned_only: bool = False, next_token: str = None) -> Tuple[List[Turn], Optional[str]]: async def fetch_all_messages(chat_id, pinned_only: bool = False) -> List[Turn]: async def fetch_pinned_messages(chat_id, next_token: str = None) -> [List[Turn], Optional[str]]: async def fetch_all_pinned_messages(chat_id: str) -> List[Turn]: next_token = None while True: messages, next_token = await client.chat.fetch_messages(chatc, next_token=next_token) if not messages: break for message in messages: print(f"[{message.author_name}]: {message.get_primary_candidate().text}") if not next_token: break ``` -------------------------------- ### Search and Manage Voices with PyCharacterAI Source: https://context7.com/xtr4f/pycharacterai/llms.txt Searches for voices, fetches specific voice details, and manages voice settings for characters. Requires a user token. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") # Search for voices voice_name = "girl" voices = await client.utils.search_voices(voice_name) print(f"Search results for '{voice_name}':") for voice in voices[:5]: print(f" {voice.name} [{voice.voice_id}]") # Fetch a specific voice voice_id = "YOUR_VOICE_ID" voice = await client.utils.fetch_voice(voice_id) print(f"\nVoice details: {voice.name}") # Set voice for a character character_id = "YOUR_CHARACTER_ID" await client.account.set_voice(character_id, voice_id) print(f"Set voice for character") # Unset voice await client.account.unset_voice(character_id) print("Voice unset") await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Fetch Similar Characters (Python) Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/character.md Fetches characters that are similar to a given character. Requires the character's ID as a string input. Returns a list of CharacterShort objects. This is an asynchronous operation. ```Python async def fetch_similar_characters(character_id: str) -> List[CharacterShort]: # fetches similar characters. # Params: # - character_id: str - id of the character. pass ``` -------------------------------- ### Edit User Account Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/account.md Updates the authenticated user's account details including name, username, bio, and avatar. Requires valid string inputs within specified character limits. ```Python async def edit_account(name: str, username: str, bio: str, avatar_rel_path: str) -> bool ``` -------------------------------- ### Create Chat and Send Messages with PyCharacterAI Source: https://context7.com/xtr4f/pycharacterai/llms.txt This snippet shows how to create a new chat session with a Character AI character and send messages. It first fetches the authenticated user's details, then creates a chat using the character ID. The conversation continues in a loop until the session is closed. ```python import asyncio from PyCharacterAI import get_client from PyCharacterAI.exceptions import SessionClosedError async def main(): client = await get_client(token="YOUR_TOKEN") me = await client.account.fetch_me() print(f"Authenticated as @{me.username}") # Create a new chat with a character (character_id from Character.AI) character_id = "YOUR_CHARACTER_ID" chat, greeting_message = await client.chat.create_chat(character_id) print(f"Chat ID: {chat.chat_id}") print(f"[{greeting_message.author_name}]: {greeting_message.get_primary_candidate().text}") try: while True: user_input = input(f"[{me.name}]: ") answer = await client.chat.send_message(character_id, chat.chat_id, user_input) print(f"[{answer.author_name}]: {answer.get_primary_candidate().text}") except SessionClosedError: print("Session closed. Bye!") finally: await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Fetch User Information by Username Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/user.md Retrieves public information about a user given their username. Returns a PublicUser object if found, otherwise None. This function is asynchronous and requires a username string as input. ```Python async def fetch_user(username: str) -> Union[PublicUser, None]: # fetches information about user by username. ``` -------------------------------- ### Fetch Chat Messages with Pagination Source: https://context7.com/xtr4f/pycharacterai/llms.txt Retrieves messages from a specific chat session using pagination. It iterates through message pages until no more messages are available. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") chat_id = "YOUR_CHAT_ID" next_token = None while True: messages, next_token = await client.chat.fetch_messages(chat_id, next_token=next_token) if not messages: break for message in messages: time = f"{message.create_time.hour}:{message.create_time.minute:02d}" author = message.author_name text = message.get_primary_candidate().text print(f"({time}) [{author}]: {text[:100]}...") if not next_token: break await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Fetch User Information with PyCharacterAI Source: https://context7.com/xtr4f/pycharacterai/llms.txt Retrieves public profile details and voice data for a specific user by their username. This requires an authenticated client session and returns user object attributes like username, name, and bio. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") username = "example_user" user = await client.user.fetch_user(username) if user: print(f"Username: {user.username}") print(f"Name: {user.name}") print(f"Bio: {user.bio}") # Fetch user's public voices voices = await client.user.fetch_user_voices(username) print(f"\nPublic voices by {username}:") for voice in voices: print(f" {voice.name} [{voice.voice_id}]") else: print("User not found") await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Archive and unarchive chats in Python Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/chat.md Utility functions to manage the archive status of a specific chat session using its unique identifier. ```python async def archive_chat(chat_id: str) -> bool async def unarchive_chat(chat_id: str) -> bool ``` -------------------------------- ### Fetch Characters by Category (Python) Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/character.md Fetches characters organized by categories. Returns a dictionary where keys are category names and values are lists of CharacterShort objects. This function is asynchronous and requires an active client connection. ```Python async def fetch_characters_by_category() -> Dict[str, List[CharacterShort]]: # fetches characters by categories. # Returns dict, where key is category and value is list of characters related to this category. pass # Example: # characters = await client.character.fetch_characters_by_category() # for category in characters: # print(f"\n{category}: ") # for character in characters[category]: # print(f"{character.name} [{character.character_id}]") ``` -------------------------------- ### Fetch following messages in Python Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/chat.md Retrieves a list of messages that occur after a specified turn ID within a character chat. Supports an optional filter to return only pinned messages. ```python async def fetch_following_messages(chat_id: str, turn_id: str, pinned_only: bool = False) -> List[Turn]: ``` -------------------------------- ### Edit Existing Voice Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/utils.md Edits an existing voice identified by its ID or Voice object. Allows modification of name, description, and visibility. Returns the updated Voice object. ```Python async def edit_voice(voice: Union[str, Voice], name: str = None, description: str = None, visibility: str = None) -> Voice: # edits your voice. pass ``` -------------------------------- ### Upload Avatar with PyCharacterAI Source: https://context7.com/xtr4f/pycharacterai/llms.txt Uploads an image to be used as an avatar for characters, personas, or profiles. Requires both user token and web_next_auth token. ```python import asyncio from PyCharacterAI import get_client async def main(): # Note: web_next_auth token is required for avatar uploads client = await get_client( token="YOUR_TOKEN", web_next_auth="YOUR_WEB_NEXT_AUTH" ) avatar_file = "path/to/avatar.png" # or URL avatar = await client.utils.upload_avatar(avatar_file) print(f"Avatar uploaded successfully!") print(f"URL: {avatar.get_url()}") print(f"Relative path (for API use): {avatar.get_file_name()}") await client.close_session() asyncio.run(main()) ``` -------------------------------- ### Fetch Character Info (Python) Source: https://github.com/xtr4f/pycharacterai/blob/main/docs/api_reference/methods/character.md Fetches detailed information about a specific character using their ID. The function takes a character ID string and returns a Character object containing comprehensive details. This is an asynchronous method. ```Python async def fetch_character_info(character_id: str) -> Character: # fetches information about character. # Params: # - character_id: str - id of the character. pass ``` -------------------------------- ### Search and Fetch Character Information Source: https://context7.com/xtr4f/pycharacterai/llms.txt Provides methods to search for characters by name or retrieve detailed metadata for a specific character using their unique ID. These functions are essential for discovering and inspecting character profiles. ```python import asyncio from PyCharacterAI import get_client async def main(): client = await get_client(token="YOUR_TOKEN") # Search name = "Assistant" characters = await client.character.search_characters(name) # Fetch Info character_id = "YOUR_CHARACTER_ID" character = await client.character.fetch_character_info(character_id) await client.close_session() asyncio.run(main()) ```