HumboldtJoker commited on
Commit
d4175a4
·
verified ·
1 Parent(s): f2913c2

Clean up nested duplicate: v2/v2/engine/model_client.py

Browse files
Files changed (1) hide show
  1. v2/v2/engine/model_client.py +0 -151
v2/v2/engine/model_client.py DELETED
@@ -1,151 +0,0 @@
1
- """Model access for Rivet.
2
-
3
- Two backends behind one interface:
4
-
5
- OllamaClient — HTTP to an Ollama server. Knowledge packs are
6
- injected as a system-context block (Ollama's API
7
- exposes no KV-cache handle, so this is the honest
8
- limit of that transport).
9
- TransformersClient — local HF transformers. Knowledge packs are
10
- injected as precomputed KV cache blocks via
11
- pharos.kv_injector — true zero-prompt-token
12
- injection, the real Pharos pipeline.
13
-
14
- Which backend runs is a config decision (`model.backend`), not a code
15
- change. Chips only ever see `ModelClient.generate()`.
16
- """
17
-
18
- import json
19
- import urllib.error
20
- import urllib.request
21
- from dataclasses import dataclass
22
-
23
-
24
- @dataclass
25
- class ModelReply:
26
- text: str
27
- ok: bool
28
- backend: str
29
- knowledge_injected: str = "none" # none | system_prompt | kv_cache
30
- error: str = ""
31
-
32
-
33
- class ModelClient:
34
- """Interface. Use OllamaClient or TransformersClient."""
35
-
36
- def generate(self, prompt: str, system: str = "", knowledge: str = "",
37
- max_tokens: int = 1024) -> ModelReply:
38
- raise NotImplementedError
39
-
40
-
41
- class OllamaClient(ModelClient):
42
- def __init__(self, base_url: str = "http://localhost:11434",
43
- model: str = "qwen2.5-coder:32b",
44
- temperature: float = 0.3, num_ctx: int = 32768,
45
- timeout: int = 180):
46
- self.base_url = base_url.rstrip("/")
47
- self.model = model
48
- self.temperature = temperature
49
- self.num_ctx = num_ctx
50
- self.timeout = timeout
51
-
52
- def generate(self, prompt: str, system: str = "", knowledge: str = "",
53
- max_tokens: int = 1024) -> ModelReply:
54
- full_system = system
55
- injected = "none"
56
- if knowledge:
57
- full_system = (
58
- f"{system}\n\n# INJECTED KNOWLEDGE (Pharos)\n"
59
- f"You have access to the following knowledge:\n{knowledge}"
60
- ).strip()
61
- injected = "system_prompt"
62
-
63
- payload = {
64
- "model": self.model,
65
- "prompt": prompt,
66
- "system": full_system,
67
- "stream": False,
68
- "options": {
69
- "temperature": self.temperature,
70
- "num_ctx": self.num_ctx,
71
- "num_predict": max_tokens,
72
- },
73
- }
74
- req = urllib.request.Request(
75
- f"{self.base_url}/api/generate",
76
- data=json.dumps(payload).encode(),
77
- headers={"Content-Type": "application/json"},
78
- )
79
- try:
80
- with urllib.request.urlopen(req, timeout=self.timeout) as resp:
81
- data = json.loads(resp.read())
82
- return ModelReply(
83
- text=data.get("response", ""), ok=True,
84
- backend=f"ollama:{self.model}", knowledge_injected=injected,
85
- )
86
- except (urllib.error.URLError, TimeoutError, OSError) as exc:
87
- return ModelReply(
88
- text="", ok=False, backend=f"ollama:{self.model}",
89
- error=f"Ollama unreachable at {self.base_url}: {exc}",
90
- )
91
-
92
-
93
- class TransformersClient(ModelClient):
94
- """Local transformers backend with real KV-cache pack injection.
95
-
96
- Lazy-loads torch/transformers on first generate() so importing this
97
- module never requires them. Pack KV blocks come from
98
- pharos.kv_injector.KVPackEncoder (precomputed once per pack).
99
- """
100
-
101
- def __init__(self, model_path: str, device: str = "auto",
102
- pack_cache_dir: str = ""):
103
- self.model_path = model_path
104
- self.device = device
105
- self.pack_cache_dir = pack_cache_dir
106
- self._injector = None
107
-
108
- def _ensure_loaded(self):
109
- if self._injector is None:
110
- from pharos.kv_injector import KVInjector
111
- self._injector = KVInjector(
112
- self.model_path, device=self.device,
113
- cache_dir=self.pack_cache_dir,
114
- )
115
- return self._injector
116
-
117
- def generate(self, prompt: str, system: str = "", knowledge: str = "",
118
- max_tokens: int = 1024) -> ModelReply:
119
- try:
120
- injector = self._ensure_loaded()
121
- except ImportError as exc:
122
- return ModelReply(
123
- text="", ok=False, backend="transformers",
124
- error=f"torch/transformers not available: {exc}",
125
- )
126
- text = injector.generate(
127
- prompt, system=system, knowledge=knowledge, max_tokens=max_tokens,
128
- )
129
- return ModelReply(
130
- text=text, ok=True,
131
- backend=f"transformers:{self.model_path}",
132
- knowledge_injected="kv_cache" if knowledge else "none",
133
- )
134
-
135
-
136
- def build_client(cfg: dict) -> ModelClient:
137
- """Construct the configured backend from the `model:` config section."""
138
- backend = cfg.get("backend", "ollama")
139
- if backend == "transformers":
140
- return TransformersClient(
141
- model_path=cfg.get("model_path", cfg.get("name", "")),
142
- device=cfg.get("device", "auto"),
143
- pack_cache_dir=cfg.get("pack_cache_dir", ""),
144
- )
145
- return OllamaClient(
146
- base_url=cfg.get("base_url", "http://localhost:11434"),
147
- model=cfg.get("name", "qwen2.5-coder:32b"),
148
- temperature=cfg.get("temperature", 0.3),
149
- num_ctx=cfg.get("num_ctx", 32768),
150
- timeout=cfg.get("timeout_seconds", 180),
151
- )