Spaces:
Running
Running
File size: 1,227 Bytes
9fb3e55 6341735 9fb3e55 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import os
from fastapi import FastAPI, HTTPException, Query
from PyCharacterAI import get_client
from PyCharacterAI.exceptions import SessionClosedError
app = FastAPI()
# Environment variables
TOKEN = "1b57232563116c2a5f5e73fba3be3d943a99d720"
CHARACTER_ID = "8zp8K166t6uBeX760DWXxkibR5wSVk-Oi4r0NC1bQZY"
@app.get("/chat")
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))
|