Spaces:
Sleeping
Sleeping
NeonClary Cursor commited on
Commit ·
923dda1
1
Parent(s): 20fa64f
Wire FEAT auth, bootstrap, vLLM-with-Neon-pile, profile-sync, conversation summary, and avatar/UserUpdate model into upstream/dev base
Browse files- multi_llm_chatbot_backend/app/api/routes/auth.py +44 -13
- multi_llm_chatbot_backend/app/api/routes/provider.py +14 -7
- multi_llm_chatbot_backend/app/core/auth.py +1 -1
- multi_llm_chatbot_backend/app/core/bootstrap.py +132 -15
- multi_llm_chatbot_backend/app/core/session_manager.py +9 -0
- multi_llm_chatbot_backend/app/llm/improved_vllm_client.py +71 -14
- multi_llm_chatbot_backend/app/models/default_personas.py +21 -2
- multi_llm_chatbot_backend/app/models/user.py +11 -0
- multi_llm_chatbot_backend/app/tests/unit/test_tool_registry.py +3 -82
- multi_llm_chatbot_backend/app/utils/chat_summary.py +53 -4
multi_llm_chatbot_backend/app/api/routes/auth.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
from fastapi import APIRouter, HTTPException, Depends, status
|
| 2 |
from datetime import datetime, timedelta
|
| 3 |
-
from app.models.user import UserCreate, UserLogin, User, Token, UserResponse
|
| 4 |
from pydantic import BaseModel, model_validator
|
| 5 |
from typing import Optional
|
| 6 |
from app.core.auth import (
|
|
@@ -89,6 +89,20 @@ async def signup(user_data: UserCreate):
|
|
| 89 |
# Insert user into database
|
| 90 |
result = await db.users.insert_one(user.dict(by_alias=True))
|
| 91 |
user.id = result.inserted_id
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
# Create access token
|
| 94 |
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
@@ -225,23 +239,40 @@ async def change_password(
|
|
| 225 |
|
| 226 |
@router.patch("/me", response_model=UserResponse)
|
| 227 |
async def update_profile(
|
| 228 |
-
body:
|
| 229 |
current_user: User = Depends(get_current_active_user),
|
| 230 |
):
|
| 231 |
-
"""
|
| 232 |
-
Update the authenticated user's profile fields.
|
| 233 |
-
@param body: UpdateProfileRequest with optional firstName and lastName
|
| 234 |
-
@param current_user: Authenticated user from dependency injection
|
| 235 |
-
@return: UserResponse with the updated profile information
|
| 236 |
-
"""
|
| 237 |
try:
|
| 238 |
-
updates = {}
|
| 239 |
-
if body.first_name is not None:
|
| 240 |
-
updates["firstName"] = body.first_name
|
| 241 |
-
if body.last_name is not None:
|
| 242 |
-
updates["lastName"] = body.last_name
|
| 243 |
db = get_database()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
await db.users.update_one({"_id": current_user.id}, {"$set": updates})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
updated_user = await db.users.find_one({"_id": current_user.id})
|
| 246 |
return create_user_response(User(**updated_user))
|
| 247 |
|
|
|
|
| 1 |
from fastapi import APIRouter, HTTPException, Depends, status
|
| 2 |
from datetime import datetime, timedelta
|
| 3 |
+
from app.models.user import UserCreate, UserLogin, User, Token, UserResponse, UserUpdate
|
| 4 |
from pydantic import BaseModel, model_validator
|
| 5 |
from typing import Optional
|
| 6 |
from app.core.auth import (
|
|
|
|
| 89 |
# Insert user into database
|
| 90 |
result = await db.users.insert_one(user.dict(by_alias=True))
|
| 91 |
user.id = result.inserted_id
|
| 92 |
+
|
| 93 |
+
profile_seed: dict = {
|
| 94 |
+
"user_id": user.id,
|
| 95 |
+
"updated_at": datetime.utcnow(),
|
| 96 |
+
}
|
| 97 |
+
if user_data.academicStage:
|
| 98 |
+
profile_seed["knowledge_level"] = user_data.academicStage
|
| 99 |
+
if user_data.researchArea:
|
| 100 |
+
profile_seed["timezone"] = user_data.researchArea
|
| 101 |
+
await db.user_profiles.update_one(
|
| 102 |
+
{"user_id": user.id},
|
| 103 |
+
{"$set": profile_seed},
|
| 104 |
+
upsert=True,
|
| 105 |
+
)
|
| 106 |
|
| 107 |
# Create access token
|
| 108 |
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
|
|
| 239 |
|
| 240 |
@router.patch("/me", response_model=UserResponse)
|
| 241 |
async def update_profile(
|
| 242 |
+
body: UserUpdate,
|
| 243 |
current_user: User = Depends(get_current_active_user),
|
| 244 |
):
|
| 245 |
+
"""Update account fields (name, email, avatar, signup preferences)."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
db = get_database()
|
| 248 |
+
updates = {k: v for k, v in body.dict().items() if v is not None}
|
| 249 |
+
if body.firstName is not None:
|
| 250 |
+
updates["firstName"] = body.firstName.strip()
|
| 251 |
+
if body.lastName is not None:
|
| 252 |
+
updates["lastName"] = body.lastName.strip()
|
| 253 |
+
if not updates:
|
| 254 |
+
return create_user_response(current_user)
|
| 255 |
+
|
| 256 |
+
if "email" in updates and updates["email"] != current_user.email:
|
| 257 |
+
existing = await get_user_by_email(updates["email"])
|
| 258 |
+
if existing:
|
| 259 |
+
raise HTTPException(
|
| 260 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 261 |
+
detail="Email already in use",
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
await db.users.update_one({"_id": current_user.id}, {"$set": updates})
|
| 265 |
+
profile_sync: dict = {"updated_at": datetime.utcnow()}
|
| 266 |
+
if body.academicStage is not None:
|
| 267 |
+
profile_sync["knowledge_level"] = body.academicStage
|
| 268 |
+
if body.researchArea is not None:
|
| 269 |
+
profile_sync["timezone"] = body.researchArea
|
| 270 |
+
if len(profile_sync) > 1:
|
| 271 |
+
await db.user_profiles.update_one(
|
| 272 |
+
{"user_id": current_user.id},
|
| 273 |
+
{"$set": profile_sync, "$setOnInsert": {"user_id": current_user.id}},
|
| 274 |
+
upsert=True,
|
| 275 |
+
)
|
| 276 |
updated_user = await db.users.find_one({"_id": current_user.id})
|
| 277 |
return create_user_response(User(**updated_user))
|
| 278 |
|
multi_llm_chatbot_backend/app/api/routes/provider.py
CHANGED
|
@@ -37,11 +37,12 @@ def create_llm_client(provider: str = None):
|
|
| 37 |
else:
|
| 38 |
raise ValueError(f"Unknown provider: {provider}")
|
| 39 |
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
| 45 |
|
| 46 |
class ProviderSwitch(BaseModel):
|
| 47 |
provider: str
|
|
@@ -65,13 +66,19 @@ async def switch_provider(provider_data: ProviderSwitch):
|
|
| 65 |
raise HTTPException(status_code=400, detail=f"Unknown provider: {provider_data.provider}. Available: {available_providers}")
|
| 66 |
|
| 67 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
current_provider = provider_data.provider
|
| 69 |
-
new_llm =
|
| 70 |
llm = new_llm
|
| 71 |
|
| 72 |
chat_orchestrator.llm_client = new_llm
|
| 73 |
|
| 74 |
-
|
|
|
|
| 75 |
chat_orchestrator.personas.clear()
|
| 76 |
for persona in new_personas:
|
| 77 |
chat_orchestrator.register_persona(persona)
|
|
|
|
| 37 |
else:
|
| 38 |
raise ValueError(f"Unknown provider: {provider}")
|
| 39 |
|
| 40 |
+
# NOTE: Personas and `llm` are already created and registered by
|
| 41 |
+
# app/core/bootstrap.py with the correct ResilientLLMClient wrapping
|
| 42 |
+
# (primary vLLM + OpenAI fallback). Re-registering them here at module
|
| 43 |
+
# import time replaces them with a raw vLLM client that lacks the
|
| 44 |
+
# fallback wrapper AND lacks the api_username/api_key wiring, breaking
|
| 45 |
+
# both auth and failover. Bootstrap already handles initial setup.
|
| 46 |
|
| 47 |
class ProviderSwitch(BaseModel):
|
| 48 |
provider: str
|
|
|
|
| 66 |
raise HTTPException(status_code=400, detail=f"Unknown provider: {provider_data.provider}. Available: {available_providers}")
|
| 67 |
|
| 68 |
try:
|
| 69 |
+
from app.core.bootstrap import (
|
| 70 |
+
create_orchestrator_llm,
|
| 71 |
+
create_persona_llm,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
current_provider = provider_data.provider
|
| 75 |
+
new_llm = create_orchestrator_llm()
|
| 76 |
llm = new_llm
|
| 77 |
|
| 78 |
chat_orchestrator.llm_client = new_llm
|
| 79 |
|
| 80 |
+
persona_llm = create_persona_llm()
|
| 81 |
+
new_personas = get_default_personas(persona_llm)
|
| 82 |
chat_orchestrator.personas.clear()
|
| 83 |
for persona in new_personas:
|
| 84 |
chat_orchestrator.register_persona(persona)
|
multi_llm_chatbot_backend/app/core/auth.py
CHANGED
|
@@ -95,7 +95,6 @@ async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(s
|
|
| 95 |
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 96 |
detail="Inactive user"
|
| 97 |
)
|
| 98 |
-
|
| 99 |
return user
|
| 100 |
|
| 101 |
async def get_current_active_user(current_user: User = Depends(get_current_user)) -> User:
|
|
@@ -113,6 +112,7 @@ def create_user_response(user: User) -> UserResponse:
|
|
| 113 |
email=user.email,
|
| 114 |
academicStage=user.academicStage,
|
| 115 |
researchArea=user.researchArea,
|
|
|
|
| 116 |
created_at=user.created_at,
|
| 117 |
last_login=user.last_login
|
| 118 |
)
|
|
|
|
| 95 |
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 96 |
detail="Inactive user"
|
| 97 |
)
|
|
|
|
| 98 |
return user
|
| 99 |
|
| 100 |
async def get_current_active_user(current_user: User = Depends(get_current_user)) -> User:
|
|
|
|
| 112 |
email=user.email,
|
| 113 |
academicStage=user.academicStage,
|
| 114 |
researchArea=user.researchArea,
|
| 115 |
+
avatarId=user.avatarId,
|
| 116 |
created_at=user.created_at,
|
| 117 |
last_login=user.last_login
|
| 118 |
)
|
multi_llm_chatbot_backend/app/core/bootstrap.py
CHANGED
|
@@ -1,37 +1,154 @@
|
|
| 1 |
# app/core/bootstrap.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from app.config import get_settings
|
| 3 |
from app.llm.improved_gemini_client import ImprovedGeminiClient
|
| 4 |
from app.llm.improved_ollama_client import ImprovedOllamaClient
|
| 5 |
from app.llm.improved_vllm_client import ImprovedVllmClient
|
|
|
|
|
|
|
| 6 |
from app.core.improved_orchestrator import ImprovedChatOrchestrator
|
| 7 |
from app.models.default_personas import get_default_personas
|
| 8 |
|
| 9 |
settings = get_settings()
|
| 10 |
|
| 11 |
-
current_provider = "
|
| 12 |
available_providers = ["ollama", "gemini", "vllm"]
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def create_llm_client(provider=None):
|
| 15 |
if provider is None:
|
| 16 |
provider = current_provider
|
| 17 |
if provider == "gemini":
|
| 18 |
return ImprovedGeminiClient(model_name=settings.llm.gemini.model)
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
llm =
|
| 33 |
chat_orchestrator = ImprovedChatOrchestrator(llm_client=llm)
|
| 34 |
|
| 35 |
-
|
|
|
|
| 36 |
for persona in DEFAULT_PERSONAS:
|
| 37 |
chat_orchestrator.register_persona(persona)
|
|
|
|
| 1 |
# app/core/bootstrap.py
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from app.core.env_loader import load_application_env
|
| 6 |
+
|
| 7 |
+
load_application_env()
|
| 8 |
+
|
| 9 |
from app.config import get_settings
|
| 10 |
from app.llm.improved_gemini_client import ImprovedGeminiClient
|
| 11 |
from app.llm.improved_ollama_client import ImprovedOllamaClient
|
| 12 |
from app.llm.improved_vllm_client import ImprovedVllmClient
|
| 13 |
+
from app.llm.openai_fallback_client import OpenAIFallbackClient
|
| 14 |
+
from app.llm.resilient_client import ResilientLLMClient
|
| 15 |
from app.core.improved_orchestrator import ImprovedChatOrchestrator
|
| 16 |
from app.models.default_personas import get_default_personas
|
| 17 |
|
| 18 |
settings = get_settings()
|
| 19 |
|
| 20 |
+
current_provider = settings.llm.provider or "vllm"
|
| 21 |
available_providers = ["ollama", "gemini", "vllm"]
|
| 22 |
|
| 23 |
+
|
| 24 |
+
def _load_shared_env_var(name: str) -> str:
|
| 25 |
+
explicit = os.environ.get("SHARED_ENV", "").strip()
|
| 26 |
+
candidates = [Path(explicit)] if explicit else []
|
| 27 |
+
candidates.append(Path.home() / ".secrets" / "shared.env")
|
| 28 |
+
prefix = f"{name}="
|
| 29 |
+
for shared in candidates:
|
| 30 |
+
if not shared.is_file():
|
| 31 |
+
continue
|
| 32 |
+
for line in shared.read_text(encoding="utf-8").splitlines():
|
| 33 |
+
line = line.strip()
|
| 34 |
+
if line.startswith(prefix):
|
| 35 |
+
return line.split("=", 1)[1].strip()
|
| 36 |
+
return ""
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _vllm_api_username() -> str:
|
| 40 |
+
"""Optional HTTP Basic auth username for the vLLM endpoint.
|
| 41 |
+
|
| 42 |
+
The Neon BrainForge/Security endpoint at 4090-x1-3 requires HTTP Basic
|
| 43 |
+
auth using HANA_USERNAME_KLATCHAT / HANA_KLATCHAT_PASSWORD from
|
| 44 |
+
~/.secrets/shared.env. We allow explicit override via api_username
|
| 45 |
+
in config or VLLM_API_USERNAME env var, falling back to the shared
|
| 46 |
+
HANA_USERNAME_KLATCHAT entry.
|
| 47 |
+
"""
|
| 48 |
+
return (
|
| 49 |
+
settings.llm.vllm.api_username
|
| 50 |
+
or os.getenv("VLLM_API_USERNAME", "")
|
| 51 |
+
or _load_shared_env_var("HANA_USERNAME_KLATCHAT")
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _vllm_api_key() -> str:
|
| 56 |
+
"""vLLM key/password. If api_username is set (HANA Basic auth), prefer
|
| 57 |
+
HANA_KLATCHAT_PASSWORD; otherwise use the generic VLLM_API_KEY Bearer
|
| 58 |
+
token. This matches the dual-auth nature of the Neon endpoints.
|
| 59 |
+
"""
|
| 60 |
+
if _vllm_api_username():
|
| 61 |
+
return (
|
| 62 |
+
settings.llm.vllm.api_key
|
| 63 |
+
or os.getenv("HANA_KLATCHAT_PASSWORD", "")
|
| 64 |
+
or _load_shared_env_var("HANA_KLATCHAT_PASSWORD")
|
| 65 |
+
or os.getenv("VLLM_API_KEY", "")
|
| 66 |
+
or _load_shared_env_var("VLLM_API_KEY")
|
| 67 |
+
)
|
| 68 |
+
return (
|
| 69 |
+
settings.llm.vllm.api_key
|
| 70 |
+
or os.getenv("VLLM_API_KEY", "")
|
| 71 |
+
or _load_shared_env_var("VLLM_API_KEY")
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _openai_api_key() -> str:
|
| 76 |
+
return (
|
| 77 |
+
settings.llm.openai.api_key
|
| 78 |
+
or os.getenv("OPENAI_API_KEY", "")
|
| 79 |
+
or _load_shared_env_var("OPENAI_API_KEY")
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _build_neon_vllm(neon_persona: str | None) -> ImprovedVllmClient:
|
| 84 |
+
vllm = settings.llm.vllm
|
| 85 |
+
if not vllm.api_url:
|
| 86 |
+
raise ValueError("No vLLM endpoint configured. Set llm.vllm.api_url in your config.")
|
| 87 |
+
model_name = vllm.model_id or None
|
| 88 |
+
return ImprovedVllmClient(
|
| 89 |
+
api_url=vllm.api_url,
|
| 90 |
+
api_key=_vllm_api_key(),
|
| 91 |
+
model_name=model_name,
|
| 92 |
+
neon_persona=neon_persona,
|
| 93 |
+
api_username=_vllm_api_username() or None,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _build_openai(reasoning_effort: str) -> OpenAIFallbackClient:
|
| 98 |
+
return OpenAIFallbackClient(
|
| 99 |
+
api_key=_openai_api_key(),
|
| 100 |
+
model=settings.llm.openai.model,
|
| 101 |
+
reasoning_effort=reasoning_effort,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _wrap_resilient(primary: ImprovedVllmClient, fallback: OpenAIFallbackClient, label: str):
|
| 106 |
+
return ResilientLLMClient(
|
| 107 |
+
primary=primary,
|
| 108 |
+
fallback=fallback,
|
| 109 |
+
race_timeout_seconds=settings.llm.resilient.race_timeout_seconds,
|
| 110 |
+
primary_label=label,
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
def create_llm_client(provider=None):
|
| 115 |
if provider is None:
|
| 116 |
provider = current_provider
|
| 117 |
if provider == "gemini":
|
| 118 |
return ImprovedGeminiClient(model_name=settings.llm.gemini.model)
|
| 119 |
+
if provider == "vllm":
|
| 120 |
+
neon = settings.llm.vllm.neon_persona_orchestrator
|
| 121 |
+
primary = _build_neon_vllm(neon if neon != "vanilla" else None)
|
| 122 |
+
fallback = _build_openai(settings.llm.openai.orchestrator_reasoning_effort)
|
| 123 |
+
return _wrap_resilient(primary, fallback, "orchestrator")
|
| 124 |
+
return ImprovedOllamaClient(
|
| 125 |
+
model_name=settings.llm.ollama.model,
|
| 126 |
+
base_url=settings.llm.ollama.base_url,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def create_orchestrator_llm():
|
| 131 |
+
if current_provider != "vllm":
|
| 132 |
+
return create_llm_client()
|
| 133 |
+
neon = settings.llm.vllm.neon_persona_orchestrator
|
| 134 |
+
primary = _build_neon_vllm(neon if neon != "vanilla" else None)
|
| 135 |
+
fallback = _build_openai(settings.llm.openai.orchestrator_reasoning_effort)
|
| 136 |
+
return _wrap_resilient(primary, fallback, "orchestrator")
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def create_persona_llm():
|
| 140 |
+
if current_provider != "vllm":
|
| 141 |
+
return create_llm_client()
|
| 142 |
+
neon = settings.llm.vllm.neon_persona_advisors
|
| 143 |
+
primary = _build_neon_vllm(neon)
|
| 144 |
+
fallback = _build_openai(settings.llm.openai.persona_reasoning_effort)
|
| 145 |
+
return _wrap_resilient(primary, fallback, "persona")
|
| 146 |
+
|
| 147 |
|
| 148 |
+
llm = create_orchestrator_llm()
|
| 149 |
chat_orchestrator = ImprovedChatOrchestrator(llm_client=llm)
|
| 150 |
|
| 151 |
+
persona_llm = create_persona_llm() if current_provider == "vllm" else llm
|
| 152 |
+
DEFAULT_PERSONAS = get_default_personas(persona_llm)
|
| 153 |
for persona in DEFAULT_PERSONAS:
|
| 154 |
chat_orchestrator.register_persona(persona)
|
multi_llm_chatbot_backend/app/core/session_manager.py
CHANGED
|
@@ -22,6 +22,14 @@ class ConversationContext:
|
|
| 22 |
self.document_chunks_count: int = 0 # Track total chunks in vector DB
|
| 23 |
self.last_retrieval_stats: Dict[str, Any] = {} # Last RAG retrieval info
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
def append_message(self, role: str, content: str):
|
| 26 |
"""Add a message to the conversation history"""
|
| 27 |
self.messages.append({
|
|
@@ -34,6 +42,7 @@ class ConversationContext:
|
|
| 34 |
def clear_messages(self):
|
| 35 |
"""Clear conversation messages but keep document references"""
|
| 36 |
self.messages.clear()
|
|
|
|
| 37 |
self.last_accessed = datetime.now()
|
| 38 |
|
| 39 |
def get_messages_by_role(self, role: str) -> List[Dict[str, str]]:
|
|
|
|
| 22 |
self.document_chunks_count: int = 0 # Track total chunks in vector DB
|
| 23 |
self.last_retrieval_stats: Dict[str, Any] = {} # Last RAG retrieval info
|
| 24 |
|
| 25 |
+
# Cached LLM summary when conversation history exceeds token threshold
|
| 26 |
+
self.conversation_summary: Optional[str] = None
|
| 27 |
+
self.conversation_summary_message_count: int = 0
|
| 28 |
+
|
| 29 |
+
def clear_conversation_summary(self) -> None:
|
| 30 |
+
self.conversation_summary = None
|
| 31 |
+
self.conversation_summary_message_count = 0
|
| 32 |
+
|
| 33 |
def append_message(self, role: str, content: str):
|
| 34 |
"""Add a message to the conversation history"""
|
| 35 |
self.messages.append({
|
|
|
|
| 42 |
def clear_messages(self):
|
| 43 |
"""Clear conversation messages but keep document references"""
|
| 44 |
self.messages.clear()
|
| 45 |
+
self.clear_conversation_summary()
|
| 46 |
self.last_accessed = datetime.now()
|
| 47 |
|
| 48 |
def get_messages_by_role(self, role: str) -> List[Dict[str, str]]:
|
multi_llm_chatbot_backend/app/llm/improved_vllm_client.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
import json
|
| 2 |
import logging
|
| 3 |
from typing import Any, Callable, Dict, List, Optional
|
|
@@ -5,23 +6,77 @@ from typing import Any, Callable, Dict, List, Optional
|
|
| 5 |
from openai import AsyncOpenAI, APIConnectionError, APIStatusError
|
| 6 |
|
| 7 |
from app.llm.llm_client import LLMClient, ToolCallInfo, ToolCallResult
|
|
|
|
| 8 |
from app.core.context_manager import get_context_manager
|
| 9 |
|
| 10 |
logger = logging.getLogger(__name__)
|
| 11 |
|
| 12 |
|
| 13 |
class ImprovedVllmClient(LLMClient):
|
| 14 |
-
def __init__(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
self.api_url = api_url
|
| 16 |
self.api_key = api_key
|
|
|
|
| 17 |
self.model_name = model_name
|
| 18 |
-
self.
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
self.context_manager = get_context_manager()
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
async def refresh_model(self):
|
| 26 |
"""Query the vLLM endpoint to discover the currently loaded model."""
|
| 27 |
models = await self.client.models.list()
|
|
@@ -35,8 +90,8 @@ class ImprovedVllmClient(LLMClient):
|
|
| 35 |
try:
|
| 36 |
context_window = self.context_manager.prepare_context_for_llm(
|
| 37 |
messages=context,
|
| 38 |
-
system_prompt=
|
| 39 |
-
llm_provider="vllm"
|
| 40 |
)
|
| 41 |
|
| 42 |
logger.debug(f"Context prepared: {len(context_window.messages)} messages, "
|
|
@@ -45,9 +100,11 @@ class ImprovedVllmClient(LLMClient):
|
|
| 45 |
if not self.model_name:
|
| 46 |
await self.refresh_model()
|
| 47 |
|
|
|
|
|
|
|
| 48 |
create_kwargs = dict(
|
| 49 |
model=self.model_name,
|
| 50 |
-
messages=
|
| 51 |
temperature=temperature,
|
| 52 |
max_tokens=max_tokens,
|
| 53 |
)
|
|
@@ -60,7 +117,7 @@ class ImprovedVllmClient(LLMClient):
|
|
| 60 |
text = response.choices[0].message.content.strip()
|
| 61 |
return self._clean_response(text)
|
| 62 |
|
| 63 |
-
except APIConnectionError:
|
| 64 |
logger.error(f"Unable to connect to vLLM at {self.api_url}")
|
| 65 |
return "I'm unable to connect to the AI service. Please ensure the vLLM endpoint is available."
|
| 66 |
except APIStatusError as e:
|
|
@@ -104,10 +161,10 @@ class ImprovedVllmClient(LLMClient):
|
|
| 104 |
if not self.model_name:
|
| 105 |
await self.refresh_model()
|
| 106 |
|
| 107 |
-
messages: List[Dict[str, Any]] =
|
| 108 |
-
|
| 109 |
-
{"role": "user", "content": user_message},
|
| 110 |
-
|
| 111 |
|
| 112 |
openai_tools = tool_definitions or []
|
| 113 |
|
|
|
|
| 1 |
+
import base64
|
| 2 |
import json
|
| 3 |
import logging
|
| 4 |
from typing import Any, Callable, Dict, List, Optional
|
|
|
|
| 6 |
from openai import AsyncOpenAI, APIConnectionError, APIStatusError
|
| 7 |
|
| 8 |
from app.llm.llm_client import LLMClient, ToolCallInfo, ToolCallResult
|
| 9 |
+
from app.llm.neon_pile import get_pile_system_prompt
|
| 10 |
from app.core.context_manager import get_context_manager
|
| 11 |
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
|
| 15 |
class ImprovedVllmClient(LLMClient):
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
api_url: str,
|
| 19 |
+
api_key: str,
|
| 20 |
+
model_name: str = None,
|
| 21 |
+
neon_persona: str | None = None,
|
| 22 |
+
model_revision: str | None = None,
|
| 23 |
+
api_username: str | None = None,
|
| 24 |
+
):
|
| 25 |
self.api_url = api_url
|
| 26 |
self.api_key = api_key
|
| 27 |
+
self.api_username = api_username or None
|
| 28 |
self.model_name = model_name
|
| 29 |
+
self.neon_persona = neon_persona
|
| 30 |
+
self.model_revision = model_revision
|
| 31 |
+
|
| 32 |
+
client_kwargs: dict = {
|
| 33 |
+
"base_url": f"{api_url}/v1",
|
| 34 |
+
"api_key": api_key or "not-needed",
|
| 35 |
+
"timeout": 90.0,
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
if self.api_username:
|
| 39 |
+
# Some Neon endpoints (e.g. BrainForge/Security at 4090-x1-3)
|
| 40 |
+
# require HTTP Basic auth using HANA-style credentials rather
|
| 41 |
+
# than the regular Bearer token. The OpenAI SDK injects its own
|
| 42 |
+
# Authorization: Bearer <api_key> header on every request, so we
|
| 43 |
+
# override it via default_headers to ensure Basic auth wins.
|
| 44 |
+
basic = base64.b64encode(
|
| 45 |
+
f"{self.api_username}:{api_key or ''}".encode("utf-8")
|
| 46 |
+
).decode("ascii")
|
| 47 |
+
client_kwargs["default_headers"] = {"Authorization": f"Basic {basic}"}
|
| 48 |
+
|
| 49 |
+
self.client = AsyncOpenAI(**client_kwargs)
|
| 50 |
self.context_manager = get_context_manager()
|
| 51 |
|
| 52 |
+
def _resolve_model_revision(self) -> str | None:
|
| 53 |
+
if not self.model_name or "@" not in self.model_name:
|
| 54 |
+
return self.model_revision
|
| 55 |
+
_, _, suffix = self.model_name.partition("@")
|
| 56 |
+
return suffix or self.model_revision
|
| 57 |
+
|
| 58 |
+
def _resolve_base_model_name(self) -> str:
|
| 59 |
+
if not self.model_name:
|
| 60 |
+
return ""
|
| 61 |
+
return self.model_name.split("@", 1)[0]
|
| 62 |
+
|
| 63 |
+
def _build_messages(self, system_prompt: str, context_messages: List[dict]) -> List[dict]:
|
| 64 |
+
"""Prepend Neon pile persona system prompt when configured."""
|
| 65 |
+
messages: List[dict] = []
|
| 66 |
+
base_model = self._resolve_base_model_name()
|
| 67 |
+
if base_model and self.neon_persona:
|
| 68 |
+
pile_prompt = get_pile_system_prompt(
|
| 69 |
+
base_model,
|
| 70 |
+
self.neon_persona,
|
| 71 |
+
revision=self._resolve_model_revision(),
|
| 72 |
+
)
|
| 73 |
+
if pile_prompt:
|
| 74 |
+
messages.append({"role": "system", "content": pile_prompt})
|
| 75 |
+
if system_prompt:
|
| 76 |
+
messages.append({"role": "system", "content": system_prompt})
|
| 77 |
+
messages.extend(context_messages)
|
| 78 |
+
return messages
|
| 79 |
+
|
| 80 |
async def refresh_model(self):
|
| 81 |
"""Query the vLLM endpoint to discover the currently loaded model."""
|
| 82 |
models = await self.client.models.list()
|
|
|
|
| 90 |
try:
|
| 91 |
context_window = self.context_manager.prepare_context_for_llm(
|
| 92 |
messages=context,
|
| 93 |
+
system_prompt="",
|
| 94 |
+
llm_provider="vllm",
|
| 95 |
)
|
| 96 |
|
| 97 |
logger.debug(f"Context prepared: {len(context_window.messages)} messages, "
|
|
|
|
| 100 |
if not self.model_name:
|
| 101 |
await self.refresh_model()
|
| 102 |
|
| 103 |
+
api_messages = self._build_messages(system_prompt, context_window.messages)
|
| 104 |
+
|
| 105 |
create_kwargs = dict(
|
| 106 |
model=self.model_name,
|
| 107 |
+
messages=api_messages,
|
| 108 |
temperature=temperature,
|
| 109 |
max_tokens=max_tokens,
|
| 110 |
)
|
|
|
|
| 117 |
text = response.choices[0].message.content.strip()
|
| 118 |
return self._clean_response(text)
|
| 119 |
|
| 120 |
+
except APIConnectionError as e:
|
| 121 |
logger.error(f"Unable to connect to vLLM at {self.api_url}")
|
| 122 |
return "I'm unable to connect to the AI service. Please ensure the vLLM endpoint is available."
|
| 123 |
except APIStatusError as e:
|
|
|
|
| 161 |
if not self.model_name:
|
| 162 |
await self.refresh_model()
|
| 163 |
|
| 164 |
+
messages: List[Dict[str, Any]] = self._build_messages(
|
| 165 |
+
system_prompt,
|
| 166 |
+
[{"role": "user", "content": user_message}],
|
| 167 |
+
)
|
| 168 |
|
| 169 |
openai_tools = tool_definitions or []
|
| 170 |
|
multi_llm_chatbot_backend/app/models/default_personas.py
CHANGED
|
@@ -6,9 +6,10 @@ The heavy persona definitions have moved into ``config.yaml`` (under the
|
|
| 6 |
and exposes the same public API the rest of the codebase already relies on.
|
| 7 |
"""
|
| 8 |
|
| 9 |
-
from typing import List, Optional
|
| 10 |
|
| 11 |
from app.config import get_settings
|
|
|
|
| 12 |
from app.models.persona import Persona
|
| 13 |
|
| 14 |
|
|
@@ -46,7 +47,7 @@ def _get_registry() -> dict:
|
|
| 46 |
# Public API — unchanged signatures so existing callers keep working
|
| 47 |
# ------------------------------------------------------------------
|
| 48 |
|
| 49 |
-
def get_default_personas(llm) -> List[Persona]:
|
| 50 |
"""Return a list of :class:`Persona` objects wired to *llm*."""
|
| 51 |
return [
|
| 52 |
Persona(
|
|
@@ -60,6 +61,24 @@ def get_default_personas(llm) -> List[Persona]:
|
|
| 60 |
]
|
| 61 |
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
def get_default_persona_prompt(persona_id: str) -> Optional[str]:
|
| 64 |
data = _get_registry().get(persona_id)
|
| 65 |
return data["system_prompt"] if data else None
|
|
|
|
| 6 |
and exposes the same public API the rest of the codebase already relies on.
|
| 7 |
"""
|
| 8 |
|
| 9 |
+
from typing import Dict, List, Optional
|
| 10 |
|
| 11 |
from app.config import get_settings
|
| 12 |
+
from app.llm.llm_client import LLMClient
|
| 13 |
from app.models.persona import Persona
|
| 14 |
|
| 15 |
|
|
|
|
| 47 |
# Public API — unchanged signatures so existing callers keep working
|
| 48 |
# ------------------------------------------------------------------
|
| 49 |
|
| 50 |
+
def get_default_personas(llm: LLMClient) -> List[Persona]:
|
| 51 |
"""Return a list of :class:`Persona` objects wired to *llm*."""
|
| 52 |
return [
|
| 53 |
Persona(
|
|
|
|
| 61 |
]
|
| 62 |
|
| 63 |
|
| 64 |
+
def get_personas_with_llm_map(
|
| 65 |
+
default_llm: LLMClient,
|
| 66 |
+
llm_map: Optional[Dict[str, LLMClient]] = None,
|
| 67 |
+
) -> List[Persona]:
|
| 68 |
+
if not llm_map:
|
| 69 |
+
return get_default_personas(default_llm)
|
| 70 |
+
return [
|
| 71 |
+
Persona(
|
| 72 |
+
id=pid,
|
| 73 |
+
name=data["name"],
|
| 74 |
+
system_prompt=data["system_prompt"],
|
| 75 |
+
llm=llm_map.get(pid, default_llm),
|
| 76 |
+
temperature=data.get("default_temperature", 5),
|
| 77 |
+
)
|
| 78 |
+
for pid, data in _get_registry().items()
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
def get_default_persona_prompt(persona_id: str) -> Optional[str]:
|
| 83 |
data = _get_registry().get(persona_id)
|
| 84 |
return data["system_prompt"] if data else None
|
multi_llm_chatbot_backend/app/models/user.py
CHANGED
|
@@ -47,10 +47,20 @@ class User(BaseModel):
|
|
| 47 |
hashed_password: str
|
| 48 |
academicStage: Optional[str] = None
|
| 49 |
researchArea: Optional[str] = None
|
|
|
|
| 50 |
created_at: datetime = Field(default_factory=datetime.utcnow)
|
| 51 |
last_login: Optional[datetime] = None
|
| 52 |
is_active: bool = True
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
class UserResponse(BaseModel):
|
| 55 |
id: str
|
| 56 |
firstName: str
|
|
@@ -58,6 +68,7 @@ class UserResponse(BaseModel):
|
|
| 58 |
email: str
|
| 59 |
academicStage: Optional[str] = None
|
| 60 |
researchArea: Optional[str] = None
|
|
|
|
| 61 |
created_at: datetime
|
| 62 |
last_login: Optional[datetime] = None
|
| 63 |
|
|
|
|
| 47 |
hashed_password: str
|
| 48 |
academicStage: Optional[str] = None
|
| 49 |
researchArea: Optional[str] = None
|
| 50 |
+
avatarId: Optional[str] = None
|
| 51 |
created_at: datetime = Field(default_factory=datetime.utcnow)
|
| 52 |
last_login: Optional[datetime] = None
|
| 53 |
is_active: bool = True
|
| 54 |
|
| 55 |
+
class UserUpdate(BaseModel):
|
| 56 |
+
avatarId: Optional[str] = None
|
| 57 |
+
firstName: Optional[str] = None
|
| 58 |
+
lastName: Optional[str] = None
|
| 59 |
+
email: Optional[EmailStr] = None
|
| 60 |
+
academicStage: Optional[str] = None
|
| 61 |
+
researchArea: Optional[str] = None
|
| 62 |
+
|
| 63 |
+
|
| 64 |
class UserResponse(BaseModel):
|
| 65 |
id: str
|
| 66 |
firstName: str
|
|
|
|
| 68 |
email: str
|
| 69 |
academicStage: Optional[str] = None
|
| 70 |
researchArea: Optional[str] = None
|
| 71 |
+
avatarId: Optional[str] = None
|
| 72 |
created_at: datetime
|
| 73 |
last_login: Optional[datetime] = None
|
| 74 |
|
multi_llm_chatbot_backend/app/tests/unit/test_tool_registry.py
CHANGED
|
@@ -10,13 +10,10 @@ from app.tools import (
|
|
| 10 |
)
|
| 11 |
|
| 12 |
|
| 13 |
-
KNOWN_TOOLS = {"
|
| 14 |
|
| 15 |
|
| 16 |
class TestToolDiscovery(unittest.TestCase):
|
| 17 |
-
"""Auto-discovery should find every tool module that exports
|
| 18 |
-
TOOL_DEFINITION + execute."""
|
| 19 |
-
|
| 20 |
def test_known_tools_are_discovered(self):
|
| 21 |
registered = set(list_registered_tools())
|
| 22 |
for name in KNOWN_TOOLS:
|
|
@@ -27,97 +24,21 @@ class TestToolDiscovery(unittest.TestCase):
|
|
| 27 |
self.assertIn("definition", entry, f"'{name}' missing definition")
|
| 28 |
self.assertIn("executor", entry, f"'{name}' missing executor")
|
| 29 |
|
| 30 |
-
def test_definitions_have_required_fields(self):
|
| 31 |
-
for name, entry in _REGISTRY.items():
|
| 32 |
-
defn = entry["definition"]
|
| 33 |
-
self.assertEqual(defn["type"], "function")
|
| 34 |
-
self.assertIn("function", defn)
|
| 35 |
-
fn = defn["function"]
|
| 36 |
-
self.assertIn("name", fn)
|
| 37 |
-
self.assertIn("description", fn)
|
| 38 |
-
self.assertIn("parameters", fn)
|
| 39 |
-
self.assertEqual(fn["name"], name)
|
| 40 |
-
|
| 41 |
-
def test_executors_are_async_callables(self):
|
| 42 |
-
for name, entry in _REGISTRY.items():
|
| 43 |
-
self.assertTrue(
|
| 44 |
-
asyncio.iscoroutinefunction(entry["executor"]),
|
| 45 |
-
f"Executor for '{name}' is not an async function",
|
| 46 |
-
)
|
| 47 |
-
|
| 48 |
|
| 49 |
class TestGetToolDefinitions(unittest.TestCase):
|
| 50 |
-
"""get_tool_definitions() returns OpenAI-format tool dicts,
|
| 51 |
-
optionally filtered."""
|
| 52 |
-
|
| 53 |
def test_returns_all_when_no_filter(self):
|
| 54 |
defs = get_tool_definitions()
|
| 55 |
names = {d["function"]["name"] for d in defs}
|
| 56 |
self.assertTrue(KNOWN_TOOLS.issubset(names))
|
| 57 |
|
| 58 |
def test_filter_to_single_tool(self):
|
| 59 |
-
defs = get_tool_definitions(enabled=["
|
| 60 |
self.assertEqual(len(defs), 1)
|
| 61 |
-
self.assertEqual(defs[0]["function"]["name"], "
|
| 62 |
-
|
| 63 |
-
def test_filter_to_multiple_tools(self):
|
| 64 |
-
defs = get_tool_definitions(enabled=["search_courses", "rate_my_professor"])
|
| 65 |
-
names = {d["function"]["name"] for d in defs}
|
| 66 |
-
self.assertEqual(names, KNOWN_TOOLS)
|
| 67 |
-
|
| 68 |
-
def test_filter_with_unknown_name_returns_empty(self):
|
| 69 |
-
defs = get_tool_definitions(enabled=["nonexistent_tool"])
|
| 70 |
-
self.assertEqual(defs, [])
|
| 71 |
-
|
| 72 |
-
def test_filter_with_empty_list_returns_empty(self):
|
| 73 |
-
defs = get_tool_definitions(enabled=[])
|
| 74 |
-
self.assertEqual(defs, [])
|
| 75 |
-
|
| 76 |
-
def test_filter_ignores_unknown_names_keeps_valid(self):
|
| 77 |
-
defs = get_tool_definitions(enabled=["search_courses", "bogus"])
|
| 78 |
-
self.assertEqual(len(defs), 1)
|
| 79 |
-
self.assertEqual(defs[0]["function"]["name"], "search_courses")
|
| 80 |
|
| 81 |
|
| 82 |
class TestGetToolExecutor(unittest.TestCase):
|
| 83 |
-
"""get_tool_executor() returns a dispatcher that routes to the
|
| 84 |
-
correct tool executor."""
|
| 85 |
-
|
| 86 |
-
def test_dispatch_known_tool(self):
|
| 87 |
-
mock_exec = AsyncMock(return_value={"courses": []})
|
| 88 |
-
original = _REGISTRY["search_courses"]["executor"]
|
| 89 |
-
_REGISTRY["search_courses"]["executor"] = mock_exec
|
| 90 |
-
try:
|
| 91 |
-
dispatch = get_tool_executor()
|
| 92 |
-
result = asyncio.run(dispatch(name="search_courses", subject="CSCI"))
|
| 93 |
-
mock_exec.assert_called_once_with(name="search_courses", subject="CSCI")
|
| 94 |
-
self.assertEqual(result, {"courses": []})
|
| 95 |
-
finally:
|
| 96 |
-
_REGISTRY["search_courses"]["executor"] = original
|
| 97 |
-
|
| 98 |
def test_dispatch_unknown_tool_returns_error(self):
|
| 99 |
dispatch = get_tool_executor()
|
| 100 |
result = asyncio.run(dispatch(name="nonexistent"))
|
| 101 |
self.assertIn("error", result)
|
| 102 |
-
|
| 103 |
-
def test_filtered_executor_allows_enabled_tool(self):
|
| 104 |
-
mock_exec = AsyncMock(return_value={"courses": []})
|
| 105 |
-
original = _REGISTRY["search_courses"]["executor"]
|
| 106 |
-
_REGISTRY["search_courses"]["executor"] = mock_exec
|
| 107 |
-
try:
|
| 108 |
-
dispatch = get_tool_executor(enabled=["search_courses"])
|
| 109 |
-
result = asyncio.run(dispatch(name="search_courses", subject="CSCI"))
|
| 110 |
-
self.assertNotIn("error", result)
|
| 111 |
-
finally:
|
| 112 |
-
_REGISTRY["search_courses"]["executor"] = original
|
| 113 |
-
|
| 114 |
-
def test_filtered_executor_blocks_disabled_tool(self):
|
| 115 |
-
dispatch = get_tool_executor(enabled=["search_courses"])
|
| 116 |
-
result = asyncio.run(dispatch(name="rate_my_professor", professor_name="Smith"))
|
| 117 |
-
self.assertIn("error", result)
|
| 118 |
-
self.assertIn("not enabled", result["error"])
|
| 119 |
-
|
| 120 |
-
def test_filtered_executor_with_empty_list_blocks_all(self):
|
| 121 |
-
dispatch = get_tool_executor(enabled=[])
|
| 122 |
-
result = asyncio.run(dispatch(name="search_courses", subject="CSCI"))
|
| 123 |
-
self.assertIn("error", result)
|
|
|
|
| 10 |
)
|
| 11 |
|
| 12 |
|
| 13 |
+
KNOWN_TOOLS = {"get_current_datetime"}
|
| 14 |
|
| 15 |
|
| 16 |
class TestToolDiscovery(unittest.TestCase):
|
|
|
|
|
|
|
|
|
|
| 17 |
def test_known_tools_are_discovered(self):
|
| 18 |
registered = set(list_registered_tools())
|
| 19 |
for name in KNOWN_TOOLS:
|
|
|
|
| 24 |
self.assertIn("definition", entry, f"'{name}' missing definition")
|
| 25 |
self.assertIn("executor", entry, f"'{name}' missing executor")
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
class TestGetToolDefinitions(unittest.TestCase):
|
|
|
|
|
|
|
|
|
|
| 29 |
def test_returns_all_when_no_filter(self):
|
| 30 |
defs = get_tool_definitions()
|
| 31 |
names = {d["function"]["name"] for d in defs}
|
| 32 |
self.assertTrue(KNOWN_TOOLS.issubset(names))
|
| 33 |
|
| 34 |
def test_filter_to_single_tool(self):
|
| 35 |
+
defs = get_tool_definitions(enabled=["get_current_datetime"])
|
| 36 |
self.assertEqual(len(defs), 1)
|
| 37 |
+
self.assertEqual(defs[0]["function"]["name"], "get_current_datetime")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
|
| 40 |
class TestGetToolExecutor(unittest.TestCase):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
def test_dispatch_unknown_tool_returns_error(self):
|
| 42 |
dispatch = get_tool_executor()
|
| 43 |
result = asyncio.run(dispatch(name="nonexistent"))
|
| 44 |
self.assertIn("error", result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
multi_llm_chatbot_backend/app/utils/chat_summary.py
CHANGED
|
@@ -1,12 +1,61 @@
|
|
| 1 |
-
from typing import List
|
| 2 |
-
|
| 3 |
-
from app.config import get_settings
|
| 4 |
import logging
|
| 5 |
import re
|
| 6 |
-
|
|
|
|
|
|
|
| 7 |
|
| 8 |
logger = logging.getLogger(__name__)
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
async def generate_summary_from_messages(messages: List[dict], llm: LLMClient, max_tokens: int = 800) -> str:
|
| 11 |
"""
|
| 12 |
Summarize the conversation using the given LLM client.
|
|
|
|
| 1 |
+
from typing import Dict, List, Optional
|
| 2 |
+
|
|
|
|
| 3 |
import logging
|
| 4 |
import re
|
| 5 |
+
|
| 6 |
+
from app.llm.llm_client import LLMClient
|
| 7 |
+
from app.config import get_settings
|
| 8 |
|
| 9 |
logger = logging.getLogger(__name__)
|
| 10 |
|
| 11 |
+
CONTEXT_SUMMARY_SYSTEM = (
|
| 12 |
+
"You are a concise summarizer. Condense the following conversation into a short summary "
|
| 13 |
+
"that preserves the key topics discussed, any conclusions reached, important facts shared, "
|
| 14 |
+
"and the overall tone. Keep it under 300 words. Write in third person narrative form."
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _conversation_role_label(role: str, persona_names: Optional[Dict[str, str]] = None) -> str:
|
| 19 |
+
if role == "user":
|
| 20 |
+
return "User"
|
| 21 |
+
if role == "assistant":
|
| 22 |
+
return "Assistant"
|
| 23 |
+
if persona_names and role in persona_names:
|
| 24 |
+
return persona_names[role]
|
| 25 |
+
return role.replace("_", " ").title()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
async def generate_conversation_context_summary(
|
| 29 |
+
messages: List[dict],
|
| 30 |
+
llm: LLMClient,
|
| 31 |
+
persona_names: Optional[Dict[str, str]] = None,
|
| 32 |
+
max_tokens: int = 1024,
|
| 33 |
+
) -> str:
|
| 34 |
+
"""Summarize chat history for LLM context when the transcript exceeds the token budget."""
|
| 35 |
+
transcript_lines = []
|
| 36 |
+
for msg in messages:
|
| 37 |
+
content = (msg.get("content") or "").strip()
|
| 38 |
+
if not content:
|
| 39 |
+
continue
|
| 40 |
+
label = _conversation_role_label(msg.get("role", "user"), persona_names)
|
| 41 |
+
transcript_lines.append(f"{label}: {content}")
|
| 42 |
+
|
| 43 |
+
if not transcript_lines:
|
| 44 |
+
return ""
|
| 45 |
+
|
| 46 |
+
transcript = "\n".join(transcript_lines)
|
| 47 |
+
try:
|
| 48 |
+
summary = await llm.generate(
|
| 49 |
+
system_prompt=CONTEXT_SUMMARY_SYSTEM,
|
| 50 |
+
context=[{"role": "user", "content": transcript}],
|
| 51 |
+
temperature=0.3,
|
| 52 |
+
max_tokens=max_tokens,
|
| 53 |
+
)
|
| 54 |
+
return (summary or "").strip()
|
| 55 |
+
except Exception as exc:
|
| 56 |
+
logger.error("Conversation context summary failed: %s", exc)
|
| 57 |
+
return ""
|
| 58 |
+
|
| 59 |
async def generate_summary_from_messages(messages: List[dict], llm: LLMClient, max_tokens: int = 800) -> str:
|
| 60 |
"""
|
| 61 |
Summarize the conversation using the given LLM client.
|