-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
217 lines (166 loc) · 6.75 KB
/
cli.py
File metadata and controls
217 lines (166 loc) · 6.75 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
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
#!/usr/bin/env python
"""CLI interface for CodeBase Intelligence RAG."""
import typer
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.table import Table
from typing import Optional
app = typer.Typer(
name="codebase-rag",
help="🧠 CodeBase Intelligence RAG - Chat with any codebase",
)
console = Console()
# Global state
_retriever = None
_generator = None
_reranker = None
def get_components():
"""Lazy load components."""
global _retriever, _generator, _reranker
if _retriever is None:
from src.retrieval import HybridRetriever, LightweightReranker
from src.generation import CodeGenerator
_retriever = HybridRetriever()
_generator = CodeGenerator()
_reranker = LightweightReranker()
return _retriever, _generator, _reranker
@app.command()
def ingest(
repo_url: str = typer.Argument(..., help="GitHub repository URL"),
branch: Optional[str] = typer.Option(None, "--branch", "-b", help="Branch to clone"),
force: bool = typer.Option(False, "--force", "-f", help="Force re-clone"),
):
"""Ingest a GitHub repository into the RAG system."""
from src.ingestion import GitHubLoader
from src.chunking import ASTChunker
with console.status("[bold green]Ingesting repository..."):
# Load
console.print(f"📦 Cloning [cyan]{repo_url}[/cyan]...")
loader = GitHubLoader()
files = loader.clone_repo(repo_url, branch=branch, force=force)
console.print(f"📄 Found [green]{len(files)}[/green] files")
# Chunk
console.print("🧩 Chunking files...")
chunker = ASTChunker()
chunks = chunker.chunk_files(files)
console.print(f"✂️ Created [green]{len(chunks)}[/green] chunks")
# Index
console.print("📊 Indexing chunks...")
retriever, _, _ = get_components()
retriever.index(chunks)
console.print(Panel.fit(
f"[bold green]✅ Successfully indexed![/bold green]\n\n"
f"Files: {len(files)}\n"
f"Chunks: {len(chunks)}\n\n"
f"Run [cyan]codebase-rag query \"your question\"[/cyan] to search",
title="Ingestion Complete",
))
@app.command()
def query(
question: str = typer.Argument(..., help="Question about the codebase"),
top_k: int = typer.Option(5, "--top-k", "-k", help="Number of results"),
no_rerank: bool = typer.Option(False, "--no-rerank", help="Disable reranking"),
show_sources: bool = typer.Option(True, "--sources/--no-sources", help="Show sources"),
):
"""Query the indexed codebase."""
import time
retriever, generator, reranker = get_components()
with console.status("[bold blue]Searching..."):
# Retrieve
start = time.time()
results = retriever.search(question, top_k=top_k * 2)
if not results:
console.print("[yellow]No results found. Try a different query.[/yellow]")
return
# Rerank
if not no_rerank:
results = reranker.rerank(question, results, top_k=top_k)
else:
results = results[:top_k]
retrieval_time = time.time() - start
# Generate
start = time.time()
answer = generator.generate(question, results)
generation_time = time.time() - start
# Display answer
console.print()
console.print(Panel(Markdown(answer), title="[bold]Answer[/bold]", border_style="green"))
# Display sources
if show_sources:
table = Table(title="Sources", show_header=True)
table.add_column("#", style="dim", width=3)
table.add_column("File", style="cyan")
table.add_column("Type", style="green")
table.add_column("Name", style="yellow")
table.add_column("Score", justify="right")
for i, r in enumerate(results[:5], 1):
meta = r.get("metadata", {})
table.add_row(
str(i),
meta.get("file_path", "unknown"),
meta.get("chunk_type", "code"),
meta.get("name", "-"),
f"{r.get('score', 0):.3f}",
)
console.print(table)
# Timing
console.print(f"\n[dim]⏱️ Retrieval: {retrieval_time*1000:.0f}ms | Generation: {generation_time*1000:.0f}ms[/dim]")
@app.command()
def chat():
"""Start interactive chat mode."""
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
retriever, generator, reranker = get_components()
console.print(Panel.fit(
"[bold]🧠 CodeBase Intelligence RAG[/bold]\n\n"
"Type your questions and press Enter.\n"
"Type [cyan]exit[/cyan] or [cyan]quit[/cyan] to leave.\n"
"Type [cyan]clear[/cyan] to clear the screen.",
title="Interactive Chat",
))
history = FileHistory(".codebase_rag_history")
while True:
try:
question = prompt("\n❓ ", history=history).strip()
if not question:
continue
if question.lower() in ("exit", "quit", "q"):
console.print("[yellow]Goodbye! 👋[/yellow]")
break
if question.lower() == "clear":
console.clear()
continue
# Search and generate
with console.status("[bold blue]Thinking..."):
results = retriever.search(question, top_k=10)
if not results:
console.print("[yellow]No results found.[/yellow]")
continue
results = reranker.rerank(question, results, top_k=5)
answer = generator.generate(question, results)
console.print()
console.print(Markdown(answer))
except KeyboardInterrupt:
console.print("\n[yellow]Use 'exit' to quit.[/yellow]")
except EOFError:
break
@app.command()
def stats():
"""Show system statistics."""
retriever, _, _ = get_components()
stats = retriever.vector_store.get_stats()
console.print(Panel.fit(
f"[bold]Collection:[/bold] {stats['name']}\n"
f"[bold]Total Chunks:[/bold] {stats['count']}",
title="📊 System Statistics",
))
@app.command()
def reset():
"""Reset the system (delete all indexed data)."""
if typer.confirm("⚠️ This will delete all indexed data. Continue?"):
retriever, _, _ = get_components()
retriever.vector_store.delete_collection()
console.print("[green]✅ Collection deleted successfully.[/green]")
if __name__ == "__main__":
app()