Codexcoder commited on
Commit
7e081c6
·
verified ·
1 Parent(s): 14b0da7

integration: add chat/api/routes.py

Browse files
Files changed (1) hide show
  1. chat/api/routes.py +113 -0
chat/api/routes.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # chat/api/routes.py
2
+ """
3
+ DeepSeek V4 chat API — endpoints under /api/v1/chat/*.
4
+
5
+ Sessions are held in memory (bounded history). Model calls go through
6
+ DeepSeekV4Client — API mode with DEEPSEEK_API_KEY, local echo otherwise.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import time
12
+ from typing import Any, Dict, List
13
+
14
+ from fastapi import APIRouter, HTTPException
15
+ from pydantic import BaseModel, Field
16
+
17
+ from chat.core import SOVEREIGN_SYSTEM_PROMPT, ChatSession, get_client
18
+
19
+ router = APIRouter(prefix="/api/v1/chat", tags=["chat"])
20
+
21
+ sessions: Dict[str, ChatSession] = {}
22
+
23
+
24
+ class SendIn(BaseModel):
25
+ message: str = Field(min_length=1)
26
+ session_id: str = ""
27
+ temperature: float = 0.7
28
+ max_tokens: int = 1024
29
+
30
+
31
+ class SessionOut(BaseModel):
32
+ session_id: str
33
+ model: str
34
+ messages: List[Dict[str, Any]]
35
+ created_at: float
36
+
37
+
38
+ def _get_or_create(session_id: str) -> ChatSession:
39
+ if session_id and session_id in sessions:
40
+ return sessions[session_id]
41
+ session = ChatSession()
42
+ session.add("system", SOVEREIGN_SYSTEM_PROMPT)
43
+ sessions[session.session_id] = session
44
+ return session
45
+
46
+
47
+ @router.post("/sessions")
48
+ async def create_session() -> Dict[str, Any]:
49
+ """Create a new chat session."""
50
+ session = _get_or_create("")
51
+ return {
52
+ "session_id": session.session_id,
53
+ "model": session.model,
54
+ "mode": "api" if not get_client().local_mode else "local",
55
+ "created_at": session.created_at,
56
+ }
57
+
58
+
59
+ @router.get("/sessions/{session_id}")
60
+ async def get_session(session_id: str) -> Dict[str, Any]:
61
+ """Session + message history."""
62
+ session = sessions.get(session_id)
63
+ if session is None:
64
+ raise HTTPException(status_code=404, detail="session not found")
65
+ return {
66
+ "session_id": session.session_id,
67
+ "model": session.model,
68
+ "messages": [{"role": m.role, "content": m.content, "ts": m.timestamp}
69
+ for m in session.messages],
70
+ "created_at": session.created_at,
71
+ }
72
+
73
+
74
+ @router.post("/send")
75
+ async def send_message(body: SendIn) -> Dict[str, Any]:
76
+ """Send a message and get an assistant reply."""
77
+ client = get_client()
78
+ session = _get_or_create(body.session_id)
79
+ session.add("user", body.message)
80
+ try:
81
+ result = client.complete(session, temperature=body.temperature,
82
+ max_tokens=body.max_tokens)
83
+ except RuntimeError as exc:
84
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
85
+ session.add("assistant", result["content"])
86
+ return {
87
+ "session_id": session.session_id,
88
+ "reply": result["content"],
89
+ "model": result["model"],
90
+ "mode": result["mode"],
91
+ "usage": result.get("usage", {}),
92
+ "timestamp": time.time(),
93
+ }
94
+
95
+
96
+ @router.get("/models")
97
+ async def list_models() -> Dict[str, Any]:
98
+ """Available models."""
99
+ return {"models": get_client().list_models(),
100
+ "active": get_client().model,
101
+ "mode": "api" if not get_client().local_mode else "local"}
102
+
103
+
104
+ @router.get("/status")
105
+ async def chat_status() -> Dict[str, Any]:
106
+ """Chat module status."""
107
+ client = get_client()
108
+ return {
109
+ "mode": "api" if not client.local_mode else "local",
110
+ "model": client.model,
111
+ "base_url": client.base_url,
112
+ "sessions": len(sessions),
113
+ }