Skip to content

Commit 119c920

Browse files
committed
Python Examples for Context SDK
1 parent 7e6a4c0 commit 119c920

File tree

39 files changed

+3626
-0
lines changed

39 files changed

+3626
-0
lines changed

examples/python-sdk/README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,15 @@
22

33
This directory contains examples demonstrating how to use the Augment Python SDK.
44

5+
The SDK has two main components:
6+
7+
1. **Auggie SDK** - An agent-based interface for AI-powered workflows with typed responses, sessions, and function calling
8+
2. **Context SDK** - Semantic search and AI-powered code analysis via `FileSystemContext` and `DirectContext`
9+
510
## Quick Links
611

712
- **[User Examples](user_examples/)** - Numbered tutorial examples (01-09) with a comprehensive [user guide](user_examples/user_guide.md)
13+
- **[Context Examples](context/)** - Semantic search and AI-powered code analysis examples
814
- **[Documentation](docs/)** - Detailed guides on specific features
915
- **Basic Examples** - See below for standalone example scripts
1016

@@ -75,6 +81,18 @@ python acp_example_usage.py
7581
For ClaudeCodeACPClient documentation, see:
7682
- [Claude Code Client Guide](docs/CLAUDE_CODE_CLIENT.md)
7783

84+
## Context SDK Examples
85+
86+
The **[context](context/)** directory contains examples demonstrating the Auggie SDK's context modes for semantic search and AI-powered code analysis:
87+
88+
- **[Direct Context](context/direct_context/)** - API-based indexing with semantic search and AI Q&A
89+
- **[FileSystem Context](context/filesystem_context/)** - Local directory search via MCP protocol
90+
- **[File Search Server](context/file_search_server/)** - REST API for semantic file search with AI summarization
91+
- **[Prompt Enhancer Server](context/prompt_enhancer_server/)** - HTTP server that enhances prompts with codebase context
92+
- **[GitHub Action Indexer](context/github_action_indexer/)** - Index GitHub repositories for semantic search
93+
94+
See the [context README](context/README.md) for prerequisites and detailed usage instructions.
95+
7896
## Prompt-to-SDK Conversion
7997

