Graphlit TypeScript Client SDK
The official TypeScript/JavaScript SDK for the Graphlit Platform - build AI-powered applications with knowledge retrieval in minutes.
🚀 What is Graphlit?
Graphlit is a cloud platform that handles the complex parts of building AI applications:
- Ingest any content - PDFs, websites, audio, video, and more
- Chat with your data - Using RAG (Retrieval-Augmented Generation)
- Extract insights - Summaries, entities, and metadata
- Build knowledge graphs - Automatically connect related information
What's New
OpenAI Responses API Support
- Automatic Responses API Routing - GPT-5.4 and eligible OpenAI models are automatically routed through the OpenAI Responses API for improved intelligence, fewer reasoning tokens, higher cache hit rates, and lower latency. Disable with
useResponsesApi: false in StreamAgentOptions.
- Reasoning Effort - Reasoning effort (e.g.
medium, high) is read from the specification's openAI.reasoningEffort field and passed through to the Responses API.
- GPT-5.4 Temperature Handling - Temperature is only sent when reasoning effort is
none (the GPT-5.4 default). Other reasoning levels don't support temperature per the OpenAI docs.
phase on Assistant Messages - Conversation history replayed to the Responses API includes phase: "commentary" on assistant messages that preceded tool calls, and phase: "final_answer" on terminal messages, per GPT-5.4 best practices.
- Tool Call ID Remapping - Tool call IDs are automatically remapped between
call_ (Chat Completions) and fc_ (Responses API) formats, enabling mid-conversation model switches without errors.
- First-Round Tool Engagement - When tools are provided, the SDK sends
tool_choice: "required" on the first API request to ensure the model engages with available tools, then reverts to auto for subsequent rounds. This addresses GPT-5.4's tendency to skip tool use under the default auto setting. This behavior is internal to the Responses API path and not exposed as a caller option.
Streaming Provider Resilience
- Automatic Retry for Provider Errors -
streamAgent and runAgent now retry transient LLM provider errors (HTTP 500, 503, 429, network failures) with exponential backoff (up to 3 retries)
ProviderError Class - Normalized, typed error class across all 10 streaming providers with provider, statusCode, retryable, and requestId fields
- Structured
recoverable Flag - Error events now accurately indicate whether an error is transient, enabling smarter application-level retry logic
- No More Duplicate Error Events - Fixed providers that were emitting both an error event and throwing, causing duplicate error handling
v1.6.0 - Agent Framework
- Agent Entity - First-class agent lifecycle management
runAgent() Method - Autonomous agent harness with built-in stuck detection and turn evaluation
- Skills API - Define and manage reusable agent skills
- Agent Scratchpad - Persistent scratchpad for agents and conversations
- Optimized Reasoning Streaming - More efficient streaming of reasoning/thinking updates
- Node.js 20+ Required - Minimum Node.js version bumped from 18 to 20
v1.5.0 - Streaming & Context Management 🎛️
- Context Management - Token windowing for
streamAgent and promptAgent to handle large conversations
- Artifact Collection - Collect and track artifacts generated during agent streaming
- Conversation Queueing - Queue multiple prompts in
streamAgent for sequential processing
- Thinking Storage - LLM thinking/reasoning responses now tracked and stored across turns
- Better Abort Handling - Improved cancellation cleanup in
streamAgent
- Partial Error Responses - Graceful degradation when API returns partial data with errors
- BREAKING: Renamed
distributeContents() to distribute()
v1.4.0 - Knowledge Graph & Platform Enhancements 🔍
- Knowledge Graph Queries - New
queryGraph and queryFactsGraph methods for graph traversal
- Expanded Entity Queries - Richer entity detail retrieval with
lookupEntity and expanded query variants
- Conversation Clusters - Group and query related conversations
- Optional dotenv -
dotenv is no longer a required dependency
- Partial Error Handling - SDK now surfaces partial data instead of throwing on mixed responses
- JSDoc Documentation - Client methods now include inline documentation
v1.3.0 - Google SDK Migration 🔄
- BREAKING CHANGE: Migrated from deprecated
@google/generative-ai to new @google/genai SDK
- Improved Thinking Support - Better detection of Google Gemini thinking/reasoning with proper
part.thought API
- Enhanced Streaming - More reliable streaming with the new Google SDK
- Migration Required - See Migration Guide below
v1.2.0 - Reasoning & Cancellation Support 🧠
- Reasoning/Thinking Detection - See how AI models think through problems (Bedrock Nova, Deepseek, Anthropic)
- Stream Cancellation - Stop long-running generations instantly with AbortSignal support
- Enhanced Streaming Events - New
reasoning_update events expose model thought processes
v1.1.0 - Streaming & Resilience
- Real-time streaming - Watch AI responses appear word-by-word across 9 different providers
- Tool calling - Let AI execute functions and retrieve data
- Extended provider support - Native streaming integration with OpenAI, Anthropic, Google, Groq, Cerebras, Cohere, Mistral, AWS Bedrock, and Deepseek
- Better performance - Optimized streaming with provider-specific SDKs
- Network resilience - Automatic retry logic for transient failures
📋 Table of Contents
Quick Start
Get started in 2 minutes:
# Install the SDK
npm install graphlit-client
# Set your credentials (get free account at https://portal.graphlit.dev)
export GRAPHLIT_ORGANIZATION_ID=your_org_id
export GRAPHLIT_ENVIRONMENT_ID=your_env_id
export GRAPHLIT_JWT_SECRET=your_secret
import { Graphlit, Types } from "graphlit-client";
const client = new Graphlit(); // Uses env vars: GRAPHLIT_ORGANIZATION_ID, GRAPHLIT_ENVIRONMENT_ID, GRAPHLIT_JWT_SECRET
// First, create a specification (or use your project default)
const spec = await client.createSpecification({
name: "Assistant",
type: Types.SpecificationTypes.Completion,
serviceType: Types.ModelServiceTypes.OpenAi,
openAI: {
model: Types.OpenAiModels.Gpt4O_128K,
},
});
// Start chatting with AI
await client.streamAgent(
"Tell me a joke",
(event) => {
if (event.type === "message_update") {
console.log(event.message.message);
}
},
undefined, // conversationId (optional)
{ id: spec.createSpecification.id }, // specification
);
Installation
npm install graphlit-client
Want Real-time Streaming?
Install the LLM SDK for streaming responses:
# For OpenAI streaming
npm install openai
# For Anthropic streaming
npm install @anthropic-ai/sdk
# For Google streaming
npm install @google/genai
# For Groq streaming (OpenAI-compatible)
npm install groq-sdk
# For Cerebras streaming (OpenAI-compatible)
npm install openai
# For Cohere streaming
npm install cohere-ai
# For Mistral streaming
npm install @mistralai/mistralai
# For AWS Bedrock streaming (Claude models)
npm install @aws-sdk/client-bedrock-runtime
# For Deepseek streaming (OpenAI-compatible)
npm install openai
Setting Up
Create a .env file in your project:
GRAPHLIT_ORGANIZATION_ID=your_org_id
GRAPHLIT_ENVIRONMENT_ID=your_env_id
GRAPHLIT_JWT_SECRET=your_secret
# Optional: For streaming with specific providers
OPENAI_API_KEY=your_key
ANTHROPIC_API_KEY=your_key
GOOGLE_API_KEY=your_key
# Additional streaming providers
GROQ_API_KEY=your_key # For Groq models (Llama, Mixtral)
CEREBRAS_API_KEY=your_key # For Cerebras models
COHERE_API_KEY=your_key # For Cohere Command models
MISTRAL_API_KEY=your_key # For Mistral models
DEEPSEEK_API_KEY=your_key # For Deepseek models
# For AWS Bedrock streaming (requires AWS credentials)
AWS_REGION=us-east-2
AWS_ACCESS_KEY_ID=your_key
AWS_SECRET_ACCESS_KEY=your_secret
Migrating from @google/generative-ai
⚠️ Breaking Change in v1.3.0
The deprecated @google/generative-ai SDK has been replaced with the new @google/genai SDK. This change provides better thinking/reasoning support and improved streaming reliability.
Migration Steps
- Update your dependencies:
# Remove old SDK
npm uninstall @google/generative-ai
# Install new SDK
npm install @google/genai
- Update your client initialization:
// Old (deprecated)
import { GoogleGenerativeAI } from "@google/generative-ai";
const googleClient = new GoogleGenerativeAI(apiKey);
client.setGoogleClient(googleClient);
// New
import { GoogleGenAI } from "@google/genai";
const googleClient = new GoogleGenAI({ apiKey });
client.setGoogleClient(googleClient);
- No other code changes required!
- The Graphlit SDK handles all the API differences internally
- Your existing specifications and conversations will continue to work
- Thinking/reasoning detection is now more reliable with proper
part.thought support
Why the Migration?
- The
@google/generative-ai SDK is deprecated by Google
- New SDK provides better support for Gemini 2.x features including thinking mode
- Improved streaming performance and reliability
- Proper detection of thought parts without markdown parsing hacks
Benefits
- Better Thinking Detection: Properly detects and separates thinking content using Google's official API
- Improved Performance: More efficient streaming with the new SDK architecture
- Future-Proof: Ensures compatibility with upcoming Gemini models and features
- Cleaner API: Simplified configuration and better TypeScript types
Reasoning Support (New!) 🧠
The SDK can detect and expose AI reasoning processes, showing you how models "think" through problems. This feature works with models that support reasoning output.
Quick Example
await client.streamAgent(
"What's 15% of 240? Think step by step.",
(event) => {
if (event.type === "reasoning_update") {
console.log("🤔 Model thinking:", event.content);
} else if (event.type === "message_update") {
console.log("💬 Answer:", event.message.message);
}
},
undefined,
{ id: specificationId },
);
Supported Models
| Provider |
Models |
Format |
Example Output |
| AWS Bedrock |
Nova Premier |
thinking_tag |
<thinking>Let me calculate...</thinking> |
| Deepseek |
Chat, Reasoner |
markdown |
**Step 1:** First, I need to... |
| Anthropic |
Claude (with special access) |
thinking_tag |
Internal thinking blocks |
Using Reasoning Detection
// Create a specification with a reasoning-capable model
const spec = await client.createSpecification({
name: "Reasoning Assistant",
serviceType: Types.ModelServiceTypes.Bedrock,
bedrock: {
model: Types.BedrockModels.NovaPremier,
temperature: 0.7,
},
});
// Track reasoning steps
const reasoningSteps: string[] = [];
await client.streamAgent(
"Analyze the pros and cons of remote work. Think carefully.",
(event) => {
switch (event.type) {
case "reasoning_update":
// Capture model's thinking process
reasoningSteps.push(event.content);
console.log(`🧠 Thinking (${event.format}):`, event.content);
if (event.isComplete) {
console.log("✅ Reasoning complete!");
}
break;
case "message_update":
// The actual answer (reasoning removed)
console.log("Answer:", event.message.message);
break;
}
},
undefined,
{ id: spec.createSpecification!.id },
);
Key Features
- Automatic Detection: Reasoning content is automatically detected and separated
- Format Preservation: Maintains original formatting (markdown, tags, etc.)
- Real-time Streaming: Reasoning streams as it's generated
- Clean Separation