SDK/TypeScript
TypeScript SDK
The official TypeScript/JavaScript SDK for Engrami. Build type-safe AI agents with full IntelliSense support.
Installation
Install the Engrami TypeScript SDK using npm, yarn, or pnpm:
# npm
npm install @engrami/sdk
# yarn
yarn add @engrami/sdk
# pnpm
pnpm add @engrami/sdkRequirements
- Node.js 18 or higher
- TypeScript 5.0+ (for TypeScript users)
- An Engrami API key
Quick Start
Initialize the Client
import { EngramiClient } from '@engrami/sdk';
// Initialize with API key
const client = new EngramiClient({
apiKey: 'your-api-key',
});
// Or use environment variable ENGRAMI_API_KEY
const client = new EngramiClient();Create an Agent
// Create a data analyst agent
const agent = await client.agents.create({
name: 'Data Analyst',
type: 'analyst',
description: 'Analyzes data and provides insights',
memoryTypes: ['semantic', 'procedural'],
config: {
model: 'gpt-4-turbo',
temperature: 0.3,
capabilities: ['data_analysis', 'visualization'],
},
});
console.log(`Created agent: ${agent.id}`);Chat with an Agent
// Send a message and get a response
const response = await agent.chat({
message: 'Analyze the sales trends for Q4',
sessionId: 'user-123', // Optional: for conversation continuity
});
console.log(response.content);
console.log(`Tokens used: ${response.usage.totalTokens}`);Type Definitions
The SDK comes with comprehensive TypeScript definitions for full type safety.
import type {
Agent,
AgentConfig,
ChatResponse,
MemoryType,
Workflow,
WorkflowNode,
} from '@engrami/sdk';
// Fully typed agent configuration
const config: AgentConfig = {
model: 'gpt-4-turbo',
temperature: 0.7,
maxTokens: 4096,
personality: 'helpful and concise',
};
// Type-safe agent creation
const agent: Agent = await client.agents.create({
name: 'My Agent',
type: 'assistant',
config,
});Streaming Responses
Get real-time streaming responses for a better user experience.
// Stream a chat response
const stream = await agent.chatStream({
message: 'Write a detailed analysis of market trends',
});
for await (const chunk of stream) {
process.stdout.write(chunk.content);
}
// In React/Browser
const stream = await agent.chatStream({ message: 'Hello!' });
for await (const chunk of stream) {
setResponse(prev => prev + chunk.content);
}Memory Operations
// Add knowledge to semantic memory
await client.memory.add({
agentId: 'agent-id',
memoryType: 'semantic',
content: 'Q4 revenue exceeded projections by 15%',
metadata: {
category: 'financial',
quarter: 'Q4',
year: 2024,
},
});
// Search memory
const results = await client.memory.search({
agentId: 'agent-id',
memoryType: 'semantic',
query: 'Q4 revenue',
topK: 5,
});
results.forEach(result => {
console.log(`Score: ${result.score}, Content: ${result.content}`);
});
// Clear memory
await client.memory.clear({
agentId: 'agent-id',
memoryType: 'episodic',
});Workflows
// Create a workflow
const workflow = await client.workflows.create({
name: 'Data Pipeline',
description: 'Process and analyze incoming data',
nodes: [
{
id: 'start',
type: 'trigger',
config: { triggerType: 'schedule', cron: '0 9 * * *' },
},
{
id: 'fetch',
type: 'agent',
config: { agentId: 'data-fetcher-id' },
},
{
id: 'analyze',
type: 'agent',
config: { agentId: 'analyst-id' },
},
{
id: 'notify',
type: 'integration',
config: { integration: 'slack', channel: '#reports' },
},
],
edges: [
{ source: 'start', target: 'fetch' },
{ source: 'fetch', target: 'analyze' },
{ source: 'analyze', target: 'notify' },
],
});
// Execute a workflow manually
const execution = await client.workflows.execute({
workflowId: workflow.id,
input: { date: '2024-01-15' },
});
console.log(`Execution ID: ${execution.id}`);
console.log(`Status: ${execution.status}`);Error Handling
import {
EngramiError,
AuthenticationError,
RateLimitError,
NotFoundError,
ValidationError,
} from '@engrami/sdk';
try {
const agent = await client.agents.get('non-existent-id');
} catch (error) {
if (error instanceof NotFoundError) {
console.log('Agent not found');
} else if (error instanceof AuthenticationError) {
console.log('Invalid API key');
} else if (error instanceof RateLimitError) {
console.log(`Rate limited. Retry after ${error.retryAfter} seconds`);
} else if (error instanceof EngramiError) {
console.log(`API error: ${error.message}`);
}
}React Integration
import { EngramiProvider, useAgent, useChat } from '@engrami/react';
// Wrap your app with the provider
function App() {
return (
<EngramiProvider apiKey="your-api-key">
<ChatComponent />
</EngramiProvider>
);
}
// Use hooks in your components
function ChatComponent() {
const { agent, loading } = useAgent('agent-id');
const { messages, sendMessage, isStreaming } = useChat(agent);
const handleSend = async (text: string) => {
await sendMessage(text);
};
return (
<div>
{messages.map(msg => (
<div key={msg.id}>{msg.content}</div>
))}
<input onSubmit={handleSend} disabled={isStreaming} />
</div>
);
}Full API Reference
See the complete API reference for all available methods and options.