Skip to content

Commit c4990f2

Browse files
committed
TypeScript SDK Examples
1 parent ad5318a commit c4990f2

File tree

4 files changed

+545
-0
lines changed

4 files changed

+545
-0
lines changed
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
import { DirectContext } from '@augmentcode/auggie-sdk';
2+
3+
/**
4+
* Example 1: Simple Usage
5+
* Upload files and ask questions immediately
6+
*/
7+
async function simpleExample() {
8+
console.log('\n=== Example 1: Simple Usage ===\n');
9+
10+
// Create context (authentication is automatic)
11+
const context = await DirectContext.create();
12+
13+
// Add files and wait for indexing (default behavior)
14+
const result = await context.addToIndex([
15+
{ path: 'src/auth.ts', contents: 'export function login(user: string, pass: string) { /* auth logic */ }' },
16+
{ path: 'src/user.ts', contents: 'export class User { constructor(public id: string) { /* user logic */ } }' },
17+
{ path: 'README.md', contents: '# My Project\nAuthentication system' }
18+
]);
19+
20+
console.log(`Newly uploaded: ${result.newlyUploaded.length}`);
21+
22+
// Ask questions about the code - files are already indexed
23+
const answer = await context.searchAndAsk(
24+
'How does the login system work?'
25+
);
26+
console.log('Answer:', answer);
27+
}
28+
29+
/**
30+
* Example 2: Persistent Index
31+
* Persist state between sessions to avoid re-indexing
32+
*/
33+
async function persistentIndexExample() {
34+
console.log('\n=== Example 2: Persistent Index ===\n');
35+
36+
// First session: Upload and save
37+
console.log('Session 1: Uploading and saving...');
38+
const context1 = await DirectContext.create();
39+
40+
await context1.addToIndex([
41+
{ path: 'src/auth.ts', contents: 'export function login() { /* auth logic */ }' },
42+
{ path: 'src/user.ts', contents: 'export class User { /* user logic */ }' },
43+
{ path: 'src/database.ts', contents: 'export function connect() { /* db connection */ }' }
44+
]);
45+
46+
// Save state for later use
47+
await context1.exportToFile('./my-project-context.json');
48+
console.log('Context saved!');
49+
50+
// Second session: Load and update
51+
console.log('\nSession 2: Loading and updating...');
52+
const context2 = await DirectContext.importFromFile('./my-project-context.json');
53+
console.log('Context loaded from previous session');
54+
55+
// Make incremental changes
56+
await context2.removeFromIndex(['src/user.ts']);
57+
await context2.addToIndex([
58+
{ path: 'src/profile.ts', contents: 'export class Profile { /* profile logic */ }' },
59+
{ path: 'src/settings.ts', contents: 'export function updateSettings() { /* settings */ }' }
60+
]);
61+
console.log('Index updated incrementally');
62+
63+
// Save updated state
64+
await context2.exportToFile('./my-project-context.json');
65+
console.log('Updated context saved!');
66+
67+
// Third session: Load and search
68+
console.log('\nSession 3: Loading and searching...');
69+
const context3 = await DirectContext.importFromFile('./my-project-context.json');
70+
console.log('Updated context loaded');
71+
72+
const answer = await context3.searchAndAsk(
73+
'What user management features are implemented?'
74+
);
75+
console.log('Answer:', answer);
76+
}
77+
78+
/**
79+
* Example 3: Batch Upload Then Wait
80+
* Optimized for multiple uploads before searching
81+
*/
82+
async function batchExample() {
83+
console.log('\n=== Example 3: Batch Upload ===\n');
84+
85+
const context = await DirectContext.create();
86+
87+
// Upload multiple batches without waiting for indexing
88+
await context.addToIndex([
89+
{ path: 'src/auth.ts', contents: 'export function login() { /* auth logic */ }' },
90+
{ path: 'src/user.ts', contents: 'export class User { /* user logic */ }' }
91+
], { waitForIndexing: false });
92+
93+
await context.addToIndex([
94+
{ path: 'src/database.ts', contents: 'export function connect() { /* db connection */ }' },
95+
{ path: 'src/api.ts', contents: 'export function createServer() { /* api logic */ }' }
96+
], { waitForIndexing: false });
97+
98+
// Wait for all files to be indexed
99+
console.log('Waiting for indexing to complete...');
100+
await context.waitForIndexing();
101+
console.log('All files indexed!');
102+
103+
// Now search - all files are guaranteed to be indexed
104+
const answer = await context.searchAndAsk(
105+
'How do the database and auth systems work together?'
106+
);
107+
console.log('Answer:', answer);
108+
}
109+
110+
/**
111+
* Example 4: External LLM Integration
112+
* Use search() results with external LLM APIs
113+
*/
114+
async function externalLLMExample() {
115+
console.log('\n=== Example 4: External LLM Integration ===\n');
116+
117+
const context = await DirectContext.create();
118+
119+
// Upload code
120+
await context.addToIndex([
121+
{ path: 'src/api.ts', contents: 'export function handleRequest() { /* API logic */ }' },
122+
{ path: 'src/auth.ts', contents: 'export function authenticate() { /* auth */ }' },
123+
{ path: 'src/database.ts', contents: 'export function query() { /* db query */ }' }
124+
]);
125+
126+
// Get formatted search results for external LLMs
127+
const codeContext = await context.search('API request handling');
128+
129+
console.log('Code context for LLM (first 500 chars):');
130+
console.log(codeContext.substring(0, 500) + '...');
131+
console.log('\nThis context can be used with Anthropic, OpenAI, or other LLM APIs');
132+
}
133+
134+
// Run all examples
135+
async function main() {
136+
try {
137+
await simpleExample();
138+
await persistentIndexExample();
139+
await batchExample();
140+
await externalLLMExample();
141+
} catch (error) {
142+
console.error('Error running examples:', error);
143+
process.exit(1);
144+
}
145+
}
146+
147+
main();
148+
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
import express from 'express';
2+
import { DirectContext } from '@augmentcode/auggie-sdk';
3+
import { readFileSync, readdirSync, statSync } from 'fs';
4+
import { join, relative } from 'path';
5+
6+
/**
7+
* File Search Server Example
8+
*
9+
* A REST API server that provides semantic file search with AI-powered summarization.
10+
*
11+
* Usage:
12+
* npm run file-search-server
13+
* curl "http://localhost:3000/search?q=typescript"
14+
*/
15+
16+
const app = express();
17+
const PORT = 3000;
18+
19+
let context: DirectContext | null = null;
20+
21+
/**
22+
* Recursively read all files from a directory
23+
*/
24+
function readFilesRecursively(dir: string, baseDir: string = dir): Array<{ path: string; contents: string }> {
25+
const files: Array<{ path: string; contents: string }> = [];
26+
27+
const entries = readdirSync(dir);
28+
29+
for (const entry of entries) {
30+
const fullPath = join(dir, entry);
31+
const stat = statSync(fullPath);
32+
33+
// Skip node_modules and hidden directories
34+
if (entry === 'node_modules' || entry.startsWith('.')) {
35+
continue;
36+
}
37+
38+
if (stat.isDirectory()) {
39+
files.push(...readFilesRecursively(fullPath, baseDir));
40+
} else if (stat.isFile()) {
41+
// Only index text files (you can customize this)
42+
const textExtensions = ['.ts', '.js', '.json', '.md', '.txt', '.yml', '.yaml'];
43+
if (textExtensions.some(ext => entry.endsWith(ext))) {
44+
try {
45+
const contents = readFileSync(fullPath, 'utf-8');
46+
// Skip files larger than 1MB
47+
if (contents.length < 1024 * 1024) {
48+
files.push({
49+
path: relative(baseDir, fullPath),
50+
contents
51+
});
52+
}
53+
} catch (error) {
54+
console.warn(`Failed to read file ${fullPath}:`, error);
55+
}
56+
}
57+
}
58+
}
59+
60+
return files;
61+
}
62+
63+
/**
64+
* Initialize the context with files from the specified directory
65+
*/
66+
async function initializeContext(directory: string) {
67+
console.log(`Indexing directory: ${directory}`);
68+
69+
context = await DirectContext.create({ debug: false });
70+
71+
const files = readFilesRecursively(directory);
72+
console.log(`Found ${files.length} files to index`);
73+
74+
const result = await context.addToIndex(files);
75+
console.log(`Indexed ${result.newlyUploaded.length} files`);
76+
77+
return context;
78+
}
79+
80+
// Middleware
81+
app.use(express.json());
82+
83+
// Routes
84+
app.get('/search', async (req, res) => {
85+
try {
86+
const query = req.query.q as string;
87+
88+
if (!query) {
89+
return res.status(400).json({ error: 'Query parameter "q" is required' });
90+
}
91+
92+
if (!context) {
93+
return res.status(503).json({ error: 'Context not initialized yet' });
94+
}
95+
96+
console.log(`Searching for: ${query}`);
97+
const results = await context.search(query);
98+
99+
res.json({
100+
query,
101+
results: results.substring(0, 2000) // Limit response size
102+
});
103+
} catch (error) {
104+
console.error('Search error:', error);
105+
res.status(500).json({ error: 'Search failed' });
106+
}
107+
});
108+
109+
app.post('/ask', async (req, res) => {
110+
try {
111+
const { searchQuery, prompt } = req.body;
112+
113+
if (!searchQuery) {
114+
return res.status(400).json({ error: 'searchQuery is required' });
115+
}
116+
117+
if (!context) {
118+
return res.status(503).json({ error: 'Context not initialized yet' });
119+
}
120+
121+
console.log(`Asking: ${searchQuery}`);
122+
const answer = await context.searchAndAsk(searchQuery, prompt);
123+
124+
res.json({
125+
searchQuery,
126+
prompt: prompt || searchQuery,
127+
answer
128+
});
129+
} catch (error) {
130+
console.error('Ask error:', error);
131+
res.status(500).json({ error: 'Ask failed' });
132+
}
133+
});
134+
135+
app.get('/health', (req, res) => {
136+
res.json({
137+
status: 'ok',
138+
contextInitialized: context !== null
139+
});
140+
});
141+
142+
// Start server
143+
async function main() {
144+
const directory = process.argv[2] || process.cwd();
145+
146+
console.log('Starting File Search Server...');
147+
await initializeContext(directory);
148+
149+
app.listen(PORT, () => {
150+
console.log(`\nServer running on http://localhost:${PORT}`);
151+
console.log(`\nTry these commands:`);
152+
console.log(` curl "http://localhost:${PORT}/search?q=typescript"`);
153+
console.log(` curl -X POST http://localhost:${PORT}/ask -H "Content-Type: application/json" -d '{"searchQuery":"package.json","prompt":"What are the dependencies?"}'`);
154+
});
155+
}
156+
157+
main().catch((error) => {
158+
console.error('Server error:', error);
159+
process.exit(1);
160+
});
161+
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { FileSystemContext } from '@augmentcode/auggie-sdk';
2+
import { fileURLToPath } from 'url';
3+
import { dirname, join } from 'path';
4+
5+
const __filename = fileURLToPath(import.meta.url);
6+
const __dirname = dirname(__filename);
7+
8+
/**
9+
* FileSystem Context Example
10+
*
11+
* Demonstrates how to search a local directory using automatic file discovery
12+
* via the MCP protocol.
13+
*/
14+
async function main() {
15+
console.log('\n=== FileSystem Context Example ===\n');
16+
17+
// Get the current directory (or specify your own)
18+
const workspaceDir = join(__dirname, '../../..');
19+
console.log(`Indexing directory: ${workspaceDir}\n`);
20+
21+
// Create FileSystemContext - automatically indexes the directory
22+
const context = await FileSystemContext.create({
23+
directory: workspaceDir,
24+
debug: false // Set to true for debug logging
25+
});
26+
27+
console.log('Directory indexed successfully!\n');
28+
29+
// Example 1: Simple search
30+
console.log('Example 1: Searching for TypeScript files...');
31+
const tsResults = await context.search('TypeScript configuration files');
32+
console.log('Search results (first 500 chars):');
33+
console.log(tsResults.substring(0, 500) + '...\n');
34+
35+
// Example 2: Search and ask
36+
console.log('Example 2: Asking about the project structure...');
37+
const answer = await context.searchAndAsk(
38+
'project structure',
39+
'What is the overall structure of this project? What are the main directories?'
40+
);
41+
console.log('Answer:', answer, '\n');
42+
43+
// Example 3: Search for specific functionality
44+
console.log('Example 3: Searching for package management...');
45+
const packageAnswer = await context.searchAndAsk(
46+
'package.json dependencies',
47+
'What are the main dependencies in this project?'
48+
);
49+
console.log('Answer:', packageAnswer, '\n');
50+
51+
// Clean up
52+
await context.close();
53+
console.log('Context closed successfully!');
54+
}
55+
56+
main().catch((error) => {
57+
console.error('Error running FileSystem Context example:', error);
58+
process.exit(1);
59+
});
60+

0 commit comments

Comments
 (0)