snapkitty
compilers
c
python
nasm
File size: 9,942 Bytes
9abace2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
"""

RAG Pipeline

Part of SOVEREIGN PYTHON LLM ENGINE



Complete Retrieval-Augmented Generation pipeline.

"""

from typing import AsyncIterator
from dataclasses import dataclass
from datetime import datetime

from ..models.entities import Message, MessageRole, RetrievalRequest, RetrievalResult
from ..core.protocols import Model, VectorStore
from ..tools.embeddings.encode import EmbeddingsTool
from .parallel import ParallelRetriever
from ..core.evidence import WORMLedger


@dataclass
class RAGConfig:
    """Configuration for RAG pipeline"""
    top_k: int = 5
    score_threshold: float = 0.7
    use_reranking: bool = True
    context_window: int = 8000  # Max tokens for context
    log_to_worm: bool = True


class RAGPipeline:
    """

    Complete RAG (Retrieval-Augmented Generation) pipeline.



    Steps:

    1. Embed query

    2. Retrieve top-K documents

    3. Optionally rerank

    4. Format context

    5. Generate answer with LLM

    """

    def __init__(

        self,

        model: Model,

        retriever: ParallelRetriever,

        embeddings: EmbeddingsTool,

        worm_ledger: WORMLedger | None = None,

        config: RAGConfig | None = None

    ):
        """

        Initialize RAG pipeline.



        Args:

            model: LLM for generation

            retriever: Parallel retriever

            embeddings: Embeddings tool

            worm_ledger: Optional WORM ledger

            config: Configuration

        """
        self.model = model
        self.retriever = retriever
        self.embeddings = embeddings
        self.worm_ledger = worm_ledger
        self.config = config or RAGConfig()

    async def query(

        self,

        question: str,

        filters: dict | None = None,

        stream: bool = False

    ) -> str | AsyncIterator[str]:
        """

        Query the RAG system.



        Args:

            question: User question

            filters: Optional metadata filters

            stream: Whether to stream response



        Returns:

            Answer string (or stream of chunks)

        """
        # 1. Retrieve relevant documents
        retrieval_request = RetrievalRequest(
            query=question,
            limit=self.config.top_k,
            score_threshold=self.config.score_threshold,
            filters=filters
        )

        results = await self.retriever.retrieve(retrieval_request)

        # 2. Format context
        context = self._format_context(results)

        # 3. Build prompt
        prompt = self._build_prompt(question, context)

        # 4. Generate answer
        messages = [
            {"role": "system", "content": "You are a helpful assistant that answers questions based on provided context."},
            {"role": "user", "content": prompt}
        ]

        if stream:
            # Streaming not implemented in base Model protocol yet
            # Return async generator wrapper
            answer = await self.model.generate(
                messages=messages,
                temperature=0.3,
                max_tokens=2048
            )

            # Log to WORM
            if self.worm_ledger and self.config.log_to_worm:
                await self._log_to_worm(question, results, answer)

            async def stream_wrapper():
                yield answer

            return stream_wrapper()
        else:
            answer = await self.model.generate(
                messages=messages,
                temperature=0.3,
                max_tokens=2048
            )

            # Log to WORM
            if self.worm_ledger and self.config.log_to_worm:
                await self._log_to_worm(question, results, answer)

            return answer

    async def query_with_citations(

        self,

        question: str,

        filters: dict | None = None

    ) -> tuple[str, list[RetrievalResult]]:
        """

        Query with source citations.



        Args:

            question: User question

            filters: Optional filters



        Returns:

            (answer, source_documents) tuple

        """
        # Retrieve
        retrieval_request = RetrievalRequest(
            query=question,
            limit=self.config.top_k,
            score_threshold=self.config.score_threshold,
            filters=filters
        )

        results = await self.retriever.retrieve(retrieval_request)

        # Format context
        context = self._format_context(results)

        # Build prompt with citation instruction
        prompt = f"""Answer the question based on the provided context.

Cite sources using [Source N] notation.



Context:

{context}



Question: {question}



Answer:"""

        # Generate
        messages = [
            {"role": "system", "content": "You are a helpful assistant that answers questions and cites sources."},
            {"role": "user", "content": prompt}
        ]

        answer = await self.model.generate(
            messages=messages,
            temperature=0.3,
            max_tokens=2048
        )

        # Log to WORM
        if self.worm_ledger and self.config.log_to_worm:
            await self._log_to_worm(question, results, answer)

        return answer, results

    def _format_context(self, results: list[RetrievalResult]) -> str:
        """

        Format retrieval results into context string.



        Args:

            results: Retrieved documents



        Returns:

            Formatted context

        """
        if not results:
            return "No relevant documents found."

        context_parts = []

        for i, result in enumerate(results, 1):
            source_info = ""
            if result.metadata:
                source_info = f" ({result.metadata.get('source', 'Unknown')})"

            context_parts.append(
                f"[Source {i}]{source_info}\n{result.content}\n"
            )

        return "\n".join(context_parts)

    def _build_prompt(self, question: str, context: str) -> str:
        """

        Build RAG prompt.



        Args:

            question: User question

            context: Retrieved context



        Returns:

            Formatted prompt

        """
        return f"""Answer the question based on the following context.

If the context doesn't contain enough information, say so.



Context:

{context}



Question: {question}



Answer:"""

    async def _log_to_worm(

        self,

        question: str,

        results: list[RetrievalResult],

        answer: str

    ) -> None:
        """Log RAG query to WORM ledger"""
        if not self.worm_ledger:
            return

        await self.worm_ledger.append({
            "event": "rag_query",
            "question": question,
            "retrieved_docs": len(results),
            "top_score": results[0].score if results else None,
            "answer_length": len(answer),
            "timestamp": datetime.utcnow().isoformat()
        })


