valkyria-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- valkyria_cli-0.1.0.dist-info/METADATA +117 -0
- valkyria_cli-0.1.0.dist-info/RECORD +55 -0
- valkyria_cli-0.1.0.dist-info/WHEEL +4 -0
- valkyria_cli-0.1.0.dist-info/entry_points.txt +3 -0
- valkyrie/__init__.py +5 -0
- valkyrie/auth/__init__.py +21 -0
- valkyrie/auth/account.py +245 -0
- valkyrie/auth/firebase_config.py +28 -0
- valkyrie/auth/login_page.py +177 -0
- valkyrie/auth/server.py +145 -0
- valkyrie/auth/tokens.py +196 -0
- valkyrie/chat/__init__.py +37 -0
- valkyrie/chat/clients.py +431 -0
- valkyrie/chat/commands.py +229 -0
- valkyrie/chat/engine.py +1458 -0
- valkyrie/chat/messages.py +108 -0
- valkyrie/chat/renderer.py +122 -0
- valkyrie/cli/__init__.py +2 -0
- valkyrie/cli/auth_commands.py +61 -0
- valkyrie/cli/chat_commands.py +139 -0
- valkyrie/cli/keys_commands.py +275 -0
- valkyrie/cli/main.py +179 -0
- valkyrie/cli/model_commands.py +334 -0
- valkyrie/cli/rag_commands.py +191 -0
- valkyrie/cli/session_commands.py +247 -0
- valkyrie/cli/setup_wizard.py +510 -0
- valkyrie/core/__init__.py +2 -0
- valkyrie/core/cards.py +55 -0
- valkyrie/core/config.py +84 -0
- valkyrie/core/console.py +122 -0
- valkyrie/core/paths.py +68 -0
- valkyrie/core/workspace.py +87 -0
- valkyrie/providers/__init__.py +23 -0
- valkyrie/providers/base.py +78 -0
- valkyrie/providers/gemini.py +141 -0
- valkyrie/providers/groq.py +102 -0
- valkyrie/providers/nvidia.py +95 -0
- valkyrie/providers/registry.py +233 -0
- valkyrie/rag/__init__.py +32 -0
- valkyrie/rag/chunker.py +75 -0
- valkyrie/rag/embeddings.py +227 -0
- valkyrie/rag/files.py +163 -0
- valkyrie/rag/pinecone_store.py +191 -0
- valkyrie/rag/pipeline.py +170 -0
- valkyrie/sessions/__init__.py +9 -0
- valkyrie/sessions/store.py +544 -0
- valkyrie/tools/__init__.py +6 -0
- valkyrie/tools/local_fs.py +423 -0
- valkyrie/tools/registry.py +100 -0
- valkyrie/tools/web_search.py +73 -0
- valkyrie/vault/__init__.py +26 -0
- valkyrie/vault/crypto.py +119 -0
- valkyrie/vault/prompt.py +77 -0
- valkyrie/vault/store.py +207 -0
- valkyrie/vault/sync.py +140 -0
valkyrie/chat/clients.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Streaming chat completion clients for Groq, Gemini, and NVIDIA NIM, with tool calling.
|
|
3
|
+
|
|
4
|
+
Groq and NVIDIA NIM share the OpenAI SSE streaming protocol via a single helper;
|
|
5
|
+
Gemini uses its streamGenerateContent?alt=sse endpoint with functionDeclarations.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import TYPE_CHECKING, Any
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from valkyrie.chat.messages import ChatMessage, MessageRole, TokenUsage
|
|
18
|
+
from valkyrie.providers.gemini import GEMINI_API_BASE
|
|
19
|
+
from valkyrie.providers.groq import GROQ_API_BASE
|
|
20
|
+
from valkyrie.providers.nvidia import NVIDIA_API_BASE
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from collections.abc import AsyncIterator
|
|
24
|
+
|
|
25
|
+
_SUGGESTED_MODEL_RE = re.compile(r"models/([A-Za-z0-9_.\-]+)")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ChatStreamError(RuntimeError):
|
|
29
|
+
"""Raised when a provider rejects or fails during a streaming completion."""
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
message: str,
|
|
34
|
+
*,
|
|
35
|
+
status_code: int | None = None,
|
|
36
|
+
suggested_model: str | None = None,
|
|
37
|
+
) -> None:
|
|
38
|
+
super().__init__(message)
|
|
39
|
+
self.status_code = status_code
|
|
40
|
+
self.suggested_model = suggested_model
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class ToolCall:
|
|
45
|
+
"""Normalized tool/function invocation emitted by any provider."""
|
|
46
|
+
|
|
47
|
+
id: str
|
|
48
|
+
name: str
|
|
49
|
+
arguments: dict[str, Any]
|
|
50
|
+
|
|
51
|
+
def to_openai_dict(self) -> dict[str, Any]:
|
|
52
|
+
"""Serialize back into an OpenAI assistant tool_calls entry."""
|
|
53
|
+
return {
|
|
54
|
+
"id": self.id,
|
|
55
|
+
"type": "function",
|
|
56
|
+
"function": {
|
|
57
|
+
"name": self.name,
|
|
58
|
+
"arguments": json.dumps(self.arguments),
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass
|
|
64
|
+
class StreamChunk:
|
|
65
|
+
"""A single streamed event from a provider."""
|
|
66
|
+
|
|
67
|
+
delta: str = ""
|
|
68
|
+
usage: TokenUsage | None = None
|
|
69
|
+
finish_reason: str | None = None
|
|
70
|
+
tool_calls: list[ToolCall] | None = None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _parse_provider_error(
|
|
74
|
+
*,
|
|
75
|
+
provider_key: str,
|
|
76
|
+
model_id: str,
|
|
77
|
+
status_code: int,
|
|
78
|
+
raw_body: str,
|
|
79
|
+
) -> ChatStreamError:
|
|
80
|
+
"""Extract clean message and optional replacement suggestion from provider error JSON."""
|
|
81
|
+
clean_msg = raw_body.strip()
|
|
82
|
+
try:
|
|
83
|
+
parsed = json.loads(raw_body)
|
|
84
|
+
if isinstance(parsed, dict):
|
|
85
|
+
err_obj = parsed.get("error")
|
|
86
|
+
if isinstance(err_obj, dict) and err_obj.get("message"):
|
|
87
|
+
clean_msg = str(err_obj["message"])
|
|
88
|
+
elif parsed.get("message"):
|
|
89
|
+
clean_msg = str(parsed["message"])
|
|
90
|
+
except json.JSONDecodeError:
|
|
91
|
+
pass
|
|
92
|
+
|
|
93
|
+
if len(clean_msg) > 400:
|
|
94
|
+
clean_msg = clean_msg[:397] + "..."
|
|
95
|
+
|
|
96
|
+
suggested_model: str | None = None
|
|
97
|
+
if provider_key == "gemini":
|
|
98
|
+
for match in _SUGGESTED_MODEL_RE.findall(clean_msg):
|
|
99
|
+
if match != model_id:
|
|
100
|
+
suggested_model = f"gemini/{match}"
|
|
101
|
+
break
|
|
102
|
+
|
|
103
|
+
return ChatStreamError(
|
|
104
|
+
f"HTTP {status_code}: {clean_msg}",
|
|
105
|
+
status_code=status_code,
|
|
106
|
+
suggested_model=suggested_model,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _finalize_openai_tool_calls(acc: dict[int, dict[str, Any]]) -> list[ToolCall]:
|
|
111
|
+
"""Convert accumulated OpenAI streaming delta tool_calls into ToolCall objects."""
|
|
112
|
+
calls: list[ToolCall] = []
|
|
113
|
+
for idx in sorted(acc.keys()):
|
|
114
|
+
entry = acc[idx]
|
|
115
|
+
raw_args = "".join(entry["args_parts"]).strip()
|
|
116
|
+
try:
|
|
117
|
+
parsed = json.loads(raw_args) if raw_args else {}
|
|
118
|
+
args = parsed if isinstance(parsed, dict) else {}
|
|
119
|
+
except json.JSONDecodeError:
|
|
120
|
+
args = {"raw_arguments": raw_args}
|
|
121
|
+
calls.append(
|
|
122
|
+
ToolCall(
|
|
123
|
+
id=entry["id"] or f"call_{idx}",
|
|
124
|
+
name=entry["name"],
|
|
125
|
+
arguments=args,
|
|
126
|
+
)
|
|
127
|
+
)
|
|
128
|
+
return calls
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
async def _stream_openai_compatible(
|
|
132
|
+
*,
|
|
133
|
+
provider_key: str,
|
|
134
|
+
base_url: str,
|
|
135
|
+
api_key: str,
|
|
136
|
+
model_id: str,
|
|
137
|
+
messages: list[ChatMessage],
|
|
138
|
+
temperature: float = 0.7,
|
|
139
|
+
include_stream_usage: bool = True,
|
|
140
|
+
tools: list[dict[str, Any]] | None = None,
|
|
141
|
+
) -> AsyncIterator[StreamChunk]:
|
|
142
|
+
"""Stream completions from any OpenAI-compatible SSE endpoint."""
|
|
143
|
+
payload: dict[str, Any] = {
|
|
144
|
+
"model": model_id,
|
|
145
|
+
"messages": [m.to_openai_dict() for m in messages],
|
|
146
|
+
"stream": True,
|
|
147
|
+
"temperature": temperature,
|
|
148
|
+
}
|
|
149
|
+
if include_stream_usage:
|
|
150
|
+
payload["stream_options"] = {"include_usage": True}
|
|
151
|
+
if tools:
|
|
152
|
+
payload["tools"] = tools
|
|
153
|
+
payload["tool_choice"] = "auto"
|
|
154
|
+
|
|
155
|
+
headers = {
|
|
156
|
+
"Authorization": f"Bearer {api_key}",
|
|
157
|
+
"Content-Type": "application/json",
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
tool_acc: dict[int, dict[str, Any]] = {}
|
|
161
|
+
|
|
162
|
+
try:
|
|
163
|
+
async with (
|
|
164
|
+
httpx.AsyncClient(timeout=60.0) as client,
|
|
165
|
+
client.stream(
|
|
166
|
+
"POST",
|
|
167
|
+
f"{base_url}/chat/completions",
|
|
168
|
+
json=payload,
|
|
169
|
+
headers=headers,
|
|
170
|
+
) as resp,
|
|
171
|
+
):
|
|
172
|
+
if resp.status_code >= 400:
|
|
173
|
+
body = (await resp.aread()).decode("utf-8", errors="replace")
|
|
174
|
+
raise _parse_provider_error(
|
|
175
|
+
provider_key=provider_key,
|
|
176
|
+
model_id=model_id,
|
|
177
|
+
status_code=resp.status_code,
|
|
178
|
+
raw_body=body,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
async for line in resp.aiter_lines():
|
|
182
|
+
if not line or not line.startswith("data:"):
|
|
183
|
+
continue
|
|
184
|
+
data_str = line[5:].strip()
|
|
185
|
+
if data_str == "[DONE]":
|
|
186
|
+
break
|
|
187
|
+
|
|
188
|
+
try:
|
|
189
|
+
event = json.loads(data_str)
|
|
190
|
+
except json.JSONDecodeError:
|
|
191
|
+
continue
|
|
192
|
+
|
|
193
|
+
usage_obj = event.get("usage")
|
|
194
|
+
usage: TokenUsage | None = None
|
|
195
|
+
if isinstance(usage_obj, dict):
|
|
196
|
+
usage = TokenUsage(
|
|
197
|
+
prompt_tokens=int(usage_obj.get("prompt_tokens", 0)),
|
|
198
|
+
completion_tokens=int(usage_obj.get("completion_tokens", 0)),
|
|
199
|
+
estimated=False,
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
choices = event.get("choices") or []
|
|
203
|
+
if not choices:
|
|
204
|
+
if usage is not None:
|
|
205
|
+
yield StreamChunk(usage=usage)
|
|
206
|
+
continue
|
|
207
|
+
|
|
208
|
+
choice = choices[0]
|
|
209
|
+
delta_obj = choice.get("delta", {})
|
|
210
|
+
delta = delta_obj.get("content") or ""
|
|
211
|
+
finish_reason = choice.get("finish_reason")
|
|
212
|
+
|
|
213
|
+
for tc in delta_obj.get("tool_calls") or []:
|
|
214
|
+
idx = int(tc.get("index", 0))
|
|
215
|
+
slot = tool_acc.setdefault(
|
|
216
|
+
idx,
|
|
217
|
+
{"id": "", "name": "", "args_parts": []},
|
|
218
|
+
)
|
|
219
|
+
if tc.get("id"):
|
|
220
|
+
slot["id"] = str(tc["id"])
|
|
221
|
+
fn = tc.get("function") or {}
|
|
222
|
+
if fn.get("name"):
|
|
223
|
+
slot["name"] += str(fn["name"])
|
|
224
|
+
if fn.get("arguments"):
|
|
225
|
+
slot["args_parts"].append(str(fn["arguments"]))
|
|
226
|
+
|
|
227
|
+
if delta or usage is not None or finish_reason:
|
|
228
|
+
yield StreamChunk(delta=delta, usage=usage, finish_reason=finish_reason)
|
|
229
|
+
|
|
230
|
+
if tool_acc:
|
|
231
|
+
yield StreamChunk(tool_calls=_finalize_openai_tool_calls(tool_acc))
|
|
232
|
+
except httpx.HTTPError as exc:
|
|
233
|
+
raise ChatStreamError(f"Network error: {exc}") from exc
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _build_gemini_contents(messages: list[ChatMessage]) -> tuple[list[str], list[dict[str, Any]]]:
|
|
237
|
+
"""Convert ChatMessage history into Gemini systemInstruction parts and contents."""
|
|
238
|
+
system_parts: list[str] = []
|
|
239
|
+
contents: list[dict[str, Any]] = []
|
|
240
|
+
|
|
241
|
+
for msg in messages:
|
|
242
|
+
if msg.role == MessageRole.SYSTEM:
|
|
243
|
+
system_parts.append(msg.content)
|
|
244
|
+
continue
|
|
245
|
+
|
|
246
|
+
if msg.role == MessageRole.ASSISTANT:
|
|
247
|
+
parts: list[dict[str, Any]] = []
|
|
248
|
+
if msg.content:
|
|
249
|
+
parts.append({"text": msg.content})
|
|
250
|
+
for tc in msg.tool_calls or []:
|
|
251
|
+
fn = tc.get("function", {})
|
|
252
|
+
raw_args = fn.get("arguments", "{}")
|
|
253
|
+
try:
|
|
254
|
+
parsed_args = json.loads(raw_args) if isinstance(raw_args, str) else raw_args
|
|
255
|
+
except json.JSONDecodeError:
|
|
256
|
+
parsed_args = {}
|
|
257
|
+
parts.append(
|
|
258
|
+
{
|
|
259
|
+
"functionCall": {
|
|
260
|
+
"name": fn.get("name", ""),
|
|
261
|
+
"args": parsed_args if isinstance(parsed_args, dict) else {},
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
)
|
|
265
|
+
if parts:
|
|
266
|
+
contents.append({"role": "model", "parts": parts})
|
|
267
|
+
continue
|
|
268
|
+
|
|
269
|
+
if msg.role == MessageRole.TOOL:
|
|
270
|
+
resp_part = {
|
|
271
|
+
"functionResponse": {
|
|
272
|
+
"name": msg.name or "tool",
|
|
273
|
+
"response": {"result": msg.content},
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if contents and contents[-1]["role"] == "user" and any(
|
|
277
|
+
"functionResponse" in p for p in contents[-1]["parts"]
|
|
278
|
+
):
|
|
279
|
+
contents[-1]["parts"].append(resp_part)
|
|
280
|
+
else:
|
|
281
|
+
contents.append({"role": "user", "parts": [resp_part]})
|
|
282
|
+
continue
|
|
283
|
+
|
|
284
|
+
contents.append({"role": "user", "parts": [{"text": msg.content}]})
|
|
285
|
+
|
|
286
|
+
return system_parts, contents
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
async def _stream_gemini(
|
|
290
|
+
*,
|
|
291
|
+
api_key: str,
|
|
292
|
+
model_id: str,
|
|
293
|
+
messages: list[ChatMessage],
|
|
294
|
+
temperature: float = 0.7,
|
|
295
|
+
function_declarations: list[dict[str, Any]] | None = None,
|
|
296
|
+
) -> AsyncIterator[StreamChunk]:
|
|
297
|
+
"""Stream completions from Gemini streamGenerateContent?alt=sse."""
|
|
298
|
+
system_parts, contents = _build_gemini_contents(messages)
|
|
299
|
+
|
|
300
|
+
payload: dict[str, Any] = {
|
|
301
|
+
"contents": contents,
|
|
302
|
+
"generationConfig": {"temperature": temperature},
|
|
303
|
+
}
|
|
304
|
+
if system_parts:
|
|
305
|
+
payload["systemInstruction"] = {"parts": [{"text": "\n\n".join(system_parts)}]}
|
|
306
|
+
if function_declarations:
|
|
307
|
+
payload["tools"] = [{"functionDeclarations": function_declarations}]
|
|
308
|
+
|
|
309
|
+
url = f"{GEMINI_API_BASE}/models/{model_id}:streamGenerateContent"
|
|
310
|
+
params = {"alt": "sse", "key": api_key}
|
|
311
|
+
|
|
312
|
+
call_seq = 0
|
|
313
|
+
try:
|
|
314
|
+
async with (
|
|
315
|
+
httpx.AsyncClient(timeout=60.0) as client,
|
|
316
|
+
client.stream("POST", url, params=params, json=payload) as resp,
|
|
317
|
+
):
|
|
318
|
+
if resp.status_code >= 400:
|
|
319
|
+
body = (await resp.aread()).decode("utf-8", errors="replace")
|
|
320
|
+
raise _parse_provider_error(
|
|
321
|
+
provider_key="gemini",
|
|
322
|
+
model_id=model_id,
|
|
323
|
+
status_code=resp.status_code,
|
|
324
|
+
raw_body=body,
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
async for line in resp.aiter_lines():
|
|
328
|
+
if not line or not line.startswith("data:"):
|
|
329
|
+
continue
|
|
330
|
+
data_str = line[5:].strip()
|
|
331
|
+
if not data_str or data_str == "[DONE]":
|
|
332
|
+
continue
|
|
333
|
+
|
|
334
|
+
try:
|
|
335
|
+
event = json.loads(data_str)
|
|
336
|
+
except json.JSONDecodeError:
|
|
337
|
+
continue
|
|
338
|
+
|
|
339
|
+
usage: TokenUsage | None = None
|
|
340
|
+
meta = event.get("usageMetadata")
|
|
341
|
+
if isinstance(meta, dict):
|
|
342
|
+
usage = TokenUsage(
|
|
343
|
+
prompt_tokens=int(meta.get("promptTokenCount", 0)),
|
|
344
|
+
completion_tokens=int(meta.get("candidatesTokenCount", 0)),
|
|
345
|
+
estimated=False,
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
candidates = event.get("candidates") or []
|
|
349
|
+
text_parts: list[str] = []
|
|
350
|
+
tool_calls: list[ToolCall] = []
|
|
351
|
+
finish_reason: str | None = None
|
|
352
|
+
if candidates:
|
|
353
|
+
cand = candidates[0]
|
|
354
|
+
finish_reason = cand.get("finishReason")
|
|
355
|
+
parts = cand.get("content", {}).get("parts", [])
|
|
356
|
+
for p in parts:
|
|
357
|
+
if not isinstance(p, dict):
|
|
358
|
+
continue
|
|
359
|
+
if "text" in p and p["text"]:
|
|
360
|
+
text_parts.append(str(p["text"]))
|
|
361
|
+
if "functionCall" in p and isinstance(p["functionCall"], dict):
|
|
362
|
+
fc = p["functionCall"]
|
|
363
|
+
call_seq += 1
|
|
364
|
+
args = fc.get("args")
|
|
365
|
+
tool_calls.append(
|
|
366
|
+
ToolCall(
|
|
367
|
+
id=f"gemini_call_{call_seq}",
|
|
368
|
+
name=str(fc.get("name", "")),
|
|
369
|
+
arguments=args if isinstance(args, dict) else {},
|
|
370
|
+
)
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
text_delta = "".join(text_parts)
|
|
374
|
+
if text_delta or tool_calls or usage is not None or finish_reason:
|
|
375
|
+
yield StreamChunk(
|
|
376
|
+
delta=text_delta,
|
|
377
|
+
usage=usage,
|
|
378
|
+
finish_reason=finish_reason,
|
|
379
|
+
tool_calls=tool_calls or None,
|
|
380
|
+
)
|
|
381
|
+
except httpx.HTTPError as exc:
|
|
382
|
+
raise ChatStreamError(f"Network error: {exc}") from exc
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
async def stream_chat_completion(
|
|
386
|
+
*,
|
|
387
|
+
provider_key: str,
|
|
388
|
+
model_id: str,
|
|
389
|
+
api_key: str,
|
|
390
|
+
messages: list[ChatMessage],
|
|
391
|
+
temperature: float = 0.7,
|
|
392
|
+
openai_tools: list[dict[str, Any]] | None = None,
|
|
393
|
+
gemini_declarations: list[dict[str, Any]] | None = None,
|
|
394
|
+
) -> AsyncIterator[StreamChunk]:
|
|
395
|
+
"""Dispatch streaming completion to the requested provider."""
|
|
396
|
+
pkey = provider_key.lower()
|
|
397
|
+
if pkey == "groq":
|
|
398
|
+
async for chunk in _stream_openai_compatible(
|
|
399
|
+
provider_key="groq",
|
|
400
|
+
base_url=GROQ_API_BASE,
|
|
401
|
+
api_key=api_key,
|
|
402
|
+
model_id=model_id,
|
|
403
|
+
messages=messages,
|
|
404
|
+
temperature=temperature,
|
|
405
|
+
include_stream_usage=True,
|
|
406
|
+
tools=openai_tools,
|
|
407
|
+
):
|
|
408
|
+
yield chunk
|
|
409
|
+
elif pkey == "nvidia":
|
|
410
|
+
async for chunk in _stream_openai_compatible(
|
|
411
|
+
provider_key="nvidia",
|
|
412
|
+
base_url=NVIDIA_API_BASE,
|
|
413
|
+
api_key=api_key,
|
|
414
|
+
model_id=model_id,
|
|
415
|
+
messages=messages,
|
|
416
|
+
temperature=temperature,
|
|
417
|
+
include_stream_usage=False,
|
|
418
|
+
tools=openai_tools,
|
|
419
|
+
):
|
|
420
|
+
yield chunk
|
|
421
|
+
elif pkey == "gemini":
|
|
422
|
+
async for chunk in _stream_gemini(
|
|
423
|
+
api_key=api_key,
|
|
424
|
+
model_id=model_id,
|
|
425
|
+
messages=messages,
|
|
426
|
+
temperature=temperature,
|
|
427
|
+
function_declarations=gemini_declarations,
|
|
428
|
+
):
|
|
429
|
+
yield chunk
|
|
430
|
+
else:
|
|
431
|
+
raise ChatStreamError(f"Unsupported chat provider: {provider_key}")
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Slash command registry and prompt-toolkit completer (`/`, `/model <id>`, `@path`).
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
|
|
11
|
+
from prompt_toolkit.completion import Completer, Completion
|
|
12
|
+
|
|
13
|
+
from valkyrie.core.workspace import list_workspace_files
|
|
14
|
+
from valkyrie.providers.registry import PROVIDERS
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from collections.abc import Callable, Iterable
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from prompt_toolkit.document import Document
|
|
21
|
+
|
|
22
|
+
from valkyrie.providers.registry import ModelRegistry
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def is_dev_build(feature_flags: dict[str, bool] | None = None) -> bool:
|
|
26
|
+
"""Return True when running in a development build or with dev_mode enabled."""
|
|
27
|
+
if os.environ.get("VALKYRIE_DEV", "").strip().lower() in ("1", "true", "yes"):
|
|
28
|
+
return True
|
|
29
|
+
return bool(feature_flags and feature_flags.get("dev_mode", False))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class SlashCommand:
|
|
34
|
+
"""Definition of a chat slash command."""
|
|
35
|
+
|
|
36
|
+
name: str # e.g. "/help"
|
|
37
|
+
usage: str
|
|
38
|
+
description: str
|
|
39
|
+
handler: Callable[[list[str]], bool] | None = None
|
|
40
|
+
aliases: tuple[str, ...] = ()
|
|
41
|
+
feature_flag: str | None = None
|
|
42
|
+
upcoming: bool = False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class SlashCommandRegistry:
|
|
46
|
+
"""Registry supporting prefix filtering, feature gating, and execution."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, feature_flags: dict[str, bool] | None = None) -> None:
|
|
49
|
+
self.feature_flags = feature_flags or {}
|
|
50
|
+
self._commands: dict[str, SlashCommand] = {}
|
|
51
|
+
|
|
52
|
+
def register(self, cmd: SlashCommand) -> None:
|
|
53
|
+
"""Register a slash command."""
|
|
54
|
+
self._commands[cmd.name.lower()] = cmd
|
|
55
|
+
|
|
56
|
+
def is_executable(self, cmd: SlashCommand) -> bool:
|
|
57
|
+
"""Return True if a command is active and can be executed."""
|
|
58
|
+
if cmd.upcoming:
|
|
59
|
+
return False
|
|
60
|
+
if cmd.feature_flag and not self.feature_flags.get(cmd.feature_flag, False):
|
|
61
|
+
return False
|
|
62
|
+
return cmd.handler is not None
|
|
63
|
+
|
|
64
|
+
def executable_commands(self) -> list[SlashCommand]:
|
|
65
|
+
"""Return all active executable commands sorted by name."""
|
|
66
|
+
return sorted(
|
|
67
|
+
(c for c in self._commands.values() if self.is_executable(c)),
|
|
68
|
+
key=lambda c: c.name,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
def help_commands(self) -> list[SlashCommand]:
|
|
72
|
+
"""Return commands to display in /help (including upcoming only in dev builds)."""
|
|
73
|
+
dev = is_dev_build(self.feature_flags)
|
|
74
|
+
items = [
|
|
75
|
+
c for c in self._commands.values() if self.is_executable(c) or (dev and c.upcoming)
|
|
76
|
+
]
|
|
77
|
+
return sorted(items, key=lambda c: c.name)
|
|
78
|
+
|
|
79
|
+
def filter_prefix(self, prefix: str) -> list[SlashCommand]:
|
|
80
|
+
"""Filter executable commands matching a `/` prefix."""
|
|
81
|
+
needle = prefix.strip().lower()
|
|
82
|
+
if not needle.startswith("/"):
|
|
83
|
+
needle = "/" + needle
|
|
84
|
+
results: list[SlashCommand] = []
|
|
85
|
+
for cmd in self.executable_commands():
|
|
86
|
+
if cmd.name.startswith(needle) or any(a.startswith(needle) for a in cmd.aliases):
|
|
87
|
+
results.append(cmd)
|
|
88
|
+
return results
|
|
89
|
+
|
|
90
|
+
def resolve(self, name: str) -> SlashCommand | None:
|
|
91
|
+
"""Find an executable command by exact name or alias."""
|
|
92
|
+
needle = name.strip().lower()
|
|
93
|
+
for cmd in self.executable_commands():
|
|
94
|
+
if cmd.name == needle or needle in cmd.aliases:
|
|
95
|
+
return cmd
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class ValkyrieCompleter(Completer):
|
|
100
|
+
"""Autocomplete `/` slash commands, `/model` targets/providers, and `@` workspace paths."""
|
|
101
|
+
|
|
102
|
+
def __init__(
|
|
103
|
+
self,
|
|
104
|
+
registry: SlashCommandRegistry,
|
|
105
|
+
workspace_root: Path,
|
|
106
|
+
model_registry: ModelRegistry | None = None,
|
|
107
|
+
) -> None:
|
|
108
|
+
self.registry = registry
|
|
109
|
+
self.workspace_root = workspace_root
|
|
110
|
+
self.model_registry = model_registry
|
|
111
|
+
self._cached_files: list[str] | None = None
|
|
112
|
+
|
|
113
|
+
def _get_files(self) -> list[str]:
|
|
114
|
+
if self._cached_files is None:
|
|
115
|
+
self._cached_files = list_workspace_files(self.workspace_root)
|
|
116
|
+
return self._cached_files
|
|
117
|
+
|
|
118
|
+
def refresh_files(self) -> None:
|
|
119
|
+
"""Invalidate cached workspace file list."""
|
|
120
|
+
self._cached_files = None
|
|
121
|
+
|
|
122
|
+
def _model_completions(self, text: str) -> Iterable[Completion]:
|
|
123
|
+
parts = text.split(" ")
|
|
124
|
+
last = parts[-1].lower()
|
|
125
|
+
subcmds = [
|
|
126
|
+
("list", "list models (optionally filter by provider)"),
|
|
127
|
+
("pick", "interactive numbered model selector"),
|
|
128
|
+
("refresh", "fetch live catalogs from providers"),
|
|
129
|
+
("use", "switch to a model by ID"),
|
|
130
|
+
]
|
|
131
|
+
if len(parts) == 2:
|
|
132
|
+
for sub, desc in subcmds:
|
|
133
|
+
if not last or sub.startswith(last):
|
|
134
|
+
yield Completion(
|
|
135
|
+
sub,
|
|
136
|
+
start_position=-len(last),
|
|
137
|
+
display=sub,
|
|
138
|
+
display_meta=desc,
|
|
139
|
+
)
|
|
140
|
+
for pkey, pobj in PROVIDERS.items():
|
|
141
|
+
if not last or pkey.startswith(last):
|
|
142
|
+
yield Completion(
|
|
143
|
+
pkey,
|
|
144
|
+
start_position=-len(last),
|
|
145
|
+
display=pkey,
|
|
146
|
+
display_meta=f"filter {pobj.name} models",
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
if self.model_registry is None:
|
|
150
|
+
return
|
|
151
|
+
|
|
152
|
+
# Suggest active models matching typed fragment (after /model or /model list/use/pick)
|
|
153
|
+
provider_hint = (
|
|
154
|
+
parts[1].lower()
|
|
155
|
+
if len(parts) >= 3 and parts[1].lower() in PROVIDERS
|
|
156
|
+
else None
|
|
157
|
+
)
|
|
158
|
+
candidates = self.model_registry.list_models(provider=provider_hint)
|
|
159
|
+
for m in candidates:
|
|
160
|
+
if not m.is_active:
|
|
161
|
+
continue
|
|
162
|
+
if not last or last in m.qualified_id.lower():
|
|
163
|
+
ctx = f"{m.context_window // 1000}k" if m.context_window else "?"
|
|
164
|
+
yield Completion(
|
|
165
|
+
m.qualified_id,
|
|
166
|
+
start_position=-len(last),
|
|
167
|
+
display=m.qualified_id,
|
|
168
|
+
display_meta=f"{ctx} ctx",
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
def _account_completions(self, text: str) -> Iterable[Completion]:
|
|
172
|
+
parts = text.split(" ")
|
|
173
|
+
if len(parts) != 2:
|
|
174
|
+
return
|
|
175
|
+
last = parts[1].lower()
|
|
176
|
+
subcmds = [
|
|
177
|
+
("status", "show active signed-in account details"),
|
|
178
|
+
("switch", "switch to another Google account"),
|
|
179
|
+
("delete", "permanently delete account and remote vault"),
|
|
180
|
+
("login", "sign in with Google via browser"),
|
|
181
|
+
("logout", "sign out locally without deleting account"),
|
|
182
|
+
]
|
|
183
|
+
for sub, desc in subcmds:
|
|
184
|
+
if not last or sub.startswith(last):
|
|
185
|
+
yield Completion(
|
|
186
|
+
sub,
|
|
187
|
+
start_position=-len(last),
|
|
188
|
+
display=sub,
|
|
189
|
+
display_meta=desc,
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
def get_completions(
|
|
193
|
+
self, document: Document, complete_event: object
|
|
194
|
+
) -> Iterable[Completion]:
|
|
195
|
+
text = document.text_before_cursor
|
|
196
|
+
|
|
197
|
+
# 1. Slash command completion when line starts with / and no space yet
|
|
198
|
+
if text.startswith("/") and " " not in text:
|
|
199
|
+
matches = self.registry.filter_prefix(text)
|
|
200
|
+
for cmd in matches:
|
|
201
|
+
yield Completion(
|
|
202
|
+
cmd.name,
|
|
203
|
+
start_position=-len(text),
|
|
204
|
+
display=cmd.name,
|
|
205
|
+
display_meta=cmd.description,
|
|
206
|
+
)
|
|
207
|
+
return
|
|
208
|
+
|
|
209
|
+
# 2. /model (or /m) arguments completion (providers, subcommands, and active models)
|
|
210
|
+
if text.lower().startswith(("/model ", "/m ")):
|
|
211
|
+
yield from self._model_completions(text)
|
|
212
|
+
return
|
|
213
|
+
|
|
214
|
+
# 3. /account (or /acc, /auth) subcommands completion
|
|
215
|
+
if text.lower().startswith(("/account ", "/acc ", "/auth ")):
|
|
216
|
+
yield from self._account_completions(text)
|
|
217
|
+
return
|
|
218
|
+
|
|
219
|
+
# 3. @path completion anywhere in the prompt
|
|
220
|
+
word = document.get_word_before_cursor(WORD=True)
|
|
221
|
+
if word.startswith("@"):
|
|
222
|
+
needle = word[1:].lower()
|
|
223
|
+
for rel_path in self._get_files():
|
|
224
|
+
if needle in rel_path.lower():
|
|
225
|
+
yield Completion(
|
|
226
|
+
f"@{rel_path}",
|
|
227
|
+
start_position=-len(word),
|
|
228
|
+
display=f"@{rel_path}",
|
|
229
|
+
)
|