Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions examples/python-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,15 @@

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

The SDK has two main components:

1. **Auggie SDK** - An agent-based interface for AI-powered workflows with typed responses, sessions, and function calling
2. **Context SDK** - Semantic search and AI-powered code analysis via `FileSystemContext` and `DirectContext`

## Quick Links

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

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

## Context SDK Examples

The **[context](context/)** directory contains examples demonstrating the Auggie SDK's context modes for semantic search and AI-powered code analysis:

- **[Direct Context](context/direct_context/)** - API-based indexing with semantic search and AI Q&A
- **[FileSystem Context](context/filesystem_context/)** - Local directory search via MCP protocol
- **[File Search Server](context/file_search_server/)** - REST API for semantic file search with AI summarization
- **[Prompt Enhancer Server](context/prompt_enhancer_server/)** - HTTP server that enhances prompts with codebase context
- **[GitHub Action Indexer](context/github_action_indexer/)** - Index GitHub repositories for semantic search

See the [context README](context/README.md) for prerequisites and detailed usage instructions.

## Prompt-to-SDK Conversion

### `example_complex_prompt.txt`
Expand Down
108 changes: 108 additions & 0 deletions examples/python-sdk/context/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Context Examples

Examples demonstrating the Auggie SDK's context modes and AI-powered code analysis.

## Prerequisites

1. **Python 3.10+** - Required to run the examples
2. **Auggie CLI** - Required for FileSystem Context examples
```bash
npm install -g @augmentcode/auggie@prerelease
```
3. **Authentication** - Required for all examples
```bash
auggie login
```
This creates a session file at `~/.augment/session.json` with your API token.

Alternatively, you can set environment variables:
```bash
export AUGMENT_API_TOKEN=your_token_here
export AUGMENT_API_URL=https://staging-shard-0.api.augmentcode.com/
```

## Examples

### [Direct Context](./direct_context/)
API-based indexing with semantic search and AI Q&A.

**Run it:**
```bash
python -m direct_context
```

### [FileSystem Context](./filesystem_context/)
Local directory search via MCP protocol.

**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.

**Run it:**
```bash
python -m filesystem_context
```

### [File Search Server](./file_search_server/)
REST API for semantic file search with AI summarization.

**Run it:**
```bash
python -m file_search_server .
```

Then query the API:
```bash
curl "http://localhost:3000/search?q=python"
```

### [Prompt Enhancer Server](./prompt_enhancer_server/)
HTTP server that enhances prompts with codebase context.

**Run it:**
```bash
python -m prompt_enhancer_server .
```

Then enhance prompts:
```bash
curl -X POST http://localhost:3001/enhance \
-H "Content-Type: application/json" \
-d '{"prompt": "fix the login bug"}'
```

### [GitHub Action Indexer](./github_action_indexer/)
Index GitHub repositories with incremental updates via GitHub Actions.

This is a more complex example that demonstrates production-ready repository indexing with GitHub Actions integration. It includes an install script for easy setup in your own repositories.

See [github_action_indexer/README.md](./github_action_indexer/README.md) for setup and usage instructions.

## Troubleshooting

### MCP Timeout in FileSystem Context

**Problem:** The FileSystem Context example times out during indexing.

**Cause:** The workspace directory contains too many files (e.g., `node_modules/` with 45,000+ files).

**Solution:** Create a `.gitignore` or `.augmentignore` file in the workspace directory to exclude large directories:

```bash
# .gitignore or .augmentignore
node_modules/
dist/
*.log
.DS_Store
__pycache__/
*.pyc
```

The auggie CLI respects both `.gitignore` and `.augmentignore` patterns and will skip excluded files during indexing.

### Authentication Errors

**Problem:** `Error: API key is required for search_and_ask()`

**Cause:** The SDK cannot find your authentication credentials.

**Solution:** Run `auggie login` to authenticate, or set the `AUGMENT_API_TOKEN` and `AUGMENT_API_URL` environment variables.

33 changes: 33 additions & 0 deletions examples/python-sdk/context/direct_context/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Direct Context Example

API-based indexing with semantic search, AI Q&A, and state persistence.

## Usage

```bash
# Authenticate
auggie login

# Run the example (from the context directory)
cd examples/python-sdk/context
python -m direct_context

# Or run directly
python direct_context/main.py
```

## What It Does

