sohank-17 commited on
Commit
fb9baed
·
2 Parent(s): 290802cd8a62c1

Merge pull request #18 from sohank-17/sohank-feature

Browse files
multi_llm_chatbot_backend/app/api/routes.py CHANGED
@@ -1,4 +1,4 @@
1
- from fastapi import APIRouter, Body
2
  from app.llm.mistral_client import MistralClient
3
  from app.models.persona import Persona
4
  from app.core.orchestrator import ChatOrchestrator
@@ -8,72 +8,100 @@ from typing import Optional, List
8
 
9
  router = APIRouter()
10
 
11
- # Singletons
12
  llm = MistralClient()
13
  chat_orchestrator = ChatOrchestrator()
14
  seamless_orchestrator = SeamlessOrchestrator()
15
 
16
- # Register personas
17
- chat_orchestrator.register_persona(Persona(
18
- id="methodist",
19
- name="Methodist Advisor",
20
- system_prompt="You are a highly methodical PhD advisor who believes in structure and planning. Provide organized, step-by-step guidance.",
21
- llm=llm
22
- ))
23
-
24
- chat_orchestrator.register_persona(Persona(
25
- id="theorist",
26
- name="Theorist Advisor",
27
- system_prompt="You are a philosophical PhD advisor who focuses on abstract theories and ideas. Help students think deeply about concepts and frameworks.",
28
- llm=llm
29
- ))
30
-
31
- chat_orchestrator.register_persona(Persona(
32
- id="pragmatist",
33
- name="Pragmatist Advisor",
34
- system_prompt="You are a practical PhD advisor who focuses on real-world outcomes and utility. Give actionable, concrete advice.",
35
- llm=llm
36
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  class ChatMessage(BaseModel):
39
  user_input: str
40
  session_id: Optional[str] = None
41
 
 
42
  @router.post("/chat")
43
  async def chat_with_orchestrator(message: ChatMessage):
44
- """Main chat endpoint with seamless orchestrator integration"""
45
-
46
- # Process message through seamless orchestrator
47
  orchestrator_result = await seamless_orchestrator.process_message(message.user_input)
48
-
49
  if orchestrator_result["status"] == "orchestrator_asking":
50
- # Orchestrator needs more info - return orchestrator question
51
  return {
52
  "type": "orchestrator_question",
53
  "responses": [{
54
- "persona": "PhD Advisor Assistant",
55
  "response": orchestrator_result["orchestrator_question"]
56
  }],
57
  "collected_info": orchestrator_result["collected_info"]
58
  }
59
-
60
  elif orchestrator_result["status"] == "ready_for_advisors":
61
- # Ready for advisor consultation
62
  enhanced_context = orchestrator_result["enhanced_context"]
63
-
64
- # Set active advisors
65
  chat_orchestrator.set_active_personas(["methodist", "theorist", "pragmatist"])
66
-
67
- # Get advisor responses
68
- advisor_responses = await chat_orchestrator.process_user_input(enhanced_context)
69
-
 
 
 
 
 
 
70
  return {
71
  "type": "advisor_responses",
72
  "responses": advisor_responses,
73
  "collected_info": orchestrator_result["collected_info"]
74
  }
75
-
76
- # Fallback - shouldn't reach here normally
77
  return {
78
  "type": "error",
79
  "responses": [{
@@ -82,21 +110,82 @@ async def chat_with_orchestrator(message: ChatMessage):
82
  }]
83
  }
84
 
 
85
  @router.post("/reset-session")
86
  async def reset_session():
87
- """Reset the orchestrator session"""
88
  seamless_orchestrator.reset()
89
- # Also reset chat orchestrator history if needed
90
  chat_orchestrator.history = []
 
91
  return {"status": "reset", "message": "Session reset successfully"}
92
 
93
- # Keep the old endpoints for backward compatibility
94
- @router.post("/chat-direct")
95
  async def chat_direct(
96
  user_input: str = Body(...),
97
  active_personas: List[str] = Body(default=["methodist", "theorist", "pragmatist"])
98
  ):
99
- """Direct chat endpoint bypassing orchestrator (for testing)"""
100
  chat_orchestrator.set_active_personas(active_personas)
101
- responses = await chat_orchestrator.process_user_input(user_input)
102
- return responses
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Body, HTTPException
2
  from app.llm.mistral_client import MistralClient
3
  from app.models.persona import Persona
4
  from app.core.orchestrator import ChatOrchestrator
 
8
 
9
  router = APIRouter()
10
 
11
+ # Initialize LLM and orchestrators
12
  llm = MistralClient()
13
  chat_orchestrator = ChatOrchestrator()
14
  seamless_orchestrator = SeamlessOrchestrator()
15
 
16
+ # Global context storage
17
+ class GlobalSessionContext:
18
+ def __init__(self):
19
+ self.full_log: list[dict] = []
20
+
21
+ def append(self, role: str, content: str):
22
+ self.full_log.append({"role": role, "content": content})
23
+
24
+ def filter_by_persona(self, persona_id: str):
25
+ return [msg for msg in self.full_log if msg["role"] in ("user", persona_id)]
26
+
27
+ def clear(self):
28
+ self.full_log = []
29
+
30
+ session_context = GlobalSessionContext()
31
+
32
+ # Default personas
33
+ DEFAULT_PERSONAS = [
34
+ Persona(
35
+ id="methodist",
36
+ name="Methodist Advisor",
37
+ system_prompt="You are a highly methodical PhD advisor who believes in structure and planning. Provide organized, step-by-step guidance.",
38
+ llm=llm
39
+ ),
40
+ Persona(
41
+ id="theorist",
42
+ name="Theorist Advisor",
43
+ system_prompt="You are a philosophical PhD advisor who focuses on abstract theories and ideas. Help students think deeply about concepts and frameworks.",
44
+ llm=llm
45
+ ),
46
+ Persona(
47
+ id="pragmatist",
48
+ name="Pragmatist Advisor",
49
+ system_prompt="You are a practical PhD advisor who focuses on real-world outcomes and utility. Give actionable, concrete advice.",
50
+ llm=llm
51
+ )
52
+ ]
53
+
54
+ for persona in DEFAULT_PERSONAS:
55
+ chat_orchestrator.register_persona(persona)
56
+
57
+ # Data models
58
+ class UserInput(BaseModel):
59
+ user_input: str
60
+
61
+ class PersonaInput(BaseModel):
62
+ id: str
63
+ name: str
64
+ system_prompt: str
65
 
66
  class ChatMessage(BaseModel):
67
  user_input: str
68
  session_id: Optional[str] = None
69
 
70
+ # Main chat endpoint with seamless orchestrator
71
  @router.post("/chat")
72
  async def chat_with_orchestrator(message: ChatMessage):
 
 
 
73
  orchestrator_result = await seamless_orchestrator.process_message(message.user_input)
74
+
75
  if orchestrator_result["status"] == "orchestrator_asking":
 
76
  return {
77
  "type": "orchestrator_question",
78
  "responses": [{
79
+ "persona": "PhD Advisor Assistant",
80
  "response": orchestrator_result["orchestrator_question"]
81
  }],
82
  "collected_info": orchestrator_result["collected_info"]
83
  }
84
+
85
  elif orchestrator_result["status"] == "ready_for_advisors":
 
86
  enhanced_context = orchestrator_result["enhanced_context"]
87
+
 
88
  chat_orchestrator.set_active_personas(["methodist", "theorist", "pragmatist"])
89
+ session_context.append("user", enhanced_context)
90
+
91
+ advisor_responses = []
92
+ for persona_id in chat_orchestrator.get_active_personas():
93
+ persona = chat_orchestrator.personas[persona_id]
94
+ context = session_context.full_log
95
+ reply = await persona.respond(context)
96
+ session_context.append(persona_id, reply)
97
+ advisor_responses.append({"persona": persona.name, "response": reply})
98
+
99
  return {
100
  "type": "advisor_responses",
101
  "responses": advisor_responses,
102
  "collected_info": orchestrator_result["collected_info"]
103
  }
104
+
 
105
  return {
106
  "type": "error",
107
  "responses": [{
 
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
+ return responses
139
+
140
+ # Individual persona endpoint
141
+ @router.post("/chat/{persona_id}")
142
+ async def chat_with_persona(persona_id: str, input: UserInput, skip_user_append: bool = False):
143
+ if persona_id not in chat_orchestrator.personas:
144
+ raise HTTPException(status_code=404, detail=f"Persona '{persona_id}' not found")
145
+
146
+ if not skip_user_append:
147
+ session_context.append("user", input.user_input)
148
+
149
+ persona = chat_orchestrator.personas[persona_id]
150
+ context = session_context.filter_by_persona(persona_id)
151
+ reply = await persona.respond(context)
152
+ session_context.append(persona_id, reply)
153
+
154
+ return {"persona": persona.name, "response": reply}
155
+
156
+ # Persona management
157
+ @router.post("/personas/add")
158
+ async def add_persona(input: PersonaInput):
159
+ if input.id in chat_orchestrator.personas:
160
+ raise HTTPException(status_code=400, detail=f"Persona '{input.id}' already exists")
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
+ @router.get("/personas")
180
+ async def list_personas():
181
+ return list(chat_orchestrator.personas.keys())
182
+
183
+ # Context inspection
184
+ @router.get("/context")
185
+ def get_context():
186
+ return session_context.full_log
187
+
188
+ @router.post("/reset")
189
+ async def reset_context():
190
+ session_context.clear()
191
+ return {"message": "Context reset successfully"}
multi_llm_chatbot_backend/app/core/orchestrator.py CHANGED
@@ -1,24 +1,27 @@
1
  from app.models.persona import Persona
 
2
 
3
  class ChatOrchestrator:
4
  def __init__(self):
5
- self.history: list[dict] = []
6
  self.personas: dict[str, Persona] = {}
 
7
 
8
  def register_persona(self, persona: Persona):
9
  self.personas[persona.id] = persona
10
 
11
- def set_active_personas(self, ids: list[str]):
12
- self.active_ids = [pid for pid in ids if pid in self.personas]
13
 
14
- async def process_user_input(self, user_input: str):
15
- self.history.append({"role": "user", "content": user_input})
 
 
16
  responses = []
17
 
18
- for pid in self.active_ids:
19
  persona = self.personas[pid]
20
- reply = await persona.respond(self.history)
21
- self.history.append({"role": persona.id, "content": reply})
22
  responses.append({"persona": persona.name, "response": reply})
 
23
 
24
  return responses
 
1
  from app.models.persona import Persona
2
+ from typing import List
3
 
4
  class ChatOrchestrator:
5
  def __init__(self):
 
6
  self.personas: dict[str, Persona] = {}
7
+ self.active_personas: List[str] = [] # renamed for clarity
8
 
9
  def register_persona(self, persona: Persona):
10
  self.personas[persona.id] = persona
11
 
12
+ def set_active_personas(self, ids: List[str]):
13
+ self.active_personas = [pid for pid in ids if pid in self.personas]
14
 
15
+ def get_active_personas(self) -> List[str]:
16
+ return self.active_personas
17
+
18
+ async def process_user_input(self, user_input: str, context: List[dict]):
19
  responses = []
20
 
21
+ for pid in self.active_personas:
22
  persona = self.personas[pid]
23
+ reply = await persona.respond(context)
 
24
  responses.append({"persona": persona.name, "response": reply})
25
+ context.append({"role": persona.id, "content": reply})
26
 
27
  return responses
multi_llm_chatbot_backend/app/tests/test_context_propagation.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import time
3
+
4
+ BASE_URL = "http://localhost:8000"
5
+
6
+ def test_unified_chat():
7
+ print("\nSending unified chat request to /chat...\n")
8
+ payload = {
9
+ "user_input": "I'm a second year PhD student in Machine Learning. Any advice for my research paper presentation?"
10
+ }
11
+
12
+ try:
13
+ response = requests.post(f"{BASE_URL}/chat", json=payload)
14
+ response.raise_for_status()
15
+ except requests.exceptions.RequestException as e:
16
+ print("Error:", e)
17
+ return
18
+
19
+ data = response.json()
20
+ print(f"Type: {data.get('type')}")
21
+ print(f"Collected Info: {data.get('collected_info')}")
22
+
23
+ for reply in data.get("responses", []):
24
+ print(f"\n{reply['persona']}:\n{reply['response'][:500]}...\n") # show only first 500 chars
25
+
26
+ def test_context_log():
27
+ print("\nFetching /context...\n")
28
+ try:
29
+ response = requests.get(f"{BASE_URL}/context")
30
+ response.raise_for_status()
31
+ except requests.exceptions.RequestException as e:
32
+ print("Error fetching context:", e)
33
+ return
34
+
35
+ context = response.json()
36
+ for entry in context[-6:]: # Show the last 6 interactions for relevance
37
+ print(f"{entry['role']}: {entry['content'][:120]}...") # preview each entry
38
+
39
+ if __name__ == "__main__":
40
+ test_unified_chat()
41
+ time.sleep(2)
42
+ test_context_log()