Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import os
|
| 3 |
+
from fastapi import FastAPI, HTTPException, Query
|
| 4 |
+
from PyCharacterAI import get_client
|
| 5 |
+
from PyCharacterAI.exceptions import SessionClosedError
|
| 6 |
+
|
| 7 |
+
# Load token and character ID from environment variables
|
| 8 |
+
TOKEN = os.getenv("CHARACTERAI_TOKEN")
|
| 9 |
+
CHARACTER_ID = os.getenv("CHARACTERAI_CHARACTER_ID")
|
| 10 |
+
|
| 11 |
+
app = FastAPI()
|
| 12 |
+
client = None
|
| 13 |
+
chat = None
|
| 14 |
+
me = None
|
| 15 |
+
|
| 16 |
+
@app.on_event("startup")
|
| 17 |
+
async def startup_event():
|
| 18 |
+
global client, chat, me
|
| 19 |
+
|
| 20 |
+
if not TOKEN or not CHARACTER_ID:
|
| 21 |
+
raise RuntimeError("Missing CHARACTERAI_TOKEN or CHARACTERAI_CHARACTER_ID")
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
client = await get_client(token=TOKEN)
|
| 25 |
+
me = await client.account.fetch_me()
|
| 26 |
+
chat_data, greeting_message = await client.chat.create_chat(CHARACTER_ID)
|
| 27 |
+
chat = chat_data
|
| 28 |
+
|
| 29 |
+
except Exception as e:
|
| 30 |
+
raise RuntimeError("Failed to start CharacterAI client") from e
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@app.on_event("shutdown")
|
| 34 |
+
async def shutdown_event():
|
| 35 |
+
if client:
|
| 36 |
+
await client.close_session()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@app.get("/chat")
|
| 40 |
+
async def chat_with_character(message: str = Query(..., description="Message to send")):
|
| 41 |
+
global client, chat
|
| 42 |
+
|
| 43 |
+
if not client or not chat:
|
| 44 |
+
raise HTTPException(status_code=503, detail="Chat not initialized")
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
answer = await client.chat.send_message(CHARACTER_ID, chat.chat_id, message)
|
| 48 |
+
return {
|
| 49 |
+
"author": answer.author_name,
|
| 50 |
+
"response": answer.get_primary_candidate().text
|
| 51 |
+
}
|
| 52 |
+
except SessionClosedError:
|
| 53 |
+
raise HTTPException(status_code=500, detail="Session was closed")
|
| 54 |
+
except Exception as e:
|
| 55 |
+
raise HTTPException(status_code=500, detail=str(e))
|