- Creates a Direct Context instance
- Adds sample files to the index
- Performs semantic searches
- Uses `search_and_ask()` for AI-powered Q&A
- Generates documentation
- Exports/imports context state

## Key Features

- **`search()`**: Semantic search returning formatted code snippets
- **`search_and_ask()`**: One-step AI Q&A about indexed code
- **State persistence**: Export/import index for reuse

2 changes: 2 additions & 0 deletions examples/python-sdk/context/direct_context/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# direct_context package

5 changes: 5 additions & 0 deletions examples/python-sdk/context/direct_context/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Allow running as: python -m direct_context"""
from .main import main

main()

133 changes: 133 additions & 0 deletions examples/python-sdk/context/direct_context/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
"""
Sample: Direct Context - API-based indexing with import/export state

This sample demonstrates:
- Creating a Direct Context instance
- Adding files to the index
- Searching the indexed files
- Using Generation API to ask questions about indexed code
- Generating documentation from indexed code
- Exporting state to a file
- Importing state from a file
"""

import json
import sys
import tempfile
from pathlib import Path

from auggie_sdk.context import DirectContext, File

# Sample files are in the samples/ subdirectory
SAMPLES_DIR = Path(__file__).parent / "samples"


def load_sample_files() -> list[File]:
"""Load sample Python files from the samples directory."""
files = []
for file_path in SAMPLES_DIR.rglob("*.py"):
relative_path = file_path.relative_to(SAMPLES_DIR)
contents = file_path.read_text()
files.append(File(path=str(relative_path), contents=contents))
return files


def main():
print("=== Direct Context Sample ===\n")

# Create a Direct Context instance
# Authentication is automatic via:
# 1. AUGMENT_API_TOKEN / AUGMENT_API_URL env vars, or
# 2. ~/.augment/session.json (created by `auggie login`)
print("Creating Direct Context...")
context = DirectContext.create(debug=True)

# Load sample files from the samples/ directory
print("\nAdding files to index...")
file_objects = load_sample_files()
print(f" Found {len(file_objects)} sample files")
result = context.add_to_index(file_objects)
print("\nIndexing result:")
print(f" Newly uploaded: {result.newly_uploaded}")
print(f" Already uploaded: {result.already_uploaded}")

# Search the codebase - returns formatted string ready for LLM use or display
# Using queries that work well with our realistic content
print("\n--- Search 1: Find string utility functions ---")
results1 = context.search("string utility functions for text formatting")
print("Search results:")
print(results1)

print("\n--- Search 2: Find user management service ---")
results2 = context.search("user management service with CRUD operations")
print("Search results:")
print(results2)

print("\n--- Search 3: Find HTTP client for API requests ---")
http_results = context.search("HTTP client for making API requests")
print("Search results:")
print(http_results)

# Use search_and_ask to ask questions about the indexed code
print("\n--- search_and_ask Example 1: Ask questions about the code ---")
question = "How does the UserService class handle user creation and validation?"
print(f"Question: {question}")

answer = context.search_and_ask(
"user creation and validation in UserService",
question,
)

print(f"\nAnswer: {answer}")

# Use search_and_ask to generate documentation
print("\n--- search_and_ask Example 2: Generate documentation ---")
documentation = context.search_and_ask(
"string utility functions",
"Generate API documentation in markdown format for the string utility functions",
)

print("\nGenerated Documentation:")
print(documentation)

# Use search_and_ask to explain code patterns
print("\n--- search_and_ask Example 3: Explain code patterns ---")
explanation = context.search_and_ask(
"utility functions",
"Explain what these utility functions do and when they would be useful",
)

print(f"\nExplanation: {explanation}")

# Export state to a file
state_file = Path(tempfile.gettempdir()) / "direct-context-state.json"
print(f"\nExporting state to {state_file}...")
context.export_to_file(state_file)
print("State exported successfully")

# Show the exported state
with open(state_file, "r") as f:
exported_state = json.load(f)
print("\nExported state:")
print(json.dumps(exported_state, indent=2))

# Import state in a new context
print("\n--- Testing state import ---")
context2 = DirectContext.import_from_file(state_file, debug=False)
print("State imported successfully")

# Verify we can still search
results3 = context2.search("string utility functions")
print("\nSearch after importing state:")
print(results3)

print("\n=== Sample Complete ===")


if __name__ == "__main__":
try:
main()
except Exception as error:
print(f"Error: {error}")
sys.exit(1)

Loading