-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_usage.py
More file actions
192 lines (151 loc) · 5.44 KB
/
api_usage.py
File metadata and controls
192 lines (151 loc) · 5.44 KB
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
#!/usr/bin/env python3
"""Example showing programmatic API usage of RLM-REPL.
This example demonstrates how to use RLM-REPL as a library in your
Python applications, including error handling and custom configuration.
"""
import sys
from typing import List, Dict, Any
from rlm_repl import RLMREPL, RLMConfig, DatabaseConfig
from rlm_repl.core.database import DocumentDatabase, QueryResult
from rlm_repl.events.streaming import Event, EventType
class DocumentQA:
"""A simple document Q&A system built on RLM-REPL."""
def __init__(
self,
base_url: str = "http://localhost:11434/v1",
api_key: str = "ollama",
model: str = "qwen3-coder",
):
"""Initialize the Q&A system."""
self.config = RLMConfig(
base_url=base_url,
api_key=api_key,
model=model,
verbose=False, # We'll handle output ourselves
max_iterations=6,
)
self._repl = RLMREPL(self.config)
self._questions_asked = 0
def load_file(self, filepath: str) -> Dict[str, Any]:
"""Load a document file.
Args:
filepath: Path to the text file.
Returns:
Dictionary with document statistics.
Raises:
FileNotFoundError: If file doesn't exist.
"""
stats = self._repl.load_document(filepath)
return {
"name": stats.doc_name,
"lines": stats.total_lines,
"words": stats.total_words,
"strategic_markers": stats.strategic_lines,
}
def load_content(self, content: str, name: str = "document") -> Dict[str, Any]:
"""Load text content directly.
Args:
content: Text content to load.
name: Name for the document.
Returns:
Dictionary with document statistics.
"""
stats = self._repl.load_text(content, name)
return {
"name": stats.doc_name,
"lines": stats.total_lines,
"words": stats.total_words,
"strategic_markers": stats.strategic_lines,
}
def ask(self, question: str) -> Dict[str, Any]:
"""Ask a question about the loaded document.
Args:
question: The question to ask.
Returns:
Dictionary with answer and metadata.
Raises:
RuntimeError: If no document is loaded.
"""
if not self._repl.is_loaded:
raise RuntimeError("No document loaded")
result = self._repl.ask(question)
self._questions_asked += 1
return {
"question": question,
"answer": result.answer,
"iterations": result.iterations,
"lines_read": result.unique_lines,
"words_read": result.total_words,
"time_seconds": result.elapsed_time,
}
def execute_sql(self, sql: str) -> List[Dict[str, Any]]:
"""Execute a raw SQL query.
Args:
sql: SQL query string.
Returns:
List of result rows as dictionaries.
"""
result = self._repl.query(sql)
return result.dataframe.to_dict("records")
def get_stats(self) -> Dict[str, Any]:
"""Get session statistics.
Returns:
Dictionary with session statistics.
"""
stats = self._repl.session_stats()
stats["document"] = None
if self._repl.is_loaded:
doc_stats = self._repl.stats
stats["document"] = {
"name": doc_stats.doc_name,
"lines": doc_stats.total_lines,
"words": doc_stats.total_words,
}
return stats
def close(self):
"""Close the Q&A system and release resources."""
self._repl.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def main():
"""Demonstrate API usage."""
print("=" * 70)
print("RLM-REPL API Usage Example")
print("=" * 70)
# Create the Q&A system
with DocumentQA() as qa:
# Load a document
content = qa.load_file("examples/library.txt")
print("\n1. Loading document...")
print(f" Loaded: {content['lines']} lines, {content['words']} words")
print("\n2. Asking questions...")
# Ask multiple questions
questions = [
"What is the main topic of this document?",
"What are the key sections or chapters?",
]
for question in questions:
print(f"\n Q: {question}")
try:
result = qa.ask(question)
print(f" A: {result['answer']}") # Show full answer, not truncated
print(f" (Read {result['lines_read']} lines in {result['time_seconds']:.1f}s)")
except Exception as e:
print(f" Error: {e}")
print("\n3. Direct SQL query...")
rows = qa.execute_sql(
"SELECT line_num, text FROM documents WHERE is_header = true LIMIT 5"
)
print(" Headers found:")
for row in rows:
print(f" - Line {row['line_num']}: {row['text']}")
print("\n4. Session statistics...")
session_stats = qa.get_stats()
print(f" Questions asked: {session_stats['questions_asked']}")
print(f" Total words read: {session_stats.get('total_words_read', 0)}")
print("\n" + "=" * 70)
print("Done!")
if __name__ == "__main__":
main()