Lobe Chat APIs: Complete Guide to Available tRPC Endpoints and Routers
Lobe Chat exposes a comprehensive set of tRPC-based APIs organized into domain-specific routers under src/server/routers/lambda, covering chat completions, agent runtime, file management, and user settings, all accessible via /api/trpc/* endpoints.
The lobehub/lobe-chat repository implements a modern, type-safe API layer using tRPC that powers its Next.js frontend and enables external integrations. These Lobe Chat APIs are structured as modular routers handling everything from AI chat completions to knowledge base management, with all procedures automatically mapped to HTTP endpoints under /api/trpc/.
Core AI and Chat APIs
The AI-centric routers manage model providers, agent execution, and real-time chat completions.
AI Chat Router
Located in [/src/server/routers/lambda/aiChat.ts](https://github.com/lobehub/lobe-chat/blob/canary/src/server/routers/lambda/aiChat.ts), the aiChatRouter handles streaming chat completions and structured output generation.
Key procedures include:
outputJSON– Generates structured JSON responses from AI modelssendMessageInServer– Processes chat messages server-side, handling tool calls and streaming
AI Agent Router
The aiAgentRouter manages agent lifecycle and runtime execution, enabling creation, configuration, and invocation of AI agents with tool-calling capabilities.
Model and Provider Management
aiModelRouter([/src/server/routers/lambda/aiModel.ts](https://github.com/lobehub/lobe-chat/blob/canary/src/server/routers/lambda/aiModel.ts)) – CRUD operations for AI models, provider model listing, and model orderingaiProviderRouter([/src/server/routers/lambda/aiProvider.ts](https://github.com/lobehub/lobe-chat/blob/canary/src/server/routers/lambda/aiProvider.ts)) – Configuration of AI providers (OpenAI, Anthropic, etc.), enabling/disabling providers, and credential management
Data Management APIs
These routers handle the core conversation data structures: messages, topics (conversations), sessions, and threads.
Message Router
The messageRouter in /src/server/routers/lambda/message.ts provides comprehensive message lifecycle management:
createMessage– Create new messages with content and metadataaddFilesToMessage– Attach files to existing messagesupdate– Modify message content or propertiesremoveMessage– Delete messages by IDsearchMessages– Full-text search across conversation history
Topic and Session Management
topicRouter([/src/server/routers/lambda/topic.ts](https://github.com/lobehub/lobe-chat/blob/canary/src/server/routers/lambda/topic.ts)) – Manages conversation containers including creation, deletion, listing, sharing, and migration helpers for legacy sessionssessionRouter([/src/server/routers/lambda/session.ts](https://github.com/lobehub/lobe-chat/blob/canary/src/server/routers/lambda/session.ts)) – Session enumeration and paginationthreadRouter([/src/server/routers/lambda/thread.ts](https://github.com/lobehub/lobe-chat/blob/canary/src/server/routers/lambda/thread.ts)) – Thread hierarchy management within topics
User and File APIs
User Management
The userRouter handles user profiles and preferences:
getState– Retrieve current user state and settingsupdateAvatar– Upload and update user avatars (stores in S3)updateUsername– Modify display nameupdatePreferences– Update user preferences and settingsgetSubscriptionInfo– Retrieve subscription status
File and API Key Management
fileRouter([/src/server/routers/lambda/file.ts](https://github.com/lobehub/lobe-chat/blob/canary/src/server/routers/lambda/file.ts)) – File upload, download, deletion, and presigned URL generation for S3 storageapiKeyRouter([/src/server/routers/lambda/apiKey.ts](https://github.com/lobehub/lobe-chat/blob/canary/src/server/routers/lambda/apiKey.ts)) – Creation, listing, enabling, and disabling of API keys for external access
Advanced Feature APIs
Generation and Media
The generationRouter manages image and video generation:
create– Initiate generation jobs (images, videos)createBatch– Batch processing for multiple generationscreateTopic– Topic-specific generation contexts
Supported providers include Stability AI, OpenAI DALL-E, and other image generation services.
Knowledge Base and RAG
knowledgeBaseRouter([/src/server/routers/lambda/knowledgeBase.ts](https://github.com/lobehub/lobe-chat/blob/canary/src/server/routers/lambda/knowledgeBase.ts)) – Import/export of knowledge bases, document management for RAG pipelinesragEvalRouter– Evaluation metrics for retrieval-augmented generation quality
Marketplace and Sharing
marketRouter([/src/server/routers/lambda/market.ts](https://github.com/lobehub/lobe-chat/blob/canary/src/server/routers/lambda/market.ts)) – Browse, install, and configure built-in tools and agents from the marketplaceshareRouter([/src/server/routers/lambda/share.ts](https://github.com/lobehub/lobe-chat/blob/canary/src/server/routers/lambda/share.ts)) – Create and manage public share links for topics and conversationsusageRouter– Usage statistics and analytics
How to Call Lobe Chat APIs
All Lobe Chat APIs are exposed via tRPC and accessible through HTTP endpoints at /api/trpc/<routerName>.<procedureName>. The project provides a type-safe client for consumption.
Setting up a tRPC Client
Create a client instance using the official tRPC setup:
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '@/server/routers/lambda';
export const trpc = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: '/api/trpc',
}),
],
});
Sending Chat Messages
Use the aiChat router to process messages server-side:
import { trpc } from '@/libs/trpc/client';
async function sendMessage({
agentId,
sessionId,
topicId,
content,
}: {
agentId: string;
sessionId?: string;
topicId: string;
content: string;
}) {
const response = await trpc.aiChat.sendMessageInServer.mutate({
agentId,
sessionId,
topicId,
newUserMessage: {
content,
files: [],
},
newAssistantMessage: {
model: 'gpt-4o-mini',
provider: 'openai',
},
});
console.log('Assistant message ID:', response.assistantMessageId);
return response;
}
Managing Conversations and Topics
Create and retrieve conversation containers:
// Create a new topic
async function createTopic(title: string, agentId: string) {
const topicId = await trpc.topic.createTopic.mutate({
title,
agentId,
});
return topicId;
}
// List recent topics with auto-migration support
async function loadRecentTopics(limit = 12) {
const recent = await trpc.topic.recentTopics.query({ limit });
return recent;
}
File and User Operations
Handle file uploads and profile updates:
// Update user avatar (stores in S3)
async function updateAvatar(base64Image: string) {
await trpc.user.updateAvatar.mutate(base64Image);
}
// Generate images via AI providers
async function generateImage(prompt: string) {
const job = await trpc.generation.create.mutate({
provider: 'stability',
model: 'stable-diffusion-xl',
prompt,
});
return job.id;
}
Summary
Lobe Chat provides a comprehensive tRPC-based API architecture exposing over 20 domain-specific routers. Key takeaways include:
- Architecture: All APIs are implemented as tRPC procedures in
src/server/routers/lambda, automatically exposed at/api/trpc/<router>.<procedure> - Core Functionality: Primary routers include
aiChatfor completions,messagefor content management, andtopicfor conversation organization - Type Safety: The
@/libs/trpcclient provides end-to-end TypeScript safety for all API interactions - Extensibility: Modular router design allows easy extension of functionality via additional tRPC routers in the lambda directory
Frequently Asked Questions
What protocol does Lobe Chat use for its APIs?
Lobe Chat uses tRPC (TypeScript RPC) as its primary API protocol. This provides end-to-end type safety between the client and server, with all procedures automatically mapped to HTTP endpoints under /api/trpc/. The implementation uses @trpc/client for browser consumption and @trpc/server for the backend routers defined in src/server/routers/lambda.
How are Lobe Chat API endpoints structured?
Endpoints follow the pattern /api/trpc/<routerName>.<procedureName>, where routerName corresponds to the tRPC router (e.g., aiChat, topic, user) and procedureName is the specific query or mutation (e.g., sendMessageInServer, createTopic). All routers are composed in src/server/routers/lambda/index.ts, which exports the AppRouter type used for client-side type inference.
Can external applications integrate with Lobe Chat APIs?
Yes, external applications can integrate by consuming the tRPC endpoints directly or using the provided client utilities. The type-safe client setup in src/libs/trpc can be instantiated in external TypeScript applications by importing the AppRouter type. For non-TypeScript consumers, standard HTTP POST requests to /api/trpc/* with JSON payloads conforming to the Zod schemas defined in each router are supported.
Where are the API schemas and routers defined in the source code?
All API routers are defined in src/server/routers/lambda/, with each domain having its own file (e.g., aiChat.ts, message.ts, topic.ts). The root router composition happens in src/server/routers/lambda/index.ts, which aggregates all domain routers into the single AppRouter type. Input and output schemas use Zod validation, typically imported from @lobechat/types or defined inline in each router file.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →