ragit 0.7__tar.gz → 0.7.1__tar.gz

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.
ragit-0.7.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
ragit-0.7.1/PKG-INFO ADDED
@@ -0,0 +1,476 @@
1
+ Metadata-Version: 2.4
2
+ Name: ragit
3
+ Version: 0.7.1
4
+ Summary: Automatic RAG Pattern Optimization Engine
5
+ Author: RODMENA LIMITED
6
+ Maintainer-email: RODMENA LIMITED <info@rodmena.co.uk>
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/rodmena-limited/ragit
9
+ Project-URL: Repository, https://github.com/rodmena-limited/ragit
10
+ Project-URL: Issues, https://github.com/rodmena-limited/ragit/issues
11
+ Keywords: AI,RAG,LLM,GenAI,Optimization,Ollama
12
+ Classifier: Development Status :: 2 - Pre-Alpha
13
+ Classifier: Natural Language :: English
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Operating System :: MacOS :: MacOS X
18
+ Classifier: Operating System :: POSIX :: Linux
19
+ Requires-Python: <3.14,>=3.12
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: requests>=2.31.0
23
+ Requires-Dist: numpy>=1.26.0
24
+ Requires-Dist: pandas>=2.2.0
25
+ Requires-Dist: pydantic>=2.0.0
26
+ Requires-Dist: python-dotenv>=1.0.0
27
+ Requires-Dist: scikit-learn>=1.5.0
28
+ Requires-Dist: tqdm>=4.66.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: ragit[test]; extra == "dev"
31
+ Requires-Dist: pytest; extra == "dev"
32
+ Requires-Dist: pytest-cov; extra == "dev"
33
+ Requires-Dist: issuedb[web]; extra == "dev"
34
+ Requires-Dist: ruff; extra == "dev"
35
+ Requires-Dist: mypy; extra == "dev"
36
+ Provides-Extra: test
37
+ Requires-Dist: pytest; extra == "test"
38
+ Requires-Dist: pytest-cov; extra == "test"
39
+ Requires-Dist: pytest-mock; extra == "test"
40
+ Dynamic: license-file
41
+
42
+ # ragit
43
+
44
+ A Python toolkit for building Retrieval-Augmented Generation (RAG) applications. Ragit provides document loading, chunking, vector search, and LLM integration out of the box, allowing you to build document Q&A systems and code generators with minimal boilerplate.
45
+
46
+ ## Table of Contents
47
+
48
+ 1. [Installation](#installation)
49
+ 2. [Configuration](#configuration)
50
+ 3. [Tutorial: Using Ragit](#tutorial-using-ragit)
51
+ - [Loading Documents](#loading-documents)
52
+ - [The RAGAssistant Class](#the-ragassistant-class)
53
+ - [Asking Questions](#asking-questions)
54
+ - [Generating Code](#generating-code)
55
+ - [Custom Retrieval](#custom-retrieval)
56
+ 4. [Tutorial: Platform Integration](#tutorial-platform-integration)
57
+ - [Flask Integration](#flask-integration)
58
+ - [FastAPI Integration](#fastapi-integration)
59
+ - [Command-Line Tools](#command-line-tools)
60
+ - [Batch Processing](#batch-processing)
61
+ 5. [Advanced: Hyperparameter Optimization](#advanced-hyperparameter-optimization)
62
+ 6. [API Reference](#api-reference)
63
+ 7. [License](#license)
64
+
65
+ ## Installation
66
+
67
+ ```bash
68
+ pip install ragit
69
+ ```
70
+
71
+ Ragit requires an Ollama-compatible API for embeddings and LLM inference. You can use:
72
+ - A local Ollama instance (https://ollama.ai)
73
+ - A cloud-hosted Ollama API
74
+ - Any OpenAI-compatible API endpoint
75
+
76
+ ## Configuration
77
+
78
+ Ragit reads configuration from environment variables. Create a `.env` file in your project root:
79
+
80
+ ```bash
81
+ # LLM API (cloud or local)
82
+ OLLAMA_BASE_URL=https://your-ollama-api.com
83
+ OLLAMA_API_KEY=your-api-key
84
+
85
+ # Embedding API (can be different from LLM)
86
+ OLLAMA_EMBEDDING_URL=http://localhost:11434
87
+
88
+ # Default models
89
+ RAGIT_DEFAULT_LLM_MODEL=llama3.1:8b
90
+ RAGIT_DEFAULT_EMBEDDING_MODEL=mxbai-embed-large
91
+ ```
92
+
93
+ A common setup is to use a cloud API for LLM inference (faster, more capable models) while running embeddings locally (lower latency, no API costs for indexing).
94
+
95
+ ## Tutorial: Using Ragit
96
+
97
+ This section covers the core functionality of ragit: loading documents, creating a RAG assistant, and querying your knowledge base.
98
+
99
+ ### Loading Documents
100
+
101
+ Ragit provides several functions for loading and chunking documents.
102
+
103
+ **Loading a single file:**
104
+
105
+ ```python
106
+ from ragit import load_text
107
+
108
+ doc = load_text("docs/api-reference.md")
109
+ print(doc.id) # "api-reference"
110
+ print(doc.content) # Full file contents
111
+ ```
112
+
113
+ **Loading a directory:**
114
+
115
+ ```python
116
+ from ragit import load_directory
117
+
118
+ # Load all markdown files
119
+ docs = load_directory("docs/", "*.md")
120
+
121
+ # Load recursively
122
+ docs = load_directory("docs/", "**/*.md", recursive=True)
123
+
124
+ # Load multiple file types
125
+ txt_docs = load_directory("docs/", "*.txt")
126
+ rst_docs = load_directory("docs/", "*.rst")
127
+ all_docs = txt_docs + rst_docs
128
+ ```
129
+
130
+ **Custom chunking:**
131
+
132
+ For fine-grained control over how documents are split:
133
+
134
+ ```python
135
+ from ragit import chunk_text, chunk_by_separator, chunk_rst_sections
136
+
137
+ # Fixed-size chunks with overlap
138
+ chunks = chunk_text(
139
+ text,
140
+ chunk_size=512, # Characters per chunk
141
+ chunk_overlap=50, # Overlap between chunks
142
+ doc_id="my-doc"
143
+ )
144
+
145
+ # Split by paragraph
146
+ chunks = chunk_by_separator(text, separator="\n\n")
147
+
148
+ # Split RST documents by section headers
149
+ chunks = chunk_rst_sections(rst_content, doc_id="tutorial")
150
+ ```
151
+
152
+ ### The RAGAssistant Class
153
+
154
+ The `RAGAssistant` class is the main interface for RAG operations. It handles document indexing, retrieval, and generation in a single object.
155
+
156
+ ```python
157
+ from ragit import RAGAssistant
158
+
159
+ # Create from a directory
160
+ assistant = RAGAssistant("docs/")
161
+
162
+ # Create from a single file
163
+ assistant = RAGAssistant("docs/tutorial.rst")
164
+
165
+ # Create from Document objects
166
+ from ragit import Document
167
+
168
+ docs = [
169
+ Document(id="intro", content="Introduction to the API..."),
170
+ Document(id="auth", content="Authentication uses JWT tokens..."),
171
+ Document(id="endpoints", content="Available endpoints: /users, /items..."),
172
+ ]
173
+ assistant = RAGAssistant(docs)
174
+ ```
175
+
176
+ **Configuration options:**
177
+
178
+ ```python
179
+ assistant = RAGAssistant(
180
+ "docs/",
181
+ embedding_model="mxbai-embed-large", # Model for embeddings
182
+ llm_model="llama3.1:70b", # Model for generation
183
+ chunk_size=512, # Characters per chunk
184
+ chunk_overlap=50, # Overlap between chunks
185
+ )
186
+ ```
187
+
188
+ ### Asking Questions
189
+
190
+ The `ask()` method retrieves relevant context and generates an answer:
191
+
192
+ ```python
193
+ assistant = RAGAssistant("docs/")
194
+
195
+ answer = assistant.ask("How do I authenticate API requests?")
196
+ print(answer)
197
+ ```
198
+
199
+ **Customizing the query:**
200
+
201
+ ```python
202
+ answer = assistant.ask(
203
+ "How do I authenticate API requests?",
204
+ top_k=5, # Number of chunks to retrieve
205
+ temperature=0.3, # Lower = more focused answers
206
+ system_prompt="You are a technical documentation assistant. "
207
+ "Answer concisely and include code examples."
208
+ )
209
+ ```
210
+
211
+ ### Generating Code
212
+
213
+ The `generate_code()` method is optimized for producing clean, runnable code:
214
+
215
+ ```python
216
+ assistant = RAGAssistant("framework-docs/")
217
+
218
+ code = assistant.generate_code(
219
+ "Create a REST API endpoint for user registration",
220
+ language="python"
221
+ )
222
+ print(code)
223
+ ```
224
+
225
+ The output is clean code without markdown formatting. The assistant uses your documentation as context to generate framework-specific, idiomatic code.
226
+
227
+ ### Custom Retrieval
228
+
229
+ For advanced use cases, you can access the retrieval and generation steps separately:
230
+
231
+ ```python
232
+ assistant = RAGAssistant("docs/")
233
+
234
+ # Step 1: Retrieve relevant chunks
235
+ results = assistant.retrieve("authentication", top_k=5)
236
+ for chunk, score in results:
237
+ print(f"Score: {score:.3f}")
238
+ print(f"Content: {chunk.content[:200]}...")
239
+ print()
240
+
241
+ # Step 2: Get formatted context string
242
+ context = assistant.get_context("authentication", top_k=3)
243
+
244
+ # Step 3: Generate with custom prompt
245
+ prompt = f"""Based on this documentation:
246
+
247
+ {context}
248
+
249
+ Write a Python function that validates a JWT token."""
250
+
251
+ response = assistant.generate(
252
+ prompt,
253
+ system_prompt="You are an expert Python developer.",
254
+ temperature=0.2
255
+ )
256
+ ```
257
+
258
+ ## Tutorial: Platform Integration
259
+
260
+ This section shows how to integrate ragit into web applications and other platforms.
261
+
262
+ ### Flask Integration
263
+
264
+ ```python
265
+ from flask import Flask, request, jsonify
266
+ from ragit import RAGAssistant
267
+
268
+ app = Flask(__name__)
269
+
270
+ # Initialize once at startup
271
+ assistant = RAGAssistant("docs/")
272
+
273
+ @app.route("/ask", methods=["POST"])
274
+ def ask():
275
+ data = request.get_json()
276
+ question = data.get("question", "")
277
+
278
+ if not question:
279
+ return jsonify({"error": "question is required"}), 400
280
+
281
+ answer = assistant.ask(question, top_k=3)
282
+ return jsonify({"answer": answer})
283
+
284
+ @app.route("/search", methods=["GET"])
285
+ def search():
286
+ query = request.args.get("q", "")
287
+ top_k = int(request.args.get("top_k", 5))
288
+
289
+ results = assistant.retrieve(query, top_k=top_k)
290
+ return jsonify({
291
+ "results": [
292
+ {"content": chunk.content, "score": score}
293
+ for chunk, score in results
294
+ ]
295
+ })
296
+
297
+ if __name__ == "__main__":
298
+ app.run(debug=True)
299
+ ```
300
+
301
+ ### FastAPI Integration
302
+
303
+ ```python
304
+ from fastapi import FastAPI, HTTPException
305
+ from pydantic import BaseModel
306
+ from ragit import RAGAssistant
307
+
308
+ app = FastAPI()
309
+
310
+ # Initialize once at startup
311
+ assistant = RAGAssistant("docs/")
312
+
313
+ class Question(BaseModel):
314
+ question: str
315
+ top_k: int = 3
316
+ temperature: float = 0.7
317
+
318
+ class Answer(BaseModel):
319
+ answer: str
320
+
321
+ @app.post("/ask", response_model=Answer)
322
+ async def ask(q: Question):
323
+ if not q.question.strip():
324
+ raise HTTPException(status_code=400, detail="question is required")
325
+
326
+ answer = assistant.ask(
327
+ q.question,
328
+ top_k=q.top_k,
329
+ temperature=q.temperature
330
+ )
331
+ return Answer(answer=answer)
332
+
333
+ @app.get("/search")
334
+ async def search(q: str, top_k: int = 5):
335
+ results = assistant.retrieve(q, top_k=top_k)
336
+ return {
337
+ "results": [
338
+ {"content": chunk.content, "score": score}
339
+ for chunk, score in results
340
+ ]
341
+ }
342
+ ```
343
+
344
+ ### Command-Line Tools
345
+
346
+ Build CLI tools using argparse or click:
347
+
348
+ ```python
349
+ #!/usr/bin/env python3
350
+ import argparse
351
+ from ragit import RAGAssistant
352
+
353
+ def main():
354
+ parser = argparse.ArgumentParser(description="Query documentation")
355
+ parser.add_argument("question", help="Question to ask")
356
+ parser.add_argument("--docs", default="docs/", help="Documentation path")
357
+ parser.add_argument("--top-k", type=int, default=3, help="Context chunks")
358
+ args = parser.parse_args()
359
+
360
+ assistant = RAGAssistant(args.docs)
361
+ answer = assistant.ask(args.question, top_k=args.top_k)
362
+ print(answer)
363
+
364
+ if __name__ == "__main__":
365
+ main()
366
+ ```
367
+
368
+ Usage:
369
+
370
+ ```bash
371
+ python ask.py "How do I configure logging?"
372
+ python ask.py "What are the API rate limits?" --docs api-docs/ --top-k 5
373
+ ```
374
+
375
+ ### Batch Processing
376
+
377
+ Process multiple questions or generate reports:
378
+
379
+ ```python
380
+ from ragit import RAGAssistant
381
+
382
+ assistant = RAGAssistant("docs/")
383
+
384
+ questions = [
385
+ "What authentication methods are supported?",
386
+ "How do I handle errors?",
387
+ "What are the rate limits?",
388
+ ]
389
+
390
+ # Process questions
391
+ results = {}
392
+ for question in questions:
393
+ results[question] = assistant.ask(question)
394
+
395
+ # Generate a report
396
+ with open("qa-report.md", "w") as f:
397
+ f.write("# Documentation Q&A Report\n\n")
398
+ for question, answer in results.items():
399
+ f.write(f"## {question}\n\n")
400
+ f.write(f"{answer}\n\n")
401
+ ```
402
+
403
+ ## Advanced: Hyperparameter Optimization
404
+
405
+ Ragit includes tools to find the optimal RAG configuration for your specific documents and use case.
406
+
407
+ ```python
408
+ from ragit import RagitExperiment, Document, BenchmarkQuestion
409
+
410
+ # Your documents
411
+ documents = [
412
+ Document(id="auth", content="Authentication uses Bearer tokens..."),
413
+ Document(id="api", content="The API supports GET, POST, PUT, DELETE..."),
414
+ ]
415
+
416
+ # Benchmark questions with expected answers
417
+ benchmark = [
418
+ BenchmarkQuestion(
419
+ question="What authentication method does the API use?",
420
+ ground_truth="The API uses Bearer token authentication."
421
+ ),
422
+ BenchmarkQuestion(
423
+ question="What HTTP methods are supported?",
424
+ ground_truth="GET, POST, PUT, and DELETE methods are supported."
425
+ ),
426
+ ]
427
+
428
+ # Run optimization
429
+ experiment = RagitExperiment(documents, benchmark)
430
+ results = experiment.run(max_configs=20)
431
+
432
+ # Get the best configuration
433
+ best = results[0]
434
+ print(f"Best config: chunk_size={best.config.chunk_size}, "
435
+ f"chunk_overlap={best.config.chunk_overlap}, "
436
+ f"top_k={best.config.top_k}")
437
+ print(f"Score: {best.score:.3f}")
438
+ ```
439
+
440
+ The experiment tests different combinations of chunk sizes, overlaps, and retrieval parameters to find what works best for your content.
441
+
442
+ ## API Reference
443
+
444
+ ### Document Loading
445
+
446
+ | Function | Description |
447
+ |----------|-------------|
448
+ | `load_text(path)` | Load a single text file as a Document |
449
+ | `load_directory(path, pattern, recursive=False)` | Load files matching a glob pattern |
450
+ | `chunk_text(text, chunk_size, chunk_overlap, doc_id)` | Split text into overlapping chunks |
451
+ | `chunk_document(doc, chunk_size, chunk_overlap)` | Split a Document into chunks |
452
+ | `chunk_by_separator(text, separator, doc_id)` | Split text by a delimiter |
453
+ | `chunk_rst_sections(text, doc_id)` | Split RST by section headers |
454
+
455
+ ### RAGAssistant
456
+
457
+ | Method | Description |
458
+ |--------|-------------|
459
+ | `retrieve(query, top_k=3)` | Return list of (Chunk, score) tuples |
460
+ | `get_context(query, top_k=3)` | Return formatted context string |
461
+ | `generate(prompt, system_prompt, temperature)` | Generate text without retrieval |
462
+ | `ask(question, system_prompt, top_k, temperature)` | Retrieve context and generate answer |
463
+ | `generate_code(request, language, top_k, temperature)` | Generate clean code |
464
+
465
+ ### Properties
466
+
467
+ | Property | Description |
468
+ |----------|-------------|
469
+ | `assistant.num_documents` | Number of loaded documents |
470
+ | `assistant.num_chunks` | Number of indexed chunks |
471
+ | `assistant.embedding_model` | Current embedding model |
472
+ | `assistant.llm_model` | Current LLM model |
473
+
474
+ ## License
475
+
476
+ Apache-2.0 - RODMENA LIMITED