Spaces:
Sleeping
Sleeping
Girish Jeswani commited on
Commit ·
b789ee4
1
Parent(s): e1b8548
add sequential and reply routes
Browse files
multi_llm_chatbot_backend/app/api/routes.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
from fastapi import APIRouter, Body, HTTPException
|
| 2 |
-
|
|
|
|
| 3 |
from app.models.persona import Persona
|
| 4 |
from app.core.orchestrator import ChatOrchestrator
|
| 5 |
from app.core.seamless_orchestrator import SeamlessOrchestrator
|
|
@@ -8,10 +9,70 @@ from typing import Optional, List
|
|
| 8 |
|
| 9 |
router = APIRouter()
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
chat_orchestrator = ChatOrchestrator()
|
| 14 |
-
seamless_orchestrator = SeamlessOrchestrator()
|
| 15 |
|
| 16 |
# Global context storage
|
| 17 |
class GlobalSessionContext:
|
|
@@ -22,31 +83,32 @@ class GlobalSessionContext:
|
|
| 22 |
self.full_log.append({"role": role, "content": content})
|
| 23 |
|
| 24 |
def filter_by_persona(self, persona_id: str):
|
| 25 |
-
|
|
|
|
| 26 |
|
| 27 |
def clear(self):
|
| 28 |
self.full_log = []
|
| 29 |
|
| 30 |
session_context = GlobalSessionContext()
|
| 31 |
|
| 32 |
-
#
|
| 33 |
DEFAULT_PERSONAS = [
|
| 34 |
Persona(
|
| 35 |
id="methodist",
|
| 36 |
name="Methodist Advisor",
|
| 37 |
-
system_prompt="You are
|
| 38 |
llm=llm
|
| 39 |
),
|
| 40 |
Persona(
|
| 41 |
id="theorist",
|
| 42 |
-
name="Theorist Advisor",
|
| 43 |
-
system_prompt="You are a philosophical PhD advisor
|
| 44 |
llm=llm
|
| 45 |
),
|
| 46 |
Persona(
|
| 47 |
id="pragmatist",
|
| 48 |
name="Pragmatist Advisor",
|
| 49 |
-
system_prompt="You are a practical PhD advisor
|
| 50 |
llm=llm
|
| 51 |
)
|
| 52 |
]
|
|
@@ -67,125 +129,199 @@ class ChatMessage(BaseModel):
|
|
| 67 |
user_input: str
|
| 68 |
session_id: Optional[str] = None
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
return {
|
| 77 |
-
"type": "
|
| 78 |
"responses": [{
|
| 79 |
-
"persona": "
|
| 80 |
-
"response":
|
| 81 |
-
}]
|
| 82 |
-
"collected_info": orchestrator_result["collected_info"]
|
| 83 |
}
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
return {
|
| 100 |
-
"type": "
|
| 101 |
-
"
|
| 102 |
-
"
|
|
|
|
|
|
|
| 103 |
}
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
| 108 |
"persona": "System",
|
| 109 |
-
"response": "I'm having trouble
|
| 110 |
-
}
|
| 111 |
-
}
|
| 112 |
-
|
| 113 |
-
# Reset both orchestrators
|
| 114 |
-
@router.post("/reset-session")
|
| 115 |
-
async def reset_session():
|
| 116 |
-
seamless_orchestrator.reset()
|
| 117 |
-
chat_orchestrator.history = []
|
| 118 |
-
session_context.clear()
|
| 119 |
-
return {"status": "reset", "message": "Session reset successfully"}
|
| 120 |
-
|
| 121 |
-
# Direct chat bypassing seamless orchestrator
|
| 122 |
-
@router.post("/chat-direct")
|
| 123 |
-
async def chat_direct(
|
| 124 |
-
user_input: str = Body(...),
|
| 125 |
-
active_personas: List[str] = Body(default=["methodist", "theorist", "pragmatist"])
|
| 126 |
-
):
|
| 127 |
-
chat_orchestrator.set_active_personas(active_personas)
|
| 128 |
-
session_context.append("user", user_input)
|
| 129 |
-
|
| 130 |
-
responses = []
|
| 131 |
-
for persona_id in active_personas:
|
| 132 |
-
persona = chat_orchestrator.personas[persona_id]
|
| 133 |
-
context = session_context.full_log
|
| 134 |
-
reply = await persona.respond(context)
|
| 135 |
-
session_context.append(persona_id, reply)
|
| 136 |
-
responses.append({"persona": persona.name, "response": reply})
|
| 137 |
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
-
# Individual
|
| 141 |
@router.post("/chat/{persona_id}")
|
| 142 |
-
async def
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
| 145 |
|
| 146 |
-
if not skip_user_append:
|
| 147 |
session_context.append("user", input.user_input)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
new_persona = Persona(
|
| 163 |
-
id=input.id,
|
| 164 |
-
name=input.name,
|
| 165 |
-
system_prompt=input.system_prompt,
|
| 166 |
-
llm=llm
|
| 167 |
-
)
|
| 168 |
-
chat_orchestrator.register_persona(new_persona)
|
| 169 |
-
return {"message": f"Persona '{input.name}' added successfully."}
|
| 170 |
-
|
| 171 |
-
@router.post("/personas/remove")
|
| 172 |
-
async def remove_persona(persona_id: str = Body(...)):
|
| 173 |
-
if persona_id not in chat_orchestrator.personas:
|
| 174 |
-
raise HTTPException(status_code=404, detail=f"Persona '{persona_id}' not found")
|
| 175 |
-
|
| 176 |
-
del chat_orchestrator.personas[persona_id]
|
| 177 |
-
return {"message": f"Persona '{persona_id}' removed successfully."}
|
| 178 |
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
# Context inspection
|
| 184 |
@router.get("/context")
|
| 185 |
def get_context():
|
| 186 |
return session_context.full_log
|
| 187 |
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import APIRouter, Body, HTTPException
|
| 2 |
+
import httpx
|
| 3 |
+
from app.llm.llm_client import LLMClient
|
| 4 |
from app.models.persona import Persona
|
| 5 |
from app.core.orchestrator import ChatOrchestrator
|
| 6 |
from app.core.seamless_orchestrator import SeamlessOrchestrator
|
|
|
|
| 9 |
|
| 10 |
router = APIRouter()
|
| 11 |
|
| 12 |
+
# Improved LLM client with better short response handling
|
| 13 |
+
class ShortResponseOllamaClient(LLMClient):
|
| 14 |
+
def __init__(self, model_name: str = "llama3.2:1b"):
|
| 15 |
+
self.model_name = model_name
|
| 16 |
+
|
| 17 |
+
async def generate(self, system_prompt: str, context: List[dict]) -> str:
|
| 18 |
+
# Create a more natural conversation format
|
| 19 |
+
messages = []
|
| 20 |
+
|
| 21 |
+
# Add system message
|
| 22 |
+
if system_prompt:
|
| 23 |
+
messages.append(f"System: {system_prompt}")
|
| 24 |
+
|
| 25 |
+
# Add conversation history
|
| 26 |
+
for msg in context:
|
| 27 |
+
role = msg['role'].capitalize()
|
| 28 |
+
if role == "User":
|
| 29 |
+
messages.append(f"Student: {msg['content']}")
|
| 30 |
+
elif role in ["Methodist", "Theorist", "Pragmatist"]:
|
| 31 |
+
messages.append(f"{role} Advisor: {msg['content']}")
|
| 32 |
+
else:
|
| 33 |
+
messages.append(f"{role}: {msg['content']}")
|
| 34 |
+
|
| 35 |
+
# Create the final prompt
|
| 36 |
+
conversation = "\n".join(messages)
|
| 37 |
+
prompt = f"{conversation}\n\nAssistant:"
|
| 38 |
+
|
| 39 |
+
payload = {
|
| 40 |
+
"model": self.model_name,
|
| 41 |
+
"prompt": prompt,
|
| 42 |
+
"stream": False,
|
| 43 |
+
"options": {
|
| 44 |
+
"temperature": 0.7,
|
| 45 |
+
"top_p": 0.9,
|
| 46 |
+
"top_k": 40,
|
| 47 |
+
"num_predict": 200, # Increased from 150
|
| 48 |
+
"repeat_penalty": 1.1,
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
async with httpx.AsyncClient(timeout=25.0) as client:
|
| 54 |
+
response = await client.post("http://localhost:11434/api/generate", json=payload)
|
| 55 |
+
response.raise_for_status()
|
| 56 |
+
result = response.json().get("response", "[No response]").strip()
|
| 57 |
+
|
| 58 |
+
# Clean up common issues
|
| 59 |
+
result = result.replace("Here are 2-3 sentence", "").strip()
|
| 60 |
+
result = result.replace("Here's an expansion of the advice:", "").strip()
|
| 61 |
+
result = result.replace("conceptual insights:", "").strip()
|
| 62 |
+
result = result.replace("actionable advice:", "").strip()
|
| 63 |
+
|
| 64 |
+
# If response is too short or just punctuation, return a fallback
|
| 65 |
+
if len(result) < 10 or result in [":", ".", ""]:
|
| 66 |
+
return "I'd be happy to help with that. Could you provide more specific details about what you're looking for?"
|
| 67 |
+
|
| 68 |
+
return result
|
| 69 |
+
|
| 70 |
+
except Exception as e:
|
| 71 |
+
return f"I apologize, but I'm having trouble generating a response right now. Please try again."
|
| 72 |
+
|
| 73 |
+
llm = ShortResponseOllamaClient(model_name="llama3.2:1b")
|
| 74 |
chat_orchestrator = ChatOrchestrator()
|
| 75 |
+
seamless_orchestrator = SeamlessOrchestrator(llm=llm)
|
| 76 |
|
| 77 |
# Global context storage
|
| 78 |
class GlobalSessionContext:
|
|
|
|
| 83 |
self.full_log.append({"role": role, "content": content})
|
| 84 |
|
| 85 |
def filter_by_persona(self, persona_id: str):
|
| 86 |
+
# Return full context but mark the persona for better understanding
|
| 87 |
+
return self.full_log
|
| 88 |
|
| 89 |
def clear(self):
|
| 90 |
self.full_log = []
|
| 91 |
|
| 92 |
session_context = GlobalSessionContext()
|
| 93 |
|
| 94 |
+
# Improved personas with natural, conversational prompts
|
| 95 |
DEFAULT_PERSONAS = [
|
| 96 |
Persona(
|
| 97 |
id="methodist",
|
| 98 |
name="Methodist Advisor",
|
| 99 |
+
system_prompt="You are Dr. Methodist, a structured PhD advisor. Give brief, organized advice in 2-3 clear sentences. Focus on systematic approaches and planning.",
|
| 100 |
llm=llm
|
| 101 |
),
|
| 102 |
Persona(
|
| 103 |
id="theorist",
|
| 104 |
+
name="Theorist Advisor",
|
| 105 |
+
system_prompt="You are Dr. Theorist, a philosophical PhD advisor. Give brief, thoughtful insights in 2-3 sentences. Focus on concepts, frameworks, and deeper understanding.",
|
| 106 |
llm=llm
|
| 107 |
),
|
| 108 |
Persona(
|
| 109 |
id="pragmatist",
|
| 110 |
name="Pragmatist Advisor",
|
| 111 |
+
system_prompt="You are Dr. Pragmatist, a practical PhD advisor. Give brief, actionable advice in 2-3 sentences. Focus on concrete steps and real-world solutions.",
|
| 112 |
llm=llm
|
| 113 |
)
|
| 114 |
]
|
|
|
|
| 129 |
user_input: str
|
| 130 |
session_id: Optional[str] = None
|
| 131 |
|
| 132 |
+
class ReplyToAdvisor(BaseModel):
|
| 133 |
+
user_input: str
|
| 134 |
+
advisor_id: str
|
| 135 |
+
original_message_id: Optional[str] = None
|
| 136 |
+
|
| 137 |
+
# Sequential advisor responses endpoint
|
| 138 |
+
@router.post("/chat-sequential")
|
| 139 |
+
async def chat_sequential(message: ChatMessage):
|
| 140 |
+
"""Generate advisor responses one by one for faster perceived response time"""
|
| 141 |
+
|
| 142 |
+
try:
|
| 143 |
+
orchestrator_result = await seamless_orchestrator.process_message(message.user_input)
|
| 144 |
+
|
| 145 |
+
if orchestrator_result["status"] == "orchestrator_asking":
|
| 146 |
+
return {
|
| 147 |
+
"type": "orchestrator_question",
|
| 148 |
+
"responses": [{
|
| 149 |
+
"persona": "PhD Advisor Assistant",
|
| 150 |
+
"response": orchestrator_result["orchestrator_question"]
|
| 151 |
+
}],
|
| 152 |
+
"collected_info": orchestrator_result["collected_info"]
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
elif orchestrator_result["status"] == "ready_for_advisors":
|
| 156 |
+
enhanced_context = orchestrator_result["enhanced_context"]
|
| 157 |
+
session_context.append("user", enhanced_context)
|
| 158 |
+
|
| 159 |
+
# Generate responses sequentially
|
| 160 |
+
advisor_order = ["methodist", "theorist", "pragmatist"]
|
| 161 |
+
responses = []
|
| 162 |
+
|
| 163 |
+
for i, persona_id in enumerate(advisor_order):
|
| 164 |
+
try:
|
| 165 |
+
persona = chat_orchestrator.personas[persona_id]
|
| 166 |
+
# Get current context up to this point
|
| 167 |
+
context = session_context.full_log.copy()
|
| 168 |
+
|
| 169 |
+
# Generate response
|
| 170 |
+
reply = await persona.respond(context)
|
| 171 |
+
|
| 172 |
+
# Add this advisor's response to context for next advisor
|
| 173 |
+
session_context.append(persona_id, reply)
|
| 174 |
+
|
| 175 |
+
responses.append({
|
| 176 |
+
"persona": persona.name,
|
| 177 |
+
"persona_id": persona_id,
|
| 178 |
+
"response": reply,
|
| 179 |
+
"order": i
|
| 180 |
+
})
|
| 181 |
+
|
| 182 |
+
except Exception as e:
|
| 183 |
+
print(f"Error generating response for {persona_id}: {e}")
|
| 184 |
+
responses.append({
|
| 185 |
+
"persona": chat_orchestrator.personas[persona_id].name,
|
| 186 |
+
"persona_id": persona_id,
|
| 187 |
+
"response": "I'm having trouble generating a response right now. Please try asking again.",
|
| 188 |
+
"order": i
|
| 189 |
+
})
|
| 190 |
+
|
| 191 |
+
return {
|
| 192 |
+
"type": "sequential_responses",
|
| 193 |
+
"responses": responses,
|
| 194 |
+
"collected_info": orchestrator_result["collected_info"]
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
except Exception as e:
|
| 198 |
+
print(f"Error in chat_sequential: {e}")
|
| 199 |
return {
|
| 200 |
+
"type": "error",
|
| 201 |
"responses": [{
|
| 202 |
+
"persona": "System",
|
| 203 |
+
"response": "I'm having trouble processing your request. Could you please try again?"
|
| 204 |
+
}]
|
|
|
|
| 205 |
}
|
| 206 |
|
| 207 |
+
# Reply to specific advisor endpoint
|
| 208 |
+
@router.post("/reply-to-advisor")
|
| 209 |
+
async def reply_to_advisor(reply: ReplyToAdvisor):
|
| 210 |
+
"""Reply to a specific advisor and get response only from that advisor"""
|
| 211 |
+
|
| 212 |
+
try:
|
| 213 |
+
if reply.advisor_id not in chat_orchestrator.personas:
|
| 214 |
+
raise HTTPException(status_code=404, detail=f"Advisor '{reply.advisor_id}' not found")
|
| 215 |
+
|
| 216 |
+
# Add user reply to context
|
| 217 |
+
session_context.append("user", reply.user_input)
|
| 218 |
+
|
| 219 |
+
# Get response from specific advisor
|
| 220 |
+
persona = chat_orchestrator.personas[reply.advisor_id]
|
| 221 |
+
context = session_context.full_log.copy()
|
| 222 |
+
|
| 223 |
+
# Generate response
|
| 224 |
+
reply_response = await persona.respond(context)
|
| 225 |
+
session_context.append(reply.advisor_id, reply_response)
|
| 226 |
+
|
| 227 |
return {
|
| 228 |
+
"type": "advisor_reply",
|
| 229 |
+
"persona": persona.name,
|
| 230 |
+
"persona_id": reply.advisor_id,
|
| 231 |
+
"response": reply_response,
|
| 232 |
+
"original_message_id": reply.original_message_id
|
| 233 |
}
|
| 234 |
+
|
| 235 |
+
except HTTPException:
|
| 236 |
+
raise
|
| 237 |
+
except Exception as e:
|
| 238 |
+
print(f"Error in reply_to_advisor: {e}")
|
| 239 |
+
return {
|
| 240 |
+
"type": "error",
|
| 241 |
"persona": "System",
|
| 242 |
+
"response": "I'm having trouble generating a reply right now. Please try again."
|
| 243 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
+
# Main chat endpoint (keep for compatibility)
|
| 246 |
+
@router.post("/chat")
|
| 247 |
+
async def chat_with_orchestrator(message: ChatMessage):
|
| 248 |
+
"""Redirect to sequential endpoint for better UX"""
|
| 249 |
+
return await chat_sequential(message)
|
| 250 |
|
| 251 |
+
# Individual advisor endpoint with context
|
| 252 |
@router.post("/chat/{persona_id}")
|
| 253 |
+
async def chat_with_specific_advisor(persona_id: str, input: UserInput):
|
| 254 |
+
"""Chat with a specific advisor"""
|
| 255 |
+
try:
|
| 256 |
+
if persona_id not in chat_orchestrator.personas:
|
| 257 |
+
raise HTTPException(status_code=404, detail=f"Persona '{persona_id}' not found")
|
| 258 |
|
|
|
|
| 259 |
session_context.append("user", input.user_input)
|
| 260 |
+
persona = chat_orchestrator.personas[persona_id]
|
| 261 |
+
context = session_context.full_log.copy()
|
| 262 |
+
reply = await persona.respond(context)
|
| 263 |
+
session_context.append(persona_id, reply)
|
| 264 |
|
| 265 |
+
return {
|
| 266 |
+
"persona": persona.name,
|
| 267 |
+
"persona_id": persona_id,
|
| 268 |
+
"response": reply
|
| 269 |
+
}
|
| 270 |
+
except HTTPException:
|
| 271 |
+
raise
|
| 272 |
+
except Exception as e:
|
| 273 |
+
print(f"Error in chat_with_specific_advisor: {e}")
|
| 274 |
+
return {
|
| 275 |
+
"persona": "System",
|
| 276 |
+
"response": "I'm having trouble generating a response right now. Please try again."
|
| 277 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
|
| 279 |
+
# Reset session
|
| 280 |
+
@router.post("/reset-session")
|
| 281 |
+
async def reset_session():
|
| 282 |
+
try:
|
| 283 |
+
seamless_orchestrator.reset()
|
| 284 |
+
session_context.clear()
|
| 285 |
+
return {"status": "reset", "message": "Session reset successfully"}
|
| 286 |
+
except Exception as e:
|
| 287 |
+
print(f"Error resetting session: {e}")
|
| 288 |
+
return {"status": "error", "message": "Failed to reset session"}
|
| 289 |
|
| 290 |
# Context inspection
|
| 291 |
@router.get("/context")
|
| 292 |
def get_context():
|
| 293 |
return session_context.full_log
|
| 294 |
|
| 295 |
+
# Model switching for development
|
| 296 |
+
@router.post("/switch-model")
|
| 297 |
+
async def switch_model(model_name: str = Body(...)):
|
| 298 |
+
global llm
|
| 299 |
+
try:
|
| 300 |
+
llm = ShortResponseOllamaClient(model_name=model_name)
|
| 301 |
+
|
| 302 |
+
# Update all personas with new LLM
|
| 303 |
+
for persona_id in chat_orchestrator.personas:
|
| 304 |
+
chat_orchestrator.personas[persona_id].llm = llm
|
| 305 |
+
|
| 306 |
+
seamless_orchestrator.llm = llm
|
| 307 |
+
|
| 308 |
+
return {"message": f"Switched to model: {model_name}"}
|
| 309 |
+
except Exception as e:
|
| 310 |
+
return {"error": f"Failed to switch model: {str(e)}"}
|
| 311 |
+
|
| 312 |
+
@router.get("/current-model")
|
| 313 |
+
async def get_current_model():
|
| 314 |
+
return {"model": llm.model_name}
|
| 315 |
+
|
| 316 |
+
# Debug endpoint
|
| 317 |
+
@router.get("/debug/personas")
|
| 318 |
+
async def debug_personas():
|
| 319 |
+
return {
|
| 320 |
+
"personas": {
|
| 321 |
+
pid: {
|
| 322 |
+
"name": persona.name,
|
| 323 |
+
"prompt": persona.system_prompt[:100] + "..."
|
| 324 |
+
} for pid, persona in chat_orchestrator.personas.items()
|
| 325 |
+
},
|
| 326 |
+
"context_length": len(session_context.full_log)
|
| 327 |
+
}
|
multi_llm_chatbot_backend/app/core/seamless_orchestrator.py
CHANGED
|
@@ -2,11 +2,11 @@
|
|
| 2 |
|
| 3 |
import re
|
| 4 |
from typing import Dict, List, Optional
|
| 5 |
-
from app.llm.
|
| 6 |
|
| 7 |
class SeamlessOrchestrator:
|
| 8 |
-
def __init__(self):
|
| 9 |
-
self.llm =
|
| 10 |
self.required_fields = ["research_area", "specific_question", "academic_stage"]
|
| 11 |
self.collected_info = {}
|
| 12 |
self.conversation_history = []
|
|
@@ -50,23 +50,17 @@ class SeamlessOrchestrator:
|
|
| 50 |
# Detect research area
|
| 51 |
research_areas = {
|
| 52 |
"computer science": ["computer science", "cs", "software", "programming", "algorithms"],
|
| 53 |
-
"machine learning": ["machine learning", "ml", "ai", "artificial intelligence", "
|
| 54 |
-
"biology": ["biology", "
|
| 55 |
-
"
|
| 56 |
-
"
|
| 57 |
-
"
|
| 58 |
-
"
|
| 59 |
-
"sociology": ["sociology", "social science", "anthropology"],
|
| 60 |
-
"literature": ["literature", "english", "linguistics"],
|
| 61 |
-
"history": ["history", "historical"],
|
| 62 |
-
"philosophy": ["philosophy", "philosophical"],
|
| 63 |
-
"economics": ["economics", "economic", "finance"],
|
| 64 |
-
"political science": ["political science", "politics", "government"],
|
| 65 |
"engineering": ["engineering", "mechanical", "electrical", "civil"],
|
| 66 |
-
"
|
| 67 |
-
"
|
| 68 |
-
"
|
| 69 |
-
"
|
| 70 |
}
|
| 71 |
|
| 72 |
for area, keywords in research_areas.items():
|
|
@@ -75,14 +69,15 @@ class SeamlessOrchestrator:
|
|
| 75 |
break
|
| 76 |
|
| 77 |
# Detect academic stage
|
| 78 |
-
|
| 79 |
-
"
|
| 80 |
-
"
|
| 81 |
-
"
|
| 82 |
-
"
|
|
|
|
| 83 |
}
|
| 84 |
|
| 85 |
-
for stage, keywords in
|
| 86 |
if any(keyword in user_lower for keyword in keywords):
|
| 87 |
info["academic_stage"] = stage
|
| 88 |
break
|
|
@@ -114,6 +109,9 @@ class SeamlessOrchestrator:
|
|
| 114 |
|
| 115 |
async def generate_orchestrator_question(self) -> str:
|
| 116 |
"""Generate a contextual follow-up question using the LLM"""
|
|
|
|
|
|
|
|
|
|
| 117 |
missing = [f for f in self.required_fields if f not in self.collected_info]
|
| 118 |
|
| 119 |
# Create context for the LLM
|
|
@@ -121,27 +119,31 @@ class SeamlessOrchestrator:
|
|
| 121 |
context += f"Information collected: {self.collected_info}\n"
|
| 122 |
context += f"Still need to know: {missing}\n"
|
| 123 |
|
| 124 |
-
system_prompt = """You are a PhD advisor's assistant
|
| 125 |
-
Based on the conversation and what information is still missing, ask ONE natural, conversational follow-up question.
|
| 126 |
|
| 127 |
-
Missing
|
| 128 |
-
- research_area: What field/discipline they
|
| 129 |
- specific_question: What specific aspect they need help with
|
| 130 |
- academic_stage: What stage of PhD they're in
|
| 131 |
|
| 132 |
-
Ask
|
| 133 |
|
| 134 |
try:
|
| 135 |
question = await self.llm.generate(system_prompt, [{"role": "user", "content": context}])
|
| 136 |
return question.strip()
|
| 137 |
except Exception as e:
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
async def process_message(self, user_input: str) -> Dict:
|
| 147 |
"""Process user message and determine next action"""
|
|
|
|
| 2 |
|
| 3 |
import re
|
| 4 |
from typing import Dict, List, Optional
|
| 5 |
+
from app.llm.llm_client import LLMClient
|
| 6 |
|
| 7 |
class SeamlessOrchestrator:
|
| 8 |
+
def __init__(self, llm: LLMClient = None):
|
| 9 |
+
self.llm = llm
|
| 10 |
self.required_fields = ["research_area", "specific_question", "academic_stage"]
|
| 11 |
self.collected_info = {}
|
| 12 |
self.conversation_history = []
|
|
|
|
| 50 |
# Detect research area
|
| 51 |
research_areas = {
|
| 52 |
"computer science": ["computer science", "cs", "software", "programming", "algorithms"],
|
| 53 |
+
"machine learning": ["machine learning", "ml", "ai", "artificial intelligence", "neural networks"],
|
| 54 |
+
"biology": ["biology", "bio", "genetics", "molecular", "cell"],
|
| 55 |
+
"physics": ["physics", "quantum", "mechanics", "particle"],
|
| 56 |
+
"psychology": ["psychology", "psych", "cognitive", "behavioral"],
|
| 57 |
+
"chemistry": ["chemistry", "chemical", "organic", "inorganic"],
|
| 58 |
+
"mathematics": ["mathematics", "math", "statistics", "calculus"],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
"engineering": ["engineering", "mechanical", "electrical", "civil"],
|
| 60 |
+
"economics": ["economics", "finance", "business", "market"],
|
| 61 |
+
"literature": ["literature", "english", "writing", "poetry"],
|
| 62 |
+
"history": ["history", "historical", "ancient", "medieval"],
|
| 63 |
+
"sociology": ["sociology", "social", "society", "culture"]
|
| 64 |
}
|
| 65 |
|
| 66 |
for area, keywords in research_areas.items():
|
|
|
|
| 69 |
break
|
| 70 |
|
| 71 |
# Detect academic stage
|
| 72 |
+
stage_patterns = {
|
| 73 |
+
"first year": ["first year", "1st year", "beginning", "just started", "new"],
|
| 74 |
+
"second year": ["second year", "2nd year", "coursework", "classes"],
|
| 75 |
+
"third year": ["third year", "3rd year", "qualifying", "comprehensive"],
|
| 76 |
+
"dissertation": ["dissertation", "thesis", "writing", "final year", "defense"],
|
| 77 |
+
"postdoc": ["postdoc", "post-doctoral", "finished", "graduated"]
|
| 78 |
}
|
| 79 |
|
| 80 |
+
for stage, keywords in stage_patterns.items():
|
| 81 |
if any(keyword in user_lower for keyword in keywords):
|
| 82 |
info["academic_stage"] = stage
|
| 83 |
break
|
|
|
|
| 109 |
|
| 110 |
async def generate_orchestrator_question(self) -> str:
|
| 111 |
"""Generate a contextual follow-up question using the LLM"""
|
| 112 |
+
if not self.llm:
|
| 113 |
+
return self._get_fallback_question()
|
| 114 |
+
|
| 115 |
missing = [f for f in self.required_fields if f not in self.collected_info]
|
| 116 |
|
| 117 |
# Create context for the LLM
|
|
|
|
| 119 |
context += f"Information collected: {self.collected_info}\n"
|
| 120 |
context += f"Still need to know: {missing}\n"
|
| 121 |
|
| 122 |
+
system_prompt = """You are a PhD advisor's assistant. Ask ONE brief follow-up question (under 15 words) to gather missing info.
|
|
|
|
| 123 |
|
| 124 |
+
Missing info types:
|
| 125 |
+
- research_area: What field/discipline they study
|
| 126 |
- specific_question: What specific aspect they need help with
|
| 127 |
- academic_stage: What stage of PhD they're in
|
| 128 |
|
| 129 |
+
Ask briefly and naturally."""
|
| 130 |
|
| 131 |
try:
|
| 132 |
question = await self.llm.generate(system_prompt, [{"role": "user", "content": context}])
|
| 133 |
return question.strip()
|
| 134 |
except Exception as e:
|
| 135 |
+
print(f"Error generating orchestrator question: {e}")
|
| 136 |
+
return self._get_fallback_question()
|
| 137 |
+
|
| 138 |
+
def _get_fallback_question(self) -> str:
|
| 139 |
+
"""Fallback questions when LLM fails"""
|
| 140 |
+
missing = [f for f in self.required_fields if f not in self.collected_info]
|
| 141 |
+
fallback_questions = {
|
| 142 |
+
"research_area": "What field are you studying in?",
|
| 143 |
+
"specific_question": "What specific aspect would you like guidance on?",
|
| 144 |
+
"academic_stage": "What stage of your PhD are you currently in?"
|
| 145 |
+
}
|
| 146 |
+
return fallback_questions.get(missing[0] if missing else "research_area", "Could you tell me more about your situation?")
|
| 147 |
|
| 148 |
async def process_message(self, user_input: str) -> Dict:
|
| 149 |
"""Process user message and determine next action"""
|