Overview
Trainly provides official SDKs for JavaScript/TypeScript and Python, making it easy to integrate GraphRAG capabilities into your applications. This guide will get you up and running in 5 minutes.
Prerequisites
Before you begin, make sure you have:
Create a Chat
Create a new chat and upload some documents
Enable API Access
Go to chat settings → Enable API access → Generate API key
Install SDK
Choose your preferred SDK and follow the installation steps below
JavaScript Setup
Installation
npm install @trainly/react
The JavaScript SDK works in both Node.js and browser environments with
automatic environment detection.
Basic Usage
import { TrainlyClient } from "@trainly/react" ;
// Initialize the client
const trainly = new TrainlyClient ({
apiKey: "tk_your_api_key_here" ,
chatId: "chat_abc123" ,
});
// Ask a question
async function queryKnowledgeBase () {
const response = await trainly . query ({
question: "What are the main findings?" ,
});
console . log ( "Answer:" , response . answer );
console . log ( "Citations:" , response . context );
}
queryKnowledgeBase ();
TypeScript Support
The SDK is written in TypeScript with full type definitions:
import { TrainlyClient , QueryResponse , UploadResponse } from "@trainly/react" ;
const trainly = new TrainlyClient ({
apiKey: process . env . TRAINLY_API_KEY ! ,
chatId: process . env . TRAINLY_CHAT_ID ! ,
});
// Fully typed response
const response : QueryResponse = await trainly . query ({
question: "What is the methodology?" ,
model: "gpt-4o-mini" ,
temperature: 0.7 ,
});
// TypeScript knows all available fields
console . log ( response . answer );
console . log ( response . context [ 0 ]. score );
console . log ( response . usage . total_tokens );
Python Setup
Installation
Basic Usage
from trainly import TrainlyClient
# Initialize the client
trainly = TrainlyClient(
api_key = "tk_your_api_key_here" ,
chat_id = "chat_abc123"
)
# Ask a question
response = trainly.query(
question = "What are the main findings?"
)
print ( "Answer:" , response.answer)
print ( "Citations:" , len (response.context))
# Access context details
for i, chunk in enumerate (response.context):
print ( f "Citation [ { i } ]: { chunk.chunk_text[: 100 ] } ... (score: { chunk.score } )" )
Type Hints
The Python SDK includes full type hints for better IDE support:
from trainly import TrainlyClient, QueryResponse, ChunkScore
from typing import List
trainly = TrainlyClient(
api_key = "tk_your_api_key" ,
chat_id = "chat_abc123"
)
# Fully typed response
response: QueryResponse = trainly.query(
question = "What is the conclusion?" ,
model = "gpt-4o" ,
temperature = 0.5 ,
max_tokens = 2000
)
# Access typed fields
answer: str = response.answer
context: List[ChunkScore] = response.context
tokens: int = response.usage.total_tokens
Environment Variables
For better security, use environment variables for your credentials:
TRAINLY_API_KEY = tk_your_api_key_here
TRAINLY_CHAT_ID = chat_abc123
Quick Examples
File Upload
// Upload a file
const uploadResult = await trainly . uploadFile ({
file: "./research_paper.pdf" ,
scopeValues: {
project_id: "proj_123" ,
category: "research" ,
},
});
console . log ( "Uploaded:" , uploadResult . filename );
console . log ( "File ID:" , uploadResult . file_id );
Streaming Responses
// Stream responses in real-time
for await ( const chunk of trainly . queryStream ({
question: "Explain the methodology in detail" ,
})) {
if ( chunk . type === "content" ) {
process . stdout . write ( chunk . data );
} else if ( chunk . type === "end" ) {
console . log ( " \n\n Stream complete!" );
}
}
List Files
// Get all files in chat
const files = await trainly . listFiles ();
console . log ( `Total files: ${ files . total_files } ` );
console . log ( `Total size: ${ formatBytes ( files . total_size_bytes ) } ` );
files . files . forEach (( file ) => {
console . log ( `- ${ file . filename } ( ${ file . chunk_count } chunks)` );
});
Delete Files
// Delete a specific file
const deleteResult = await trainly . deleteFile (
"v1_user_xyz_document.pdf_1609459200" ,
);
console . log ( `Deleted ${ deleteResult . filename } ` );
console . log ( `Freed ${ formatBytes ( deleteResult . size_bytes_freed ) } ` );
V1 OAuth Authentication
For user-facing applications with OAuth:
import { TrainlyV1Client } from "@trainly/react" ;
// User authenticates with their OAuth provider
const userToken = await getUserOAuthToken (); // Your OAuth implementation
// Initialize V1 client with user's token
const trainly = new TrainlyV1Client ({
userToken: userToken ,
appId: "app_your_app_id" ,
});
// Query user's private data
const response = await trainly . query ({
messages: [{ role: "user" , content: "What is in my documents?" }],
});
console . log ( response . answer );
Error Handling
Always wrap API calls in try-catch blocks:
try {
const response = await trainly . query ({
question: "What is the conclusion?" ,
});
console . log ( response . answer );
} catch ( error ) {
if ( error . status === 429 ) {
console . error ( "Rate limit exceeded. Please wait and retry." );
} else if ( error . status === 401 ) {
console . error ( "Invalid API key" );
} else if ( error . status === 400 ) {
console . error ( "Bad request:" , error . message );
} else {
console . error ( "Error:" , error . message );
}
}
Configuration Options
Both SDKs support extensive configuration:
const trainly = new TrainlyClient ({
apiKey: "tk_your_api_key" ,
chatId: "chat_abc123" ,
// Optional configurations
baseUrl: "https://api.trainlyai.com" ,
timeout: 30000 , // 30 seconds
maxRetries: 3 ,
retryDelay: 1000 , // 1 second
// Default query options
defaultModel: "gpt-4o-mini" ,
defaultTemperature: 0.7 ,
defaultMaxTokens: 1000 ,
});
Next Steps
Getting Help
API Key Not Working
Make sure API access is enabled in chat settings
Verify the chat has published settings
Check that the API key is correct (starts with tk_)
Rate Limit Errors
Default limit is 60 requests/minute
Implement exponential backoff in your retry logic
Consider caching responses for common queries
Empty Responses
Ensure documents are uploaded and processed
Check that published settings include the right context files
Verify your question is relevant to the uploaded documents
SDK Features Comparison
Feature JavaScript Python REST API
Query Documents ✅ ✅ ✅ Streaming Responses ✅ ✅ ✅ File Upload ✅ ✅ ✅ File Management ✅ ✅ ✅ V1 OAuth Auth ✅ ✅ ✅ Scope Filtering ✅ ✅ ✅ TypeScript Types ✅ N/A N/A Type Hints N/A ✅ N/A Async/Await ✅ ✅ N/A Browser Support ✅ ❌ ✅ Retry Logic ✅ ✅ ❌ Rate Limiting ✅ ✅ ❌
Both SDKs provide the same core functionality with idiomatic APIs for their
respective languages.