Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from fastapi import FastAPI, HTTPException, Query
|
| 3 |
+
from PyCharacterAI import get_client
|
| 4 |
+
from PyCharacterAI.exceptions import SessionClosedError
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
# Environment variables
|
| 9 |
+
TOKEN = os.getenv("CHARACTERAI_TOKEN")
|
| 10 |
+
CHARACTER_ID = os.getenv("CHARACTERAI_CHARACTER_ID")
|
| 11 |
+
|
| 12 |
+
@app.get("/chat")
|
| 13 |
+
async def chat_with_character(message: str = Query(..., description="Message to send")):
|
| 14 |
+
if not TOKEN or not CHARACTER_ID:
|
| 15 |
+
raise HTTPException(status_code=500, detail="Missing API token or character ID")
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
# Initialize client and create chat on each request
|
| 19 |
+
client = await get_client(token=TOKEN)
|
| 20 |
+
me = await client.account.fetch_me()
|
| 21 |
+
chat, greeting_message = await client.chat.create_chat(CHARACTER_ID)
|
| 22 |
+
|
| 23 |
+
answer = await client.chat.send_message(CHARACTER_ID, chat.chat_id, message)
|
| 24 |
+
await client.close_session()
|
| 25 |
+
|
| 26 |
+
return {
|
| 27 |
+
"author": answer.author_name,
|
| 28 |
+
"response": answer.get_primary_candidate().text
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
except SessionClosedError:
|
| 32 |
+
raise HTTPException(status_code=500, detail="Session was closed")
|
| 33 |
+
except Exception as e:
|
| 34 |
+
raise HTTPException(status_code=500, detail=str(e))
|