class ConversationalRAG:
    """

    RAG with conversation history.



    Maintains context across multiple turns.

    """

    def __init__(

        self,

        rag_pipeline: RAGPipeline,

        max_history: int = 10

    ):
        """

        Initialize conversational RAG.



        Args:

            rag_pipeline: Base RAG pipeline

            max_history: Maximum conversation turns to keep

        """
        self.rag = rag_pipeline
        self.max_history = max_history
        self.conversation_history: list[Message] = []

    async def query(

        self,

        question: str,

        filters: dict | None = None

    ) -> str:
        """

        Query with conversation context.



        Args:

            question: User question

            filters: Optional filters



        Returns:

            Answer

        """
        # Add user message to history
        self.conversation_history.append(
            Message(
                role=MessageRole.USER,
                content=question,
                created_at=datetime.utcnow()
            )
        )

        # Retrieve using current question
        retrieval_request = RetrievalRequest(
            query=question,
            limit=self.rag.config.top_k,
            score_threshold=self.rag.config.score_threshold,
            filters=filters
        )

        results = await self.rag.retriever.retrieve(retrieval_request)

        # Format context
        context = self.rag._format_context(results)

        # Build messages with history
        messages = [
            {"role": "system", "content": "You are a helpful assistant. Use the provided context and conversation history to answer questions."}
        ]

        # Add conversation history (limited)
        history_messages = self.conversation_history[-(self.max_history * 2):]
        for msg in history_messages:
            messages.append({
                "role": msg.role.value,
                "content": msg.content
            })

        # Add current context
        messages.append({
            "role": "user",
            "content": f"""Context:

{context}



Question: {question}



Answer:"""
        })

        # Generate
        answer = await self.rag.model.generate(
            messages=messages,
            temperature=0.3,
            max_tokens=2048
        )

        # Add assistant message to history
        self.conversation_history.append(
            Message(
                role=MessageRole.ASSISTANT,
                content=answer,
                created_at=datetime.utcnow()
            )
        )

        return answer

    def clear_history(self) -> None:
        """Clear conversation history"""
        self.conversation_history.clear()