SDK Reference
This section provides a detailed reference for the Teckel Tracer SDK.
TeckelTracer
Class
The main class for interacting with Teckel AI.
constructor(apiKey, endpoint?)
apiKey
(string, required): Your Teckel AI API key.endpoint
(string, optional): The API endpoint to send traces to. Defaults tohttps://app.teckelai.com/api/traces
. Only specify this if you need to use a different endpoint (e.g., for testing).
trace(query, response, options)
query
(string, required): The user's question or prompt.response
(string, required): The LLM's generated answer.options
(object, required): An object containing additional information about the trace.model
(string, required): The name of the LLM used (e.g., "gpt-4o").sources
(array, optional): An array ofSourceObject
objects (see below).sessionId
(string, optional): A unique identifier for the user's session.userId
(string, optional): A unique identifier for the user (e.g., email, user ID from your system).processingTimeMs
(number, optional): The time it took to generate the response, in milliseconds.
- Returns: A promise that resolves with the
trace_id
(string) of the created trace.
SourceObject
Interface
The SourceObject
interface defines the structure for the document chunks that you send to Teckel.
Required Fields
document_name
(string, required): The name or identifier of the document (e.g., "Company Policy Manual v2.0.pdf").document_text
(string, required): The actual referenced text/chunk that was sent to the LLM.
Optional Metadata Fields
type
(string, optional): The type of the source (e.g., "document", "web_page", "pdf", "markdown").confidence
(number, optional): The retrieval confidence score from your RAG system (0-1).owner
(string, optional): The owner of the document.last_updated
(string, optional but highly recommended): An ISO 8601 string of the last update time (e.g., "2023-01-15T10:00:00Z"). This field is crucial for Teckel's freshness scoring system.
Enhanced Traceability Fields
source_uri
(string, optional): The path or URL to the source document (e.g., "https://docs.teckelai.com/sdk-reference", "s3://bucket/docs/policy.pdf").chunk_id
(string, optional): Unique identifier for this specific chunk (e.g., "doc123-chunk-42").position
(number, optional): Position or index of this chunk within the document (0-based).metadata
(object, optional): Any additional custom metadata as key-value pairs.
Example with Rich Metadata
const sources = [
{
document_name: "Refund Policy v2.0",
document_text: "Customers may request a full refund within 30 days...",
type: "policy",
confidence: 0.95,
last_updated: "2024-01-15T10:00:00Z",
source_uri: "https://docs.teckelai.com/getting-started",
chunk_id: "refund-policy-v2-chunk-3",
position: 3,
metadata: {
page: 2,
section: "Refund Eligibility",
version: "2.0",
tags: ["refund", "policy", "customer-service"]
}
}
];
Migration Example
If you're currently using basic source tracking:
// Before - Basic implementation
const sources = [{
document_name: "refund-policy.pdf",
document_text: "Full refunds are available within 30 days..."
}];
// After - Enhanced with metadata
const sources = [{
document_name: "refund-policy.pdf",
document_text: "Full refunds are available within 30 days...",
source_uri: "https://docs.teckelai.com/sdk-reference",
chunk_id: "refund-chunk-1",
position: 0,
last_updated: "2024-01-15T10:00:00Z",
metadata: {
helpCenterId: "HC-12345",
locale: "en-US"
}
}];
The enhanced metadata helps Teckel AI provide better insights about which sources your AI is using and why.
Usage Examples
Tracking User-Specific Interactions
// Example with userId for tracking specific users
const traceId = await tracer.trace(userQuery, aiResponse, {
model: 'gpt-4',
sources: retrievedDocs,
sessionId: 'session_abc123',
userId: 'user@example.com', // Track specific user across sessions
processingTimeMs: 245
});
This allows you to:
- Track individual user behavior patterns
- Analyze accuracy per user
- Identify users who frequently encounter poor responses
- Build user-specific analytics dashboards
Validation and Error Handling
The Teckel API now provides detailed validation feedback to help identify and fix integration issues.
HTTP Status Codes
200
- Success400
- Bad Request (validation errors, invalid format)401
- Unauthorized (missing or invalid API key)429
- Rate Limit Exceeded500
- Internal Server Error
Validation Error Response (400)
When validation fails, you'll receive a structured error response:
{
"error": "Validation failed with 2 error(s)",
"validation_errors": [
{
"field": "response",
"message": "response is required and must be a non-empty string"
},
{
"field": "sources[0].document_text",
"message": "document_text is required and must be a non-empty string",
"details": { "index": 0 }
}
]
}
Validation Warnings
Successful traces may include warnings about missing optional fields that could improve audit accuracy:
{
"success": true,
"trace_id": "abc-123",
"validation_warnings": [
{
"field": "sources[0].last_updated",
"message": "No last_updated date provided. Document freshness cannot be determined.",
"details": { "index": 0, "document_name": "Policy Guide" }
}
]
}
Error Handling Example
try {
const traceId = await tracer.trace(query, response, options);
console.log('Trace created:', traceId);
} catch (error) {
if (error.response?.status === 400 && error.response?.data?.validation_errors) {
// Handle validation errors
console.error('Validation errors:', error.response.data.validation_errors);
// Fix the errors based on the detailed feedback
} else if (error.response?.status === 401) {
console.error('Invalid API key');
} else if (error.response?.status === 429) {
console.error('Rate limit exceeded - try again later');
} else {
// Handle other errors
console.error('Failed to create trace:', error.message);
}
}
Limits
- Maximum 50 sources per trace
- Query limited to 10,000 characters
- Response limited to 50,000 characters
Python (HTTP API Example)
For Python applications, you can use our HTTP API directly until the Python SDK is released.
import requests
import uuid
import os
from datetime import datetime
TECKEL_API_KEY = os.environ.get("TECKEL_API_KEY")
TECKEL_API_ENDPOINT = "https://app.teckelai.com/api/traces"
def trace_with_teckel(query, response, sources, model, session_id=None, user_id=None, processing_time_ms=None):
trace_data = {
"trace_id": str(uuid.uuid4()),
"query": query,
"response": response,
"model": model,
"sources": sources,
"session_id": session_id,
"user_id": user_id,
"processing_time_ms": processing_time_ms,
"created_at": datetime.now().isoformat(),
}
headers = {
"Authorization": f"Bearer {TECKEL_API_KEY}",
"Content-Type": "application/json",
}
try:
res = requests.post(TECKEL_API_ENDPOINT, json=trace_data, headers=headers)
res.raise_for_status()
return trace_data["trace_id"]
except requests.exceptions.RequestException as e:
print(f"Failed to send trace to Teckel: {e}")
return None