Spaces:
Sleeping
Sleeping
| import asyncio | |
| import os | |
| from fastapi import FastAPI, HTTPException, Query | |
| from PyCharacterAI import get_client | |
| from PyCharacterAI.exceptions import SessionClosedError | |
| # Load token and character ID from environment variables | |
| TOKEN = os.getenv("CHARACTERAI_TOKEN") | |
| CHARACTER_ID = os.getenv("CHARACTERAI_CHARACTER_ID") | |
| app = FastAPI() | |
| client = None | |
| chat = None | |
| me = None | |
| async def startup_event(): | |
| global client, chat, me | |
| if not TOKEN or not CHARACTER_ID: | |
| raise RuntimeError("Missing CHARACTERAI_TOKEN or CHARACTERAI_CHARACTER_ID") | |
| try: | |
| client = await get_client(token=TOKEN) | |
| me = await client.account.fetch_me() | |
| chat_data, greeting_message = await client.chat.create_chat(CHARACTER_ID) | |
| chat = chat_data | |
| except Exception as e: | |
| raise RuntimeError("Failed to start CharacterAI client") from e | |
| async def shutdown_event(): | |
| if client: | |
| await client.close_session() | |
| async def chat_with_character(message: str = Query(..., description="Message to send")): | |
| global client, chat | |
| if not client or not chat: | |
| raise HTTPException(status_code=503, detail="Chat not initialized") | |
| try: | |
| answer = await client.chat.send_message(CHARACTER_ID, chat.chat_id, message) | |
| return { | |
| "author": answer.author_name, | |
| "response": answer.get_primary_candidate().text | |
| } | |
| except SessionClosedError: | |
| raise HTTPException(status_code=500, detail="Session was closed") | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |