Skip to content

Commit 49b70b8

Browse files
committed
feat: High-leverage production improvements
Major improvements based on whitepaper priority: 1. Neo4j Connection Reliability - Added retry logic with exponential backoff - Connection pooling (50 connections, 1hr max lifetime) - Automatic connection recovery on failures - Comprehensive error handling for auth/network issues - Wrap all DB operations with _execute_with_retry() 2. INHERITS & Scope Resolution - Added full inheritance chain traversal (ancestors/descendants) - New resolve_symbol_scope() for smart symbol resolution - Scope search order: local -> direct imports -> transitive - get_inheritance_chain() for complete class hierarchies - Reduces hallucinations by providing proper context 3. Jamba Encoder Integration (Frozen) - Reasoner.generate_refactor_plan() uses real AI21 Jamba - use_deep_context=True activates Phase 3 encoder - Full integration tests with AI21 Cloud API - 4/4 tests passing with real Jamba compression - Produces validated ContextBlock outputs 4. Tree-Sitter AST-Based Masking - src/diffusion/masking.py (415 lines) - Deterministic masking anchored to AST node spans - Replaces heuristic token masking - Supports Python, JavaScript, TypeScript - 7 masking strategies (function_body, identifiers, types, etc.) - Preserves syntactic validity during diffusion - 15/15 tests passing Test Results: - test_jamba_integration.py: 4/4 PASS - test_ast_masking.py: 15/15 PASS - Real AI21 API compression verified Ready for Phase 5 (outlines/CFG validation + Qwen fallback)
1 parent fd6a8ca commit 49b70b8

13 files changed

Lines changed: 1764 additions & 60 deletions

File tree

.env.example

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,35 @@ NEO4J_PASSWORD=ouroboros123
66
# Provenance Metadata
77
MODEL_NAME=ouroboros-librarian
88
MODEL_VERSION=1.0.0
9+
10+
# ============================================
11+
# Phase 2: LLM API Keys (The Reasoner)
12+
# ============================================
13+
14+
# Claude (Anthropic)
15+
ANTHROPIC_API_KEY=your_anthropic_api_key_here
16+
17+
# Gemini (Google)
18+
GOOGLE_API_KEY=your_google_api_key_here
19+
20+
# OpenAI
21+
OPENAI_API_KEY=your_openai_api_key_here
22+
23+
# Jamba (AI21)
24+
AI21_API_KEY=your_ai21_api_key_here
25+
26+
# ============================================
27+
# Phase 3: Context Encoder Configuration
28+
# ============================================
29+
30+
# AI21 Jamba Configuration
31+
# Get your API key: https://studio.ai21.com/account/api-key
32+
AI21_API_KEY=your_ai21_api_key_here
33+
34+
# Context Encoder Mode
35+
# - "cloud": Use AI21 Cloud API (recommended, reliable)
36+
# - "local": Use LM Studio local inference (free, requires setup)
37+
JAMBA_MODE=cloud
38+
39+
# LM Studio Configuration (only needed if JAMBA_MODE=local)
40+
LMSTUDIO_BASE_URL=http://localhost:1234/v1

docs/AI21_SETUP.md

