Codexcoder commited on
Commit
14b0da7
·
verified ·
1 Parent(s): 29b2326

integration: add chat/core.py

Browse files
Files changed (1) hide show
  1. chat/core.py +160 -0
chat/core.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # chat/core.py
2
+ """
3
+ DeepSeek V4 chat module — sovereign-tuned conversational core.
4
+
5
+ DeepSeekV4Client speaks the OpenAI-compatible /chat/completions schema
6
+ against a configurable base URL. When no DEEPSEEK_API_KEY is set it runs
7
+ in LOCAL mode: deterministic sovereign-context responses (no network).
8
+
9
+ Model identity: sovereign/deepseek-v4-sovereign (304B MoE, sovereign-
10
+ tuned, MIT lineage) — see models/deepseek-v4-sovereign/.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import time
17
+ import uuid
18
+ from dataclasses import dataclass, field
19
+ from typing import Any, Dict, List, Optional
20
+
21
+ import requests
22
+
23
+ DEFAULT_BASE_URL = "https://api.deepseek.com/v1"
24
+ DEFAULT_MODEL = "sovereign/deepseek-v4-sovereign"
25
+
26
+ # System prompt with sovereign context (modules available to the agent)
27
+ SOVEREIGN_SYSTEM_PROMPT = (
28
+ "You are the DeepSeek-V4-Sovereign conversational core of the Sovereign stack. "
29
+ "You have access to these modules: kyrexis (quantum-inspired intelligence, 53-qubit "
30
+ "simulation, quantum skills), pec5d (8-core hierarchy, pattern bridge, invisible "
31
+ "pressure theory, coral ecosystem), coldcase (PEC5D cold-case grid — hypothesis "
32
+ "lattice only, never legal conclusions). Be honest: all 'quantum' behavior is "
33
+ "simulation; annotate confidence; never overclaim."
34
+ )
35
+
36
+
37
+ @dataclass
38
+ class ChatMessage:
39
+ """A chat message."""
40
+
41
+ role: str # system | user | assistant
42
+ content: str
43
+ timestamp: float = field(default_factory=time.time)
44
+
45
+
46
+ @dataclass
47
+ class ChatSession:
48
+ """A conversational session with bounded history."""
49
+
50
+ session_id: str = field(default_factory=lambda: f"ses_{uuid.uuid4().hex[:12]}")
51
+ model: str = DEFAULT_MODEL
52
+ messages: List[ChatMessage] = field(default_factory=list)
53
+ max_history: int = 50
54
+ created_at: float = field(default_factory=time.time)
55
+
56
+ def add(self, role: str, content: str) -> ChatMessage:
57
+ msg = ChatMessage(role=role, content=content)
58
+ self.messages.append(msg)
59
+ if len(self.messages) > self.max_history:
60
+ # keep system prompt + most recent window
61
+ head = [m for m in self.messages if m.role == "system"][:1]
62
+ tail = self.messages[-self.max_history :]
63
+ self.messages = head + [m for m in tail if m.role != "system"]
64
+ return msg
65
+
66
+ def to_api(self) -> List[Dict[str, str]]:
67
+ """Messages in OpenAI chat-completions format."""
68
+ return [{"role": m.role, "content": m.content} for m in self.messages]
69
+
70
+
71
+ class DeepSeekV4Client:
72
+ """
73
+ OpenAI-compatible DeepSeek V4 client with local-echo fallback.
74
+
75
+ Env config:
76
+ DEEPSEEK_API_BASE — API base URL (default https://api.deepseek.com/v1)
77
+ DEEPSEEK_API_KEY — API key; unset → local mode
78
+ DEEPSEEK_MODEL — model id (default sovereign/deepseek-v4-sovereign)
79
+ """
80
+
81
+ def __init__(self, base_url: Optional[str] = None, api_key: Optional[str] = None,
82
+ model: Optional[str] = None, timeout: int = 60):
83
+ self.base_url = (base_url or os.environ.get("DEEPSEEK_API_BASE", DEFAULT_BASE_URL)).rstrip("/")
84
+ self.api_key = api_key or os.environ.get("DEEPSEEK_API_KEY", "")
85
+ self.model = model or os.environ.get("DEEPSEEK_MODEL", DEFAULT_MODEL)
86
+ self.timeout = timeout
87
+
88
+ @property
89
+ def local_mode(self) -> bool:
90
+ """True when no API key is configured (deterministic local echo)."""
91
+ return not self.api_key
92
+
93
+ def complete(self, session: ChatSession, temperature: float = 0.7,
94
+ max_tokens: int = 1024) -> Dict[str, Any]:
95
+ """Generate an assistant reply for the session."""
96
+ if self.local_mode:
97
+ return self._local_complete(session)
98
+ return self._api_complete(session, temperature, max_tokens)
99
+
100
+ def _api_complete(self, session: ChatSession, temperature: float,
101
+ max_tokens: int) -> Dict[str, Any]:
102
+ """Call the OpenAI-compatible chat completions endpoint."""
103
+ url = f"{self.base_url}/chat/completions"
104
+ payload = {
105
+ "model": session.model or self.model,
106
+ "messages": session.to_api(),
107
+ "temperature": temperature,
108
+ "max_tokens": max_tokens,
109
+ }
110
+ response = requests.post(
111
+ url,
112
+ headers={"Authorization": f"Bearer {self.api_key}",
113
+ "Content-Type": "application/json"},
114
+ json=payload,
115
+ timeout=self.timeout,
116
+ )
117
+ if response.status_code != 200:
118
+ raise RuntimeError(f"DeepSeek API error {response.status_code}: {response.text[:300]}")
119
+ data = response.json()
120
+ content = data["choices"][0]["message"]["content"]
121
+ return {
122
+ "content": content,
123
+ "model": data.get("model", self.model),
124
+ "usage": data.get("usage", {}),
125
+ "mode": "api",
126
+ }
127
+
128
+ def _local_complete(self, session: ChatSession) -> Dict[str, Any]:
129
+ """Deterministic local fallback �� no network, no key required."""
130
+ user_msgs = [m for m in session.messages if m.role == "user"]
131
+ last = user_msgs[-1].content if user_msgs else ""
132
+ content = (
133
+ f"🌀 Sovereign local echo (no DEEPSEEK_API_KEY configured — API mode "
134
+ f"would call {self.base_url}/chat/completions with model {self.model}).\n"
135
+ f"Received: {last[:200] or '(empty)'}"
136
+ )
137
+ return {"content": content, "model": self.model, "usage": {}, "mode": "local"}
138
+
139
+ def list_models(self) -> List[Dict[str, str]]:
140
+ """Available models (local registry summary + API if key set)."""
141
+ models = [
142
+ {"id": "sovereign/deepseek-v4-sovereign", "type": "llm", "params": "304B MoE",
143
+ "license": "MIT", "status": "sovereign-tuned"},
144
+ {"id": "deepseek-v4-flash-0731", "type": "llm", "params": "304B MoE",
145
+ "license": "MIT", "status": "upstream-base"},
146
+ {"id": "gemma-3-12b-it-jailbreak", "type": "llm", "params": "12B",
147
+ "format": "GGUF", "status": "integrated"},
148
+ ]
149
+ return models
150
+
151
+
152
+ # Singleton (lazy — reads env at first use)
153
+ _client: Optional[DeepSeekV4Client] = None
154
+
155
+
156
+ def get_client() -> DeepSeekV4Client:
157
+ global _client
158
+ if _client is None:
159
+ _client = DeepSeekV4Client()
160
+ return _client