86 lines
2.9 KiB
Python
86 lines
2.9 KiB
Python
from fastapi import APIRouter, HTTPException
|
|
from typing import Dict, Any
|
|
from uuid import uuid4
|
|
from botbuilder.core import TurnContext
|
|
from botbuilder.schema import Activity, ActivityTypes
|
|
from backend.app.factories.bot_factory import BotFactory
|
|
|
|
router = APIRouter(prefix="/v3/directline")
|
|
|
|
# In-memory conversation store
|
|
conversations: Dict[str, Dict[str, Any]] = {}
|
|
# Each conversation will look like:
|
|
# { "activities": [ { id, type, text, from } ], "watermark": int }
|
|
|
|
@router.post("/conversations")
|
|
async def start_conversation():
|
|
conversation_id = str(uuid4())
|
|
conversations[conversation_id] = {
|
|
"activities": [],
|
|
"watermark": 0
|
|
}
|
|
|
|
return {
|
|
"conversationId": conversation_id,
|
|
"token": "mock-token", # Optional for dev use
|
|
"streamUrl": f"/v3/directline/conversations/{conversation_id}/stream"
|
|
}
|
|
|
|
@router.get("/conversations/{conversation_id}/activities")
|
|
async def get_activities(conversation_id: str, watermark: int = 0):
|
|
if conversation_id not in conversations:
|
|
raise HTTPException(status_code=404, detail="Conversation not found")
|
|
|
|
activities = conversations[conversation_id]["activities"]
|
|
return {
|
|
"activities": activities[watermark:],
|
|
"watermark": len(activities)
|
|
}
|
|
|
|
@router.post("/conversations/{conversation_id}/activities")
|
|
async def post_activity(conversation_id: str, activity: Dict[str, Any]):
|
|
if conversation_id not in conversations:
|
|
raise HTTPException(status_code=404, detail="Conversation not found")
|
|
|
|
# Starting with deserializing the activity
|
|
act = Activity().deserialize(activity)
|
|
|
|
# Store my responses in this list please
|
|
bot_responses = []
|
|
|
|
#Patch TurnContext.send_activity to capture output
|
|
async def call_bot_logic(turn_context: TurnContext):
|
|
async def capture_response(response):
|
|
|
|
# If it's a string, wrap it into an Activity
|
|
if isinstance(response, str):
|
|
bot_activity = Activity(
|
|
type=ActivityTypes.message,
|
|
text=response,
|
|
from_property={"id": "bot"}
|
|
)
|
|
else:
|
|
bot_activity = response
|
|
|
|
bot_responses.append(bot_activity)
|
|
|
|
turn_context.send_activity = capture_response
|
|
await bot.on_turn(turn_context)
|
|
# 4. Call the adapter with the activity
|
|
adapter = BotFactory().get_adapter()
|
|
bot = BotFactory().get_bot("dayta")
|
|
auth_header = ""
|
|
|
|
await adapter.process_activity(act, auth_header, call_bot_logic)
|
|
|
|
# 5. Store bot responses into conversation memory
|
|
for act in bot_responses:
|
|
conversations[conversation_id]["activities"].append({
|
|
"id": str(uuid4()),
|
|
"type": act.type,
|
|
"text": act.text,
|
|
"from": {"id": "bot"},
|
|
"attachments": [a.serialize() for a in (act.attachments or [])]
|
|
})
|
|
|
|
return { "id": str(uuid4()) } |