Lines changed: 226 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,226 @@
1+
# AI21 Jamba Cloud Setup Guide
2+
3+
## Why AI21 Cloud?
4+
5+
**Recommended for Production**
6+
- Reliable 99.9% uptime
7+
- No local GPU required
8+
- Automatic scaling
9+
- 256k token context window
10+
- Official support from AI21
11+
12+
## Step 1: Get Your API Key
13+
14+
1. Go to [AI21 Studio](https://studio.ai21.com/)
15+
2. Sign up / Log in
16+
3. Navigate to **Account → API Key**
17+
4. Click **"Create New API Key"**
18+
5. Copy your API key (starts with `AI21_...`)
19+
20+
**Free Tier:**
21+
- $10 free credits on signup
22+
- ~200,000 tokens free
23+
- Good for testing Phase 3
24+
25+
**Pricing (after free tier):**
26+
- Jamba-1.5-Mini: $0.20 per 1M input tokens
27+
- Jamba-1.5-Large: $2.00 per 1M input tokens
28+
29+
## Step 2: Configure Ouroboros
30+
31+
### Option A: Environment Variable (Recommended)
32+
33+
```bash
34+
# Windows PowerShell
35+
$env:AI21_API_KEY="your_api_key_here"
36+
37+
# Linux/Mac
38+
export AI21_API_KEY="your_api_key_here"
39+
```
40+
41+
### Option B: .env File
42+
43+
```bash
44+
# Copy the example file
45+
cp .env.example .env
46+
47+
# Edit .env and add your key
48+
AI21_API_KEY=your_actual_api_key_here
49+
JAMBA_MODE=cloud
50+
```
51+
52+
## Step 3: Test the Connection
53+
54+
```python
55+
from src.context_encoder import ContextEncoder, ContextEncoderConfig
56+
from src.context_encoder.config import EncoderProvider, JambaConfig
57+
58+
# Configure for AI21 Cloud
59+
jamba_config = JambaConfig(
60+
use_cloud=True,
61+
cloud_api_key="your_api_key_here" # Or load from env
62+
)
63+
64+
config = ContextEncoderConfig(
65+
provider=EncoderProvider.JAMBA_CLOUD,
66+
jamba=jamba_config
67+
)
68+
69+
encoder = ContextEncoder(config)
70+
71+
# Test compression
72+
sample_code = """
73+
export class AuthService {
74+
async login(email: string, password: string) {
75+
// Authentication logic
76+
}
77+
}
78+
"""
79+
80+
compressed = encoder.compress(
81+
codebase_context=sample_code,
82+
target_files=["auth.ts"]
83+
)
84+
85+
print(f"✅ Compression successful!")
86+
print(f"Input: {compressed.tokens_in} tokens")
87+
print(f"Output: {compressed.tokens_out} tokens")
88+
print(f"Ratio: {compressed.compression_ratio:.1f}x")
89+
print(f"\nSummary:\n{compressed.summary}")
90+
```
91+
92+
## Step 4: Use with Reasoner (Phase 2 Integration)
93+
94+
```python
95+
from src.reasoner import Reasoner, ReasonerConfig
96+
from src.reasoner.config import LLMProvider
97+
98+
# Initialize Reasoner
99+
config = ReasonerConfig(provider=LLMProvider.GEMINI)
100+
reasoner = Reasoner(config)
101+
102+
# Generate refactor plan with deep context
103+
plan = reasoner.generate_refactor_plan(
104+
task_description="Refactor authentication system",
105+
target_file="src/auth/login.ts",
106+
use_deep_context=True # 🔥 Uses AI21 Jamba for 256k context
107+
)
108+
109+
print(f"Plan ID: {plan.plan_id}")
110+
print(f"Impact: {plan.estimated_impact}")
111+
```
112+
113+
## Troubleshooting
114+
115+
### Error: "AI21_API_KEY environment variable not set"
116+
117+
**Solution:** Set the environment variable or pass it explicitly:
118+
119+
```python
120+
from src.context_encoder.config import JambaConfig
121+
122+
jamba_config = JambaConfig(
123+
use_cloud=True,
124+
cloud_api_key="your_key_here"
125+
)
126+
```
127+
128+
### Error: "Failed to initialize Jamba client"
129+
130+
**Possible causes:**
131+
1. Invalid API key
132+
2. No internet connection
133+
3. AI21 API is down (check [status.ai21.com](https://status.ai21.com))
134+
135+
**Solution:** Verify your API key at [studio.ai21.com](https://studio.ai21.com)
136+
137+
### Error: Rate limit exceeded
138+
139+
**Solution:** You've used your free credits. Options:
140+
1. Add payment method to AI21 account
141+
2. Switch to local mode (free): `JAMBA_MODE=local`
142+
3. Use mock provider for testing: `EncoderProvider.MOCK`
143+
144+
### Slow response times
145+
146+
**Normal behavior:**
147+
- First request: 10-30 seconds (cold start)
148+
- Subsequent requests: 3-10 seconds
149+
- Large context (100k+ tokens): 15-45 seconds
150+
151+
**If consistently slow:**
152+
- Check your internet connection
153+
- Try a smaller context first
154+
- Consider using `max_output_tokens` to limit summary length
155+
156+
## Switching Between Cloud and Local
157+
158+
### Use Cloud (Recommended)
159+
160+
```python
161+
config = ContextEncoderConfig(
162+
provider=EncoderProvider.JAMBA_CLOUD,
163+
jamba=JambaConfig(use_cloud=True)
164+
)
165+
```
166+
167+
### Use Local (Free, Requires LM Studio)
168+
169+
```python
170+
config = ContextEncoderConfig(
171+
provider=EncoderProvider.JAMBA_LOCAL,
172+
jamba=JambaConfig(
173+
use_cloud=False,
174+
local_base_url="http://localhost:1234/v1"
175+
)
176+
)
177+
```
178+
179+
See [LMSTUDIO_SETUP.md](./LMSTUDIO_SETUP.md) for local setup instructions.
180+
181+
## Cost Estimation
182+
183+
**Jamba-1.5-Mini Pricing:**
184+
185+
| Context Size | Input Tokens | Output Tokens | Cost per Request |
186+
|--------------|--------------|---------------|------------------|
187+
| Small (10k) | 10,000 | 2,000 | $0.002 |
188+
| Medium (50k) | 50,000 | 4,000 | $0.010 |
189+
| Large (100k) | 100,000 | 4,000 | $0.020 |
190+
| Massive (256k)| 256,000 | 4,000 | $0.051 |
191+
192+
**Free tier gives you:**
193+
- ~5,000 requests (small context)
194+
- ~1,000 requests (medium context)
195+
- ~500 requests (large context)
196+
- ~200 requests (massive context)
197+
198+
## Best Practices
199+
200+
1. **Start with mock provider** for development:
201+
```python
202+
config = ContextEncoderConfig(provider=EncoderProvider.MOCK)
203+
```
204+
205+
2. **Use cloud for production** (reliable, scalable)
206+
207+
3. **Use local for experimentation** (free, private)
208+
209+
4. **Monitor your usage** at [studio.ai21.com](https://studio.ai21.com)
210+
211+
5. **Cache compressed contexts** to avoid redundant API calls
212+
213+
## Security
214+
215+
⚠️ **Never commit your API key to Git!**
216+
217+
- ✅ Use environment variables
218+
- ✅ Use `.env` file (in `.gitignore`)
219+
- ❌ Don't hardcode keys in source code
220+
- ❌ Don't share keys in screenshots/logs
221+
222+
## Support
223+
224+
- **AI21 Documentation:** https://docs.ai21.com/
225+
- **AI21 Discord:** https://discord.gg/ai21labs
226+
- **GitHub Issues:** https://github.com/vivek5200/ouroboros/issues

docs/index.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,17 @@ Ouroboros is an autonomous agent designed to self-correct and refactor codebases
2121
### Key Features
2222

2323
* **⚡ Automated Refactoring**: Intelligent code analysis.
24-
* **🧠 LLM Integration**: Powered by LM Studio / Local LLMs.
24+
* **🧠 LLM Integration**: 6 providers + AI21 Jamba (256k context).
2525
* **🔄 Self-Healing**: Detects errors and proposes fixes iteratively.
26+
* **🚀 Deep Context**: AI21 Cloud integration for massive codebases.
2627

2728
### Documentation Status
2829

2930
| Module | Status | Description |
3031
|:-------|:-------|:------------|
3132
| **Phase 1** | ✅ Complete | Code parsing and graph database construction. |
3233
| **Phase 2** | ✅ Complete | LLM-powered refactor plan generation with 6 providers. |
34+
| **Phase 3** | ✅ Complete | Jamba context encoder with 256k token window (AI21 Cloud). |
3335

3436
---
3537

src/context_encoder/config.py

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,42 +12,66 @@
1212

1313
class EncoderProvider(Enum):
1414
"""Supported context encoder providers."""
15-
JAMBA = "jamba" # AI21 Jamba-1.5-Mini (Hybrid Mamba-Transformer)
16-
MOCK = "mock" # Mock encoder for testing
15+
JAMBA_CLOUD = "jamba_cloud" # AI21 Cloud API (recommended for production)
16+
JAMBA_LOCAL = "jamba_local" # LM Studio local inference
17+
MOCK = "mock" # Mock encoder for testing
1718

1819

1920
@dataclass
2021
class JambaConfig:
2122
"""Configuration for AI21 Jamba-1.5-Mini model."""
2223

23-
model_name: str = "ai21/jamba-1.5-mini"
24+
# Model Configuration
25+
model_name: str = "jamba-mini" # AI21 model name (jamba-mini or jamba-large)
2426
context_window: int = 256_000 # 256k tokens
2527
max_output_tokens: int = 4096 # For context summary
2628
temperature: float = 0.3 # Low temperature for deterministic summaries
2729

28-
# API Configuration
29-
base_url: str = "http://localhost:1234/v1" # LM Studio default
30-
api_key: Optional[str] = None
31-
timeout: int = 300 # 5 minutes for large context
30+
# API Configuration (Cloud vs Local)
31+
use_cloud: bool = True # True: AI21 Cloud, False: LM Studio local
32+
33+
# AI21 Cloud Configuration
34+
cloud_api_url: str = "https://api.ai21.com/studio/v1"
35+
cloud_api_key: Optional[str] = None # Set via AI21_API_KEY env var
36+
37+
# LM Studio Local Configuration
38+
local_base_url: str = "http://localhost:1234/v1" # LM Studio default
39+
local_api_key: Optional[str] = None # Not needed for local
3240

33-
# Performance
41+
# Common Configuration
42+
timeout: int = 300 # 5 minutes for large context
3443
batch_size: int = 1
3544
use_streaming: bool = False
3645

3746
def __post_init__(self):
38-
"""Validate configuration."""
47+
"""Validate configuration and load from environment."""
3948
if self.max_output_tokens > self.context_window:
4049
raise ValueError(
4150
f"max_output_tokens ({self.max_output_tokens}) cannot exceed "
4251
f"context_window ({self.context_window})"
4352
)
53+
54+
# Load API key from environment if not set
55+
if self.use_cloud and not self.cloud_api_key:
56+
import os
57+
self.cloud_api_key = os.getenv("AI21_API_KEY")
58+
59+
@property
60+
def base_url(self) -> str:
61+
"""Get the active base URL based on cloud/local mode."""
62+
return self.cloud_api_url if self.use_cloud else self.local_base_url
63+
64+
@property
65+
def api_key(self) -> Optional[str]:
66+
"""Get the active API key based on cloud/local mode."""
67+
return self.cloud_api_key if self.use_cloud else self.local_api_key
4468

4569

4670
@dataclass
4771
class ContextEncoderConfig:
4872
"""Main configuration for the Context Encoder."""
4973

50-
provider: EncoderProvider = EncoderProvider.JAMBA
74+
provider: EncoderProvider = EncoderProvider.JAMBA_CLOUD
5175
jamba: JambaConfig = field(default_factory=JambaConfig)
5276

5377
# Context Compression Settings

0 commit comments

Comments
 (0)