Complete API reference documentation for all AI Kit packages.
AI Kit is a comprehensive framework for building AI-powered applications. It provides:
- Framework-agnostic core for streaming, agents, and state management
- React integration with hooks and pre-built components
- Built-in tools for agent capabilities
- Next.js helpers for App Router and API routes
- Testing utilities for comprehensive test coverage
Framework-agnostic core for AI Kit - streaming, agents, state management
Key Modules:
- Streaming - Real-time LLM streaming with SSE
- Agents - AI agent creation and execution
- Security - PII detection, prompt injection prevention
- Memory - Long-term memory management
- Context - Context window management
- Tracking - Usage tracking and cost monitoring
- ZeroDB - Database integration
- Authentication - AINative authentication
- Session Management - User session tracking
- RLHF - Reinforcement learning logging
- Instrumentation - Auto-instrumentation
Installation:
npm install @ainative/ai-kit-coreReact hooks and components for AI Kit
Key Features:
- Hooks -
useAIStream,useConversation - Components - Pre-built UI components
- Component Registry - Custom component registration
Installation:
npm install @ainative/ai-kit-reactQuick Start:
import { useAIStream } from '@ainative/ai-kit-react';
function Chat() {
const { messages, send, isStreaming } = useAIStream({
endpoint: '/api/chat',
model: 'gpt-4'
});
return (
<div>
{messages.map(msg => <div key={msg.id}>{msg.content}</div>)}
<button onClick={() => send('Hello!')} disabled={isStreaming}>
Send
</button>
</div>
);
}Built-in tools for AI agents
Available Tools:
- Calculator - Mathematical computations
- WebSearch - Web search integration
- CodeInterpreter - Safe code execution
- ZeroDBTool - Database CRUD operations
- ZeroDBQuery - Advanced queries
Installation:
npm install @ainative/ai-kit-toolsQuick Start:
import { Agent } from '@ainative/ai-kit-core/agents';
import { Calculator, WebSearch } from '@ainative/ai-kit-tools';
const agent = new Agent({
name: 'Assistant',
description: 'Helpful assistant',
tools: [Calculator, WebSearch],
llm: {
provider: 'openai',
model: 'gpt-4',
apiKey: process.env.OPENAI_API_KEY
}
});Next.js integration for AI Kit
Features:
- Route helpers for App Router
- SSE streaming utilities
- Authentication middleware
- Rate limiting middleware
Installation:
npm install @ainative/ai-kit-nextjsQuick Start:
// app/api/chat/route.ts
import { createStreamingResponse } from '@ainative/ai-kit-nextjs';
import { OpenAI } from 'openai';
export async function POST(req: Request) {
const { messages } = await req.json();
const openai = new OpenAI();
const completion = await openai.chat.completions.create({
model: 'gpt-4',
messages,
stream: true
});
return createStreamingResponse(completion);
}Testing utilities for AI Kit
Features:
- Mock LLM responses and streams
- Mock agents and tools
- Pre-built test fixtures
- Custom Jest/Vitest matchers
Installation:
npm install -D @ainative/ai-kit-testingQuick Start:
import { mockAIStream, expect } from '@ainative/ai-kit-testing';
it('should handle streaming', async () => {
const stream = mockAIStream({
messages: ['Hello', ' world']
});
const result = await processStream(stream);
expect(result).toMatchStreamOutput('Hello world');
});- AIStream - Client-side streaming
- StreamingResponse - Server-side SSE
- useAIStream Hook - React streaming hook
- Next.js Streaming - App Router integration
- Agent - Agent creation
- AgentExecutor - Execute agent tasks
- StreamingAgentExecutor - Stream agent responses
- AgentSwarm - Multi-agent orchestration
- Tools - Built-in tools
- PIIDetector - PII detection and redaction
- PromptInjectionDetector - Injection prevention
- ContentModerator - Content moderation
- JailbreakDetector - Jailbreak detection
- Memory - Long-term memory
- Context Management - Context windows
- Session Management - User sessions
- Conversation Store - Conversation persistence
- Usage Tracking - Token and cost tracking
- RLHF Logging - Feedback collection
- Instrumentation - Auto-instrumentation
- Monitoring - Query monitoring
- Reporting - Usage reports
- Set up streaming endpoint
- Use React hook
- Add conversation persistence
- Implement security checks
- Track usage
import { useAIStream } from '@ainative/ai-kit-react';
import { PIIDetector } from '@ainative/ai-kit-core/security';
function SecureChat() {
const piiDetector = new PIIDetector();
const { messages, send } = useAIStream({
endpoint: '/api/chat',
model: 'gpt-4',
onToken: (token) => console.log('Token:', token)
});
const handleSend = (input: string) => {
// Check for PII before sending
const result = piiDetector.detect(input);
if (result.containsPII) {
console.warn('PII detected:', result.detectedTypes);
// Use redacted version
send(result.redacted);
} else {
send(input);
}
};
return (
<div>
{messages.map(msg => <div key={msg.id}>{msg.content}</div>)}
<input onKeyPress={(e) => {
if (e.key === 'Enter') handleSend(e.target.value);
}} />
</div>
);
}import { Agent, AgentExecutor } from '@ainative/ai-kit-core/agents';
import { Calculator, WebSearch } from '@ainative/ai-kit-tools';
import { UsageTracker } from '@ainative/ai-kit-core/tracking';
const tracker = new UsageTracker();
const agent = new Agent({
name: 'ResearchAssistant',
description: 'Helps with research and calculations',
tools: [Calculator, WebSearch],
llm: {
provider: 'openai',
model: 'gpt-4',
apiKey: process.env.OPENAI_API_KEY
}
});
const executor = new AgentExecutor(agent);
const result = await executor.execute('What is 15% of the GDP of France?');
// Track usage
await tracker.trackSuccess({
model: 'gpt-4',
promptTokens: result.trace.usage.promptTokens,
completionTokens: result.trace.usage.completionTokens,
durationMs: result.trace.durationMs
});
console.log('Result:', result.response);
console.log('Cost:', await tracker.getAggregated().totalCost);import { AgentSwarm } from '@ainative/ai-kit-core/agents';
import { Calculator, WebSearch, ZeroDBTool } from '@ainative/ai-kit-tools';
const researcher = new Agent({
name: 'Researcher',
tools: [WebSearch, ZeroDBTool],
llm: { provider: 'openai', model: 'gpt-4', apiKey: process.env.OPENAI_API_KEY }
});
const analyst = new Agent({
name: 'Analyst',
tools: [Calculator],
llm: { provider: 'openai', model: 'gpt-4', apiKey: process.env.OPENAI_API_KEY }
});
const swarm = new AgentSwarm({
agents: [researcher, analyst],
communicationMode: 'sequential'
});
const result = await swarm.execute(
'Research the GDP of top 5 countries and calculate the average'
);All AI Kit packages are written in TypeScript and include complete type definitions.
import type {
// Core types
AIStreamConfig,
AgentConfig,
ToolDefinition,
Message,
Usage,
// Security types
PIIDetectionResult,
ModerationResult,
// Memory types
MemoryRecord,
FactExtraction,
// Tracking types
UsageRecord,
AggregatedUsage
} from '@ainative/ai-kit-core';Common environment variables used across AI Kit:
# LLM Providers
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
# AINative Platform
AINATIVE_API_KEY=ain_...
# ZeroDB
ZERODB_PROJECT_ID=proj_...
ZERODB_API_KEY=zdb_...
# Web Search (optional)
SERPER_API_KEY=...
BING_API_KEY=...
# Redis (optional)
REDIS_URL=redis://...// app/api/chat/route.ts
import { createStreamingResponse } from '@ainative/ai-kit-nextjs';
export async function POST(req: Request) { /* ... */ }import { StreamingResponse } from '@ainative/ai-kit-core/streaming';
app.post('/api/chat', async (req, res) => {
const stream = new StreamingResponse(res);
// ...
});import { useAIStream } from '@ainative/ai-kit-react';
function Chat() { /* ... */ }import { createAIStream } from '@ainative/ai-kit-vue';- Always handle errors gracefully
- Use streaming for better UX
- Implement security by default
- Track usage and costs
- Test with mocks and fixtures
- Use TypeScript for type safety
- Monitor performance and usage
- Implement retry logic
- Clean up resources on unmount
- Validate inputs before processing
See the examples directory for complete, working examples:
- Basic Chat
- Agent with Tools
- Security Pipeline
- Multi-Agent System
- Next.js Integration
- React Components
See CONTRIBUTING.md for guidelines on contributing to AI Kit.
MIT - See LICENSE for details.
See CHANGELOG.md for version history and updates.