File size: 2,000 Bytes
9bf7fc2
 
 
 
 
 
 
3279ad9
911afbf
9bf7fc2
 
 
083e322
 
 
9bf7fc2
 
 
083e322
9bf7fc2
3279ad9
 
8ed2dcd
3279ad9
ef93247
 
3279ad9
 
 
 
 
 
9bf7fc2
083e322
9bf7fc2
083e322
 
 
 
 
 
 
 
 
 
 
9bf7fc2
083e322
 
 
 
9bf7fc2
 
083e322
 
9bf7fc2
 
 
083e322
 
 
 
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# server.py
import traceback
import uuid
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from app import chat
from config import SanatanConfig
from db import SanatanDatabase

router = APIRouter()

# In-memory mapping from session_id -> thread_id
# For production, you may want Redis or a DB for persistence
thread_map = {}

class Message(BaseModel):
    text: str
    session_id: str | None = None  # Optional session ID from client

@router.post("/greet")
async def handle_greet(msg: Message):
    markdown = "Namaskaram 🙏 I am **bhashyam.ai** and I can help you explore the following scriptures:\n---\n"
    for scripture in SanatanConfig().scriptures:
        num_units = SanatanDatabase().count(collection_name=scripture["collection_name"])
        markdown += f"- {scripture['title']} : `{num_units}` {scripture["unit"]}s\n"

    session_id = msg.session_id
    if not session_id:
        session_id = str(uuid.uuid4())
    return {"reply": markdown, "session_id": session_id}

@router.post("/chat")
async def handle_chat(msg: Message, request: Request):
    try:
        # Use existing session_id if provided, else generate new
        session_id = msg.session_id
        if not session_id:
            session_id = str(uuid.uuid4())

        # Get or create a persistent thread_id for this session
        if session_id not in thread_map:
            thread_map[session_id] = str(uuid.uuid4())
        thread_id = thread_map[session_id]

        # Call your graph/chat function
        reply_text = chat(
            debug_mode=False,
            message=msg.text,
            history=None,
            thread_id=thread_id
        )

        # Return both reply and session_id to the client
        return {"reply": reply_text, "session_id": session_id}

    except Exception as e:
        traceback.print_exc()
        return JSONResponse(
            status_code=500,
            content={"reply": f"Error: {e}"}
        )