Spaces:
Runtime error
Runtime error
Download app.py from RockCoder23/cai3: direct link, hf CLI and curl.
- Browser
- Download file 1.21 kB
-
https://huggingface.co/spaces/RockCoder23/cai3/resolve/main/app.py
- Command line
-
hf download hf://spaces/RockCoder23/cai3/app.py
-
curl -L -o app.py https://huggingface.co/spaces/RockCoder23/cai3/resolve/main/app.py
1.21 kB
| import os | |
| from fastapi import FastAPI, HTTPException, Query | |
| from PyCharacterAI import get_client | |
| from PyCharacterAI.exceptions import SessionClosedError | |
| app = FastAPI() | |
| # Environment variables | |
| TOKEN = os.getenv("CHARACTERAI_TOKEN") | |
| CHARACTER_ID = os.getenv("CHARACTERAI_CHARACTER_ID") | |
| async def chat_with_character(message: str = Query(..., description="Message to send")): | |
| if not TOKEN or not CHARACTER_ID: | |
| raise HTTPException(status_code=500, detail="Missing API token or character ID") | |
| try: | |
| # Initialize client and create chat on each request | |
| client = await get_client(token=TOKEN) | |
| me = await client.account.fetch_me() | |
| chat, greeting_message = await client.chat.create_chat(CHARACTER_ID) | |
| answer = await client.chat.send_message(CHARACTER_ID, chat.chat_id, message) | |
| await client.close_session() | |
| 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)) | |