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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
"""
SLM-Native Backends β€” First-class support for Small Language Models.

Purpose Agent is the world's first agentic framework designed natively for SLMs.
These backends handle the unique challenges of small models:
  - Grammar-constrained JSON output (SLMs can't reliably produce JSON from prompts alone)
  - Prompt compression for small context windows (8K-32K)
  - Adaptive prompting (shorter system prompts, schema-first format)
  - Token budget management

Supported backends:
  - OllamaBackend: Local serving via Ollama (CPU/GPU, any GGUF model)
  - LlamaCppBackend: Direct llama-cpp-python (CPU/Apple Silicon, GGUF)
  - TransformersBackend: HuggingFace transformers (GPU, native weights)

All backends implement the same LLMBackend interface β€” swap freely.
"""

from __future__ import annotations

import json
import logging
import os
import re
from typing import Any, AsyncIterator, Iterator

from purpose_agent.llm_backend import ChatMessage, LLMBackend

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# SLM Prompt Compressor β€” reduces prompt size for small context windows
# ---------------------------------------------------------------------------

class SLMPromptCompressor:
    """
    Compresses prompts for small context windows without losing critical info.
    
    Strategies (from TinyAgent arxiv:2409.00608 + LLMLingua-2 arxiv:2403.12968):
    1. Schema-first: Move JSON schema to top, compress descriptions
    2. History truncation: Summarize old steps, keep recent ones verbatim
    3. Example reduction: Fewer few-shot examples for SLMs
    4. Whitespace stripping: Remove unnecessary formatting
    
    No external dependencies β€” pure Python compression.
    For better compression, install llmlingua: pip install llmlingua
    """

    def __init__(self, max_tokens: int = 4096, aggressive: bool = False):
        self.max_tokens = max_tokens
        self.aggressive = aggressive

    def compress(self, text: str, budget: int | None = None) -> str:
        """Compress text to fit within token budget."""
        budget = budget or self.max_tokens
        # Rough estimate: 1 token β‰ˆ 4 chars
        char_budget = budget * 4

        if len(text) <= char_budget:
            return text

        compressed = text
        # Stage 1: Strip excessive whitespace
        compressed = re.sub(r'\n{3,}', '\n\n', compressed)
        compressed = re.sub(r'[ \t]{2,}', ' ', compressed)
        compressed = re.sub(r'^\s+', '', compressed, flags=re.MULTILINE)

        if len(compressed) <= char_budget:
            return compressed

        # Stage 2: Shorten verbose sections
        if self.aggressive:
            # Remove markdown formatting
            compressed = re.sub(r'\*\*([^*]+)\*\*', r'\1', compressed)
            compressed = re.sub(r'#{1,3}\s+', '', compressed)
            # Shorten common verbose phrases
            replacements = {
                "You MUST respond with": "Respond with",
                "Based on the current state and your goal, ": "",
                "Respond in this exact JSON format:": "JSON format:",
                "Step-by-step justification": "Justification",
                "Specific observable state changes": "State changes",
            }
            for old, new in replacements.items():
                compressed = compressed.replace(old, new)

        if len(compressed) <= char_budget:
            return compressed

        # Stage 3: Truncate from middle (keep start + end)
        keep_start = char_budget * 2 // 3
        keep_end = char_budget // 3
        compressed = compressed[:keep_start] + "\n...[truncated]...\n" + compressed[-keep_end:]

        return compressed

    def compress_messages(
        self, messages: list[ChatMessage], budget: int | None = None
    ) -> list[ChatMessage]:
        """Compress a message list to fit within token budget."""
        budget = budget or self.max_tokens
        total_chars = sum(len(m.content) for m in messages)
        char_budget = budget * 4

        if total_chars <= char_budget:
            return messages

        result = []
        # Always keep system prompt (compress it), always keep last user message
        for i, msg in enumerate(messages):
            if msg.role == "system":
                result.append(ChatMessage(
                    role="system",
                    content=self.compress(msg.content, budget=budget // 3),
                ))
            elif i == len(messages) - 1:
                # Last message β€” keep more of it
                result.append(ChatMessage(
                    role=msg.role,
                    content=self.compress(msg.content, budget=budget // 2),
                ))
            else:
                result.append(ChatMessage(
                    role=msg.role,
                    content=self.compress(msg.content, budget=budget // 4),
                ))
        return result


# ---------------------------------------------------------------------------
# Ollama Backend β€” Best for local SLMs
# ---------------------------------------------------------------------------

class OllamaBackend(LLMBackend):
    """
    Local model serving via Ollama with grammar-constrained JSON output.
    
    Ollama's grammar engine (via llama.cpp) forces valid JSON output from
    ANY model β€” even tiny ones that can't produce reliable JSON from prompts.
    This is the key advantage for SLM agent use.
    
    Setup:
        1. Install Ollama: https://ollama.ai
        2. Pull a model: ollama pull qwen3:1.7b
        3. Use this backend:
        
    Example:
        backend = OllamaBackend(model="qwen3:1.7b")  # 1.7B params, runs on CPU
        backend = OllamaBackend(model="llama3.2:1b")  # 1B params, ultra-light
        backend = OllamaBackend(model="phi4-mini")     # 3.8B, best tool-use
        backend = OllamaBackend(model="smollm2:1.7b")  # HF native SLM
        
    Also works with large models:
        backend = OllamaBackend(model="qwen3:32b")     # Full LLM
    """

    def __init__(
        self,
        model: str = "qwen3:1.7b",
        host: str = "http://localhost:11434",
        context_window: int = 8192,
        compress_prompts: bool = True,
        num_ctx: int | None = None,
    ):
        self.model = model
        self.host = host
        self.context_window = context_window
        self.compress_prompts = compress_prompts
        self.num_ctx = num_ctx or context_window
        self.compressor = SLMPromptCompressor(
            max_tokens=context_window, aggressive=(context_window <= 8192)
        )
        self._token_count = 0

    def _get_client(self):
        """Lazy import ollama client."""
        try:
            from ollama import Client
            return Client(host=self.host)
        except ImportError:
            raise ImportError(
                "Ollama client not installed. Run: pip install ollama\n"
                "Also install Ollama server: https://ollama.ai"
            )

    def generate(
        self,
        messages: list[ChatMessage],
        temperature: float = 0.7,
        max_tokens: int = 2048,
        stop: list[str] | None = None,
    ) -> str:
        client = self._get_client()

        if self.compress_prompts:
            messages = self.compressor.compress_messages(messages, self.context_window)

        msg_dicts = [{"role": m.role, "content": m.content} for m in messages]

        response = client.chat(
            model=self.model,
            messages=msg_dicts,
            options={
                "temperature": temperature,
                "num_predict": max_tokens,
                "num_ctx": self.num_ctx,
                "stop": stop or [],
            },
        )

        content = self._strip_thinking(response.message.content or "")
        self._token_count += response.get("eval_count", 0) + response.get("prompt_eval_count", 0)
        return content

    def generate_structured(
        self,
        messages: list[ChatMessage],
        schema: dict[str, Any],
        temperature: float = 0.3,
        max_tokens: int = 1024,
    ) -> dict[str, Any]:
        """
        Grammar-constrained JSON generation.
        
        Ollama uses llama.cpp's grammar engine to FORCE valid JSON output
        matching the schema. This works even with tiny models that can't
        produce valid JSON from prompts alone.
        """
        client = self._get_client()

        if self.compress_prompts:
            messages = self.compressor.compress_messages(messages, self.context_window)

        msg_dicts = [{"role": m.role, "content": m.content} for m in messages]

        response = client.chat(
            model=self.model,
            messages=msg_dicts,
            format=schema,  # Grammar-constrained output!
            options={
                "temperature": temperature,
                "num_predict": max_tokens,
                "num_ctx": self.num_ctx,
            },
        )

        content = response.message.content or "{}"
        self._token_count += response.get("eval_count", 0) + response.get("prompt_eval_count", 0)
        return json.loads(content)

    def generate_stream(
        self,
        messages: list[ChatMessage],
        temperature: float = 0.7,
        max_tokens: int = 2048,
    ) -> Iterator[str]:
        """Streaming generation β€” yields tokens as they're produced."""
        client = self._get_client()

        if self.compress_prompts:
            messages = self.compressor.compress_messages(messages, self.context_window)

        msg_dicts = [{"role": m.role, "content": m.content} for m in messages]

        stream = client.chat(
            model=self.model,
            messages=msg_dicts,
            stream=True,
            options={
                "temperature": temperature,
                "num_predict": max_tokens,
                "num_ctx": self.num_ctx,
            },
        )

        for chunk in stream:
            token = chunk.get("message", {}).get("content", "")
            if token:
                yield token

    @property
    def total_tokens(self) -> int:
        return self._token_count


# ---------------------------------------------------------------------------
# LlamaCpp Backend β€” Direct CPU/Apple Silicon/GGUF
# ---------------------------------------------------------------------------

class LlamaCppBackend(LLMBackend):
    """
    Direct llama-cpp-python backend for GGUF models.
    
    Best for: CPU inference, Apple Silicon, edge deployment, offline use.
    
    Example:
        backend = LlamaCppBackend(model_path="./qwen2.5-1.5b-instruct-q4_k_m.gguf")
        backend = LlamaCppBackend(
            model_path="./phi-4-mini-q4.gguf",
            n_ctx=4096,
            n_gpu_layers=35,  # Offload to GPU
        )
    """

    def __init__(
        self,
        model_path: str,
        n_ctx: int = 4096,
        n_gpu_layers: int = 0,
        verbose: bool = False,
    ):
        try:
            from llama_cpp import Llama
        except ImportError:
            raise ImportError("llama-cpp-python not installed. Run: pip install llama-cpp-python")

        self.model_path = model_path
        self.llm = Llama(
            model_path=model_path,
            n_ctx=n_ctx,
            n_gpu_layers=n_gpu_layers,
            verbose=verbose,
        )
        self.compressor = SLMPromptCompressor(max_tokens=n_ctx, aggressive=True)
        self._token_count = 0

    def generate(
        self,
        messages: list[ChatMessage],
        temperature: float = 0.7,
        max_tokens: int = 2048,
        stop: list[str] | None = None,
    ) -> str:
        messages = self.compressor.compress_messages(messages)
        msg_dicts = [{"role": m.role, "content": m.content} for m in messages]

        response = self.llm.create_chat_completion(
            messages=msg_dicts,
            temperature=temperature,
            max_tokens=max_tokens,
            stop=stop,
        )

        content = response["choices"][0]["message"]["content"] or ""
        usage = response.get("usage", {})
        self._token_count += usage.get("total_tokens", 0)
        return content

    def generate_structured(
        self,
        messages: list[ChatMessage],
        schema: dict[str, Any],
        temperature: float = 0.3,
        max_tokens: int = 1024,
    ) -> dict[str, Any]:
        """Grammar-constrained JSON via llama.cpp GBNF grammar."""
        from llama_cpp import LlamaGrammar

        grammar = LlamaGrammar.from_json_schema(json.dumps(schema))
        messages = self.compressor.compress_messages(messages)
        msg_dicts = [{"role": m.role, "content": m.content} for m in messages]

        response = self.llm.create_chat_completion(
            messages=msg_dicts,
            temperature=temperature,
            max_tokens=max_tokens,
            grammar=grammar,
        )

        content = response["choices"][0]["message"]["content"] or "{}"
        usage = response.get("usage", {})
        self._token_count += usage.get("total_tokens", 0)
        return json.loads(content)

    def generate_stream(
        self,
        messages: list[ChatMessage],
        temperature: float = 0.7,
        max_tokens: int = 2048,
    ) -> Iterator[str]:
        messages = self.compressor.compress_messages(messages)
        msg_dicts = [{"role": m.role, "content": m.content} for m in messages]

        stream = self.llm.create_chat_completion(
            messages=msg_dicts,
            temperature=temperature,
            max_tokens=max_tokens,
            stream=True,
        )

        for chunk in stream:
            delta = chunk.get("choices", [{}])[0].get("delta", {})
            token = delta.get("content", "")
            if token:
                yield token

    @property
    def total_tokens(self) -> int:
        return self._token_count


# ---------------------------------------------------------------------------
# Model Registry β€” Easy model selection for SLMs
# ---------------------------------------------------------------------------

# Recommended SLMs for agent tasks, ranked by capability
SLM_REGISTRY = {
    # Model ID β†’ (Ollama name, context window, description)
    "phi-4-mini": ("phi4-mini", 16384, "3.8B, best schema compliance, Microsoft"),
    "qwen3-1.7b": ("qwen3:1.7b", 32768, "1.7B, strong function calling, 32K context"),
    "qwen3-0.6b": ("qwen3:0.6b", 32768, "0.6B, ultra-light, 32K context"),
    "qwen2.5-1.5b": ("qwen2.5:1.5b", 32768, "1.5B, proven tool-use"),
    "llama-3.2-3b": ("llama3.2:3b", 131072, "3B, 128K context, Meta"),
    "llama-3.2-1b": ("llama3.2:1b", 131072, "1B, smallest Llama, 128K context"),
    "smollm2-1.7b": ("smollm2:1.7b", 8192, "1.7B, HF native, 8K context (tight!)"),
    "gemma-3-1b": ("gemma3:1b", 32768, "1B, Google, multimodal capable"),
}


def create_slm_backend(
    model_key: str = "qwen3-1.7b",
    host: str = "http://localhost:11434",
) -> OllamaBackend:
    """
    Create an SLM backend from the registry.
    
    Usage:
        backend = create_slm_backend("phi-4-mini")      # Best overall
        backend = create_slm_backend("qwen3-0.6b")      # Ultra-light
        backend = create_slm_backend("llama-3.2-1b")    # Smallest Llama
    """
    if model_key not in SLM_REGISTRY:
        available = ", ".join(SLM_REGISTRY.keys())
        raise ValueError(f"Unknown SLM '{model_key}'. Available: {available}")

    ollama_name, ctx_window, desc = SLM_REGISTRY[model_key]
    logger.info(f"Creating SLM backend: {model_key} ({desc})")

    return OllamaBackend(
        model=ollama_name,
        host=host,
        context_window=ctx_window,
        compress_prompts=True,
    )