8098
### `example_complex_prompt.txt`
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# Context Examples
2+
3+
Examples demonstrating the Auggie SDK's context modes and AI-powered code analysis.
4+
5+
## Prerequisites
6+
7+
1. **Python 3.10+** - Required to run the examples
8+
2. **Auggie CLI** - Required for FileSystem Context examples
9+
```bash
10+
npm install -g @augmentcode/auggie@prerelease
11+
```
12+
3. **Authentication** - Required for all examples
13+
```bash
14+
auggie login
15+
```
16+
This creates a session file at `~/.augment/session.json` with your API token.
17+
18+
Alternatively, you can set environment variables:
19+
```bash
20+
export AUGMENT_API_TOKEN=your_token_here
21+
export AUGMENT_API_URL=https://staging-shard-0.api.augmentcode.com/
22+
```
23+
24+
## Examples
25+
26+
### [Direct Context](./direct_context/)
27+
API-based indexing with semantic search and AI Q&A.
28+
29+
**Run it:**
30+
```bash
31+
python -m direct_context
32+
```
33+
34+
### [FileSystem Context](./filesystem_context/)
35+
Local directory search via MCP protocol.
36+
37+
**Important:** The FileSystem Context indexes all files in the workspace directory. To avoid timeouts when indexing large directories (like `node_modules/`), consider adding a `.gitignore` or `.augmentignore` file that excludes them. The auggie CLI respects both `.gitignore` and `.augmentignore` patterns during indexing.
38+
39+
**Run it:**
40+
```bash
41+
python -m filesystem_context
42+
```
43+
44+
### [File Search Server](./file_search_server/)
45+
REST API for semantic file search with AI summarization.
46+
47+
**Run it:**
48+
```bash
49+
python -m file_search_server .
50+
```
51+
52+
Then query the API:
53+
```bash
54+
curl "http://localhost:3000/search?q=python"
55+
```
56+
57+
### [Prompt Enhancer Server](./prompt_enhancer_server/)
58+
HTTP server that enhances prompts with codebase context.
59+
60+
**Run it:**
61+
```bash
62+
python -m prompt_enhancer_server .
63+
```
64+
65+
Then enhance prompts:
66+
```bash
67+
curl -X POST http://localhost:3001/enhance \
68+
-H "Content-Type: application/json" \
69+
-d '{"prompt": "fix the login bug"}'
70+
```
71+
72+
### [GitHub Action Indexer](./github_action_indexer/)
73+
Index GitHub repositories for semantic search.
74+
75+
This example has its own requirements.txt and dependencies.
76+
77+
**Setup:**
78+
```bash
79+
pip install -r github_action_indexer/requirements.txt
80+
```
81+
82+
**Run it:**
83+
```bash
84+
python -m github_action_indexer index
85+
python -m github_action_indexer search "your query"
86+
```
87+
88+
See [github_action_indexer/README.md](./github_action_indexer/README.md) for more details.
89+
90+
## Troubleshooting
91+
92+
### MCP Timeout in FileSystem Context
93+
94+
**Problem:** The FileSystem Context example times out during indexing.
95+
96+
**Cause:** The workspace directory contains too many files (e.g., `node_modules/` with 45,000+ files).
97+
98+
**Solution:** Create a `.gitignore` or `.augmentignore` file in the workspace directory to exclude large directories:
99+
100+
```bash
101+
# .gitignore or .augmentignore
102+
node_modules/
103+
dist/
104+
*.log
105+
.DS_Store
106+
__pycache__/
107+
*.pyc
108+
```
109+
110+
The auggie CLI respects both `.gitignore` and `.augmentignore` patterns and will skip excluded files during indexing.
111+
112+
### Authentication Errors
113+
114+
**Problem:** `Error: API key is required for search_and_ask()`
115+
116+
**Cause:** The SDK cannot find your authentication credentials.
117+
118+
**Solution:** Run `auggie login` to authenticate, or set the `AUGMENT_API_TOKEN` and `AUGMENT_API_URL` environment variables.
119+
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Direct Context Example
2+
3+
API-based indexing with semantic search, AI Q&A, and state persistence.
4+
5+
## Usage
6+
7+
```bash
8+
# Authenticate
9+
auggie login
10+
11+
# Run the example (from the context directory)
12+
cd examples/python-sdk/context
13+
python -m direct_context
14+
15+
# Or run directly
16+
python direct_context/main.py
17+
```
18+
19+
## What It Does
20+
21+
- Creates a Direct Context instance
22+
- Adds sample files to the index
23+
- Performs semantic searches
24+
- Uses `search_and_ask()` for AI-powered Q&A
25+
- Generates documentation
26+
- Exports/imports context state
27+
28+
## Key Features
29+
30+
- **`search()`**: Semantic search returning formatted code snippets
31+
- **`search_and_ask()`**: One-step AI Q&A about indexed code
32+
- **State persistence**: Export/import index for reuse
33+
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# direct_context package
2+
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
"""Allow running as: python -m direct_context"""
2+
from .main import main
3+
4+
main()
5+
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
"""
2+
Sample: Direct Context - API-based indexing with import/export state
3+
4+
This sample demonstrates:
5+
- Creating a Direct Context instance
6+
- Adding files to the index
7+
- Searching the indexed files
8+
- Using Generation API to ask questions about indexed code
9+
- Generating documentation from indexed code
10+
- Exporting state to a file
11+
- Importing state from a file
12+
"""
13+
14+
import json
15+
import sys
16+
import tempfile
17+
from pathlib import Path
18+
19+
from auggie_sdk.context import DirectContext, File
20+
21+
# Sample files are in the samples/ subdirectory
22+
SAMPLES_DIR = Path(__file__).parent / "samples"
23+
24+
25+
def load_sample_files() -> list[File]:
26+
"""Load sample Python files from the samples directory."""
27+
files = []
28+
for file_path in SAMPLES_DIR.rglob("*.py"):
29+
relative_path = file_path.relative_to(SAMPLES_DIR)
30+
contents = file_path.read_text()
31+
files.append(File(path=str(relative_path), contents=contents))
32+
return files
33+
34+
35+
def main():
36+
print("=== Direct Context Sample ===\n")
37+
38+
# Create a Direct Context instance
39+
# Authentication is automatic via:
40+
# 1. AUGMENT_API_TOKEN / AUGMENT_API_URL env vars, or
41+
# 2. ~/.augment/session.json (created by `auggie login`)
42+
print("Creating Direct Context...")
43+
context = DirectContext.create(debug=True)
44+
45+
# Load sample files from the samples/ directory
46+
print("\nAdding files to index...")
47+
file_objects = load_sample_files()
48+
print(f" Found {len(file_objects)} sample files")
49+
result = context.add_to_index(file_objects)
50+
print("\nIndexing result:")
51+
print(f" Newly uploaded: {result.newly_uploaded}")
52+
print(f" Already uploaded: {result.already_uploaded}")
53+
54+
# Search the codebase - returns formatted string ready for LLM use or display
55+
# Using queries that work well with our realistic content
56+
print("\n--- Search 1: Find string utility functions ---")
57+
results1 = context.search("string utility functions for text formatting")
58+
print("Search results:")
59+
print(results1)
60+
61+
print("\n--- Search 2: Find user management service ---")
62+
results2 = context.search("user management service with CRUD operations")
63+
print("Search results:")
64+
print(results2)
65+
66+
print("\n--- Search 3: Find HTTP client for API requests ---")
67+
http_results = context.search("HTTP client for making API requests")
68+
print("Search results:")
69+
print(http_results)
70+
71+
# Use search_and_ask to ask questions about the indexed code
72+
print("\n--- search_and_ask Example 1: Ask questions about the code ---")
73+
question = "How does the UserService class handle user creation and validation?"
74+
print(f"Question: {question}")
75+
76+
answer = context.search_and_ask(
77+
"user creation and validation in UserService",
78+
question,
79+
)
80+
81+
print(f"\nAnswer: {answer}")
82+
83+
# Use search_and_ask to generate documentation
84+
print("\n--- search_and_ask Example 2: Generate documentation ---")
85+
documentation = context.search_and_ask(
86+
"string utility functions",
87+
"Generate API documentation in markdown format for the string utility functions",
88+
)
89+
90+
print("\nGenerated Documentation:")
91+
print(documentation)
92+
93+
# Use search_and_ask to explain code patterns
94+
print("\n--- search_and_ask Example 3: Explain code patterns ---")
95+
explanation = context.search_and_ask(
96+
"utility functions",
97+
"Explain what these utility functions do and when they would be useful",
98+
)
99+
100+
print(f"\nExplanation: {explanation}")
101+
102+
# Export state to a file
103+
state_file = Path(tempfile.gettempdir()) / "direct-context-state.json"
104+
print(f"\nExporting state to {state_file}...")
105+
context.export_to_file(state_file)
106+
print("State exported successfully")
107+
108+
# Show the exported state
109+
with open(state_file, "r") as f:
110+
exported_state = json.load(f)
111+
print("\nExported state:")
112+
print(json.dumps(exported_state, indent=2))
113+
114+
# Import state in a new context
115+
print("\n--- Testing state import ---")
116+
context2 = DirectContext.import_from_file(state_file, debug=False)
117+
print("State imported successfully")
118+
119+
# Verify we can still search
120+
results3 = context2.search("string utility functions")
121+
print("\nSearch after importing state:")
122+
print(results3)
123+
124+
print("\n=== Sample Complete ===")
125+
126+
127+
if __name__ == "__main__":
128+
try:
129+
main()
130+
except Exception as error:
131+
print(f"Error: {error}")
132+
sys.exit(1)
133+

0 commit comments

Comments
 (0)