Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat: custom providers
Louisee8ae3c4fdeb
diff --git a/web-app/package.json b/web-app/package.jsonindex 9824d00df..1cc792a57 100644--- a/web-app/package.json+++ b/web-app/package.json@@ -18,6 +18,8 @@"build:serve:web": "yarn build:web && yarn serve:web"},"dependencies": {+ "@ai-sdk/anthropic": "^2.0.0",+ "@ai-sdk/google": "^2.0.0","@ai-sdk/openai-compatible": "^1.0.28","@ai-sdk/react": "^2.0.109","@dnd-kit/core": "6.3.1",diff --git a/web-app/src/components/PromptProgress.tsx b/web-app/src/components/PromptProgress.tsxindex 3d25f6a05..a2d0f2b5e 100644--- a/web-app/src/components/PromptProgress.tsx+++ b/web-app/src/components/PromptProgress.tsx@@ -1,4 +1,5 @@import { useAppState } from '@/hooks/useAppState'+import { Loader } from 'lucide-react'export function PromptProgress() {const promptProgress = useAppState((state) => state.promptProgress)@@ -15,7 +16,7 @@ export function PromptProgress() {promptProgress.total <= 0 ||percentage >= 100) {- return null+ return <Loader className="animate-spin w-4 h-4" />}return (diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex f556994b9..65b77bcec 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -454,7 +454,7 @@ const ChatInput = ({// Focus when streaming content finishesuseEffect(() => {- if (chatStatus !== 'streaming' && textareaRef.current) {+ if (chatStatus !== 'submitted' && textareaRef.current) {// Small delay to ensure UI has updatedsetTimeout(() => {textareaRef.current?.focus()@@ -1254,16 +1254,18 @@ const ChatInput = ({// If hasMmproj is false or no images found, allow normal text pasting to continue}+ const isStreaming = chatStatus === 'submitted' || chatStatus === 'streaming'+return (<div className="relative"><div className="relative"><divclassName={cn('relative overflow-hidden p-[2px] rounded-3xl',- chatStatus === 'streaming' && 'opacity-70'+ isStreaming && 'opacity-70')}>- {chatStatus === 'streaming' && (+ {isStreaming && (<div className="absolute inset-0"><MovingBorder rx="10%" ry="10%"><div@@ -1415,7 +1417,7 @@ const ChatInput = ({// - The streaming content has finished// - Prompt is not emptyif (- chatStatus !== 'streaming' &&+ !isStreaming &&prompt.trim() &&!ingestingAny) {@@ -1446,7 +1448,7 @@ const ChatInput = ({<divclassName={cn('px-1 flex items-center w-full gap-1',- chatStatus === 'streaming' && 'opacity-50 pointer-events-none'+ isStreaming && 'opacity-50 pointer-events-none')}>{/* Dropdown for attachments */}@@ -1701,7 +1703,7 @@ const ChatInput = ({</div>)}- {chatStatus === 'streaming' ? (+ {isStreaming ? (<Buttonvariant="destructive"size="icon"diff --git a/web-app/src/lib/__tests__/model-factory.test.ts b/web-app/src/lib/__tests__/model-factory.test.tsnew file mode 100644index 000000000..ade6f88f1--- /dev/null+++ b/web-app/src/lib/__tests__/model-factory.test.ts@@ -0,0 +1,127 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { ModelFactory } from '../model-factory'+import type { ProviderObject } from '@janhq/core'++// Mock the Tauri invoke function+vi.mock('@tauri-apps/api/core', () => ({+ invoke: vi.fn(),+}))++// Mock the AI SDK providers+vi.mock('@ai-sdk/openai-compatible', () => ({+ createOpenAICompatible: vi.fn(() => ({+ languageModel: vi.fn(() => ({ type: 'openai-compatible' })),+ })),+}))++vi.mock('@ai-sdk/anthropic', () => ({+ createAnthropic: vi.fn(() => vi.fn(() => ({ type: 'anthropic' }))),+}))++vi.mock('@ai-sdk/google', () => ({+ createGoogleGenerativeAI: vi.fn(() => vi.fn(() => ({ type: 'google' }))),+}))++describe('ModelFactory', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('createModel', () => {+ it('should create an Anthropic model for anthropic provider', async () => {+ const provider: ProviderObject = {+ provider: 'anthropic',+ api_key: 'test-api-key',+ base_url: 'https://api.anthropic.com/v1',+ models: [],+ settings: [],+ active: true,+ custom_header: [+ { header: 'anthropic-version', value: '2023-06-01' },+ ],+ }++ const model = await ModelFactory.createModel('claude-3-opus', provider)+ expect(model).toBeDefined()+ expect(model.type).toBe('anthropic')+ })++ it('should create a Google model for google provider', async () => {+ const provider: ProviderObject = {+ provider: 'google',+ api_key: 'test-api-key',+ base_url: 'https://generativelanguage.googleapis.com/v1',+ models: [],+ settings: [],+ active: true,+ }++ const model = await ModelFactory.createModel('gemini-pro', provider)+ expect(model).toBeDefined()+ expect(model.type).toBe('google')+ })++ it('should create a Google model for gemini provider', async () => {+ const provider: ProviderObject = {+ provider: 'gemini',+ api_key: 'test-api-key',+ base_url: 'https://generativelanguage.googleapis.com/v1',+ models: [],+ settings: [],+ active: true,+ }++ const model = await ModelFactory.createModel('gemini-pro', provider)+ expect(model).toBeDefined()+ expect(model.type).toBe('google')+ })++ it('should create an OpenAI-compatible model for openai provider', async () => {+ const provider: ProviderObject = {+ provider: 'openai',+ api_key: 'test-api-key',+ base_url: 'https://api.openai.com/v1',+ models: [],+ settings: [],+ active: true,+ }++ const model = await ModelFactory.createModel('gpt-4', provider)+ expect(model).toBeDefined()+ expect(model.type).toBe('openai-compatible')+ })++ it('should create an OpenAI-compatible model for groq provider', async () => {+ const provider: ProviderObject = {+ provider: 'groq',+ api_key: 'test-api-key',+ base_url: 'https://api.groq.com/openai/v1',+ models: [],+ settings: [],+ active: true,+ }++ const model = await ModelFactory.createModel('llama-3', provider)+ expect(model).toBeDefined()+ expect(model.type).toBe('openai-compatible')+ })++ it('should handle custom headers for OpenAI-compatible providers', async () => {+ const provider: ProviderObject = {+ provider: 'custom',+ api_key: 'test-api-key',+ base_url: 'https://custom.api.com/v1',+ models: [],+ settings: [],+ active: true,+ custom_header: [+ { header: 'X-Custom-Header', value: 'custom-value' },+ ],+ }++ const model = await ModelFactory.createModel('custom-model', provider)+ expect(model).toBeDefined()+ expect(model.type).toBe('openai-compatible')+ })+ })+})diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex 8b8c0b7f6..189471d9c 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -11,70 +11,8 @@ import {type LanguageModelUsage,jsonSchema,} from 'ai'-import { createOpenAICompatible } from '@ai-sdk/openai-compatible'-import { invoke } from '@tauri-apps/api/core'-import { SessionInfo } from '@janhq/core'import { useServiceStore } from '@/hooks/useServiceHub'--/**- * Llama.cpp timings structure from the response- */-interface LlamaCppTimings {- prompt_n?: number- predicted_n?: number- predicted_per_second?: number- prompt_per_second?: number-}--interface LlamaCppChunk {- timings?: LlamaCppTimings-}--/**- * Custom metadata extractor for llama.cpp that extracts timing information- * and converts it to token usage format- */-const llamaCppMetadataExtractor = {- extractMetadata: async ({ parsedBody }: { parsedBody: unknown }) => {- const body = parsedBody as LlamaCppChunk- if (body?.timings) {- return {- llamacpp: {- promptTokens: body.timings.prompt_n ?? null,- completionTokens: body.timings.predicted_n ?? null,- tokensPerSecond: body.timings.predicted_per_second ?? null,- promptPerSecond: body.timings.prompt_per_second ?? null,- },- }- }- return undefined- },- createStreamExtractor: () => {- let lastTimings: LlamaCppTimings | undefined-- return {- processChunk: (parsedChunk: unknown) => {- const chunk = parsedChunk as LlamaCppChunk- if (chunk?.timings) {- lastTimings = chunk.timings- }- },- buildMetadata: () => {- if (lastTimings) {- return {- llamacpp: {- promptTokens: lastTimings.prompt_n ?? null,- completionTokens: lastTimings.predicted_n ?? null,- tokensPerSecond: lastTimings.predicted_per_second ?? null,- promptPerSecond: lastTimings.prompt_per_second ?? null,- },- }- }- return undefined- },- }- },-}+import { ModelFactory } from './model-factory'export type TokenUsageCallback = (usage: LanguageModelUsage,@@ -260,38 +198,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {this.provider = providerthis.systemMessage = systemMessagethis.serviceHub = useServiceStore.getState().serviceHub- // Initialize tools asynchronously if serviceHub is provided- if (this.serviceHub) {- // Fire and forget - load MCP tools in the background- this.loadMCPTools().catch((error) => {- console.warn('Failed to load MCP tools during initialization:', error)- })- }- }-- /**- * Load MCP tools independently (can be called without RAG dependencies)- * @private- */- private async loadMCPTools() {- if (!this.serviceHub) return-- try {- const mcpTools = await this.serviceHub.mcp().getTools()- if (Array.isArray(mcpTools) && mcpTools.length > 0) {- // Convert MCP tools to AI SDK format and merge with existing tools- mcpTools.forEach((tool) => {- this.tools[tool.name] = {- description: tool.description,- inputSchema: jsonSchema(- tool.inputSchema as Record<string, unknown>- ),- } as Tool- })- }- } catch (error) {- console.warn('Failed to load MCP tools:', error)- }+ // Tools will be loaded when updateRagToolsAvailability is called with model capabilities}updateModelMetadata(modelId: string, provider: ProviderObject) {@@ -345,17 +252,35 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {const toolsRecord: Record<string, Tool> = {}- // Load RAG tools if documents are available and model supports tools- if (- this.hasDocuments &&- this.ragFeatureAvailable &&- this.modelSupportsTools- ) {+ // Only load tools if model supports them+ if (this.modelSupportsTools) {+ // Load RAG tools if documents are available+ if (this.hasDocuments && this.ragFeatureAvailable) {+ try {+ const ragTools = await this.serviceHub.rag().getTools()+ if (Array.isArray(ragTools) && ragTools.length > 0) {+ // Convert RAG tools to AI SDK format+ ragTools.forEach((tool) => {+ toolsRecord[tool.name] = {+ description: tool.description,+ inputSchema: jsonSchema(+ tool.inputSchema as Record<string, unknown>+ ),+ } as Tool+ })+ }+ } catch (error) {+ console.warn('Failed to load RAG tools:', error)+ }+ }++ // Load MCP tools (they don't depend on documents)try {- const ragTools = await this.serviceHub.rag().getTools()- if (Array.isArray(ragTools) && ragTools.length > 0) {- // Convert RAG tools to AI SDK format- ragTools.forEach((tool) => {+ const mcpTools = await this.serviceHub.mcp().getTools()+ if (Array.isArray(mcpTools) && mcpTools.length > 0) {+ // Convert MCP tools to AI SDK format+ // MCP tools added after RAG tools, so they take precedence in case of name conflicts+ mcpTools.forEach((tool) => {toolsRecord[tool.name] = {description: tool.description,inputSchema: jsonSchema(@@ -365,29 +290,10 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {})}} catch (error) {- console.warn('Failed to load RAG tools:', error)+ console.warn('Failed to load MCP tools:', error)}}- // Always reload MCP tools (they don't depend on documents)- try {- const mcpTools = await this.serviceHub.mcp().getTools()- if (Array.isArray(mcpTools) && mcpTools.length > 0) {- // Convert MCP tools to AI SDK format- // MCP tools added after RAG tools, so they take precedence in case of name conflicts- mcpTools.forEach((tool) => {- toolsRecord[tool.name] = {- description: tool.description,- inputSchema: jsonSchema(- tool.inputSchema as Record<string, unknown>- ),- } as Tool- })- }- } catch (error) {- console.warn('Failed to load MCP tools:', error)- }-this.tools = toolsRecord}@@ -414,62 +320,8 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {// Start the model (this will be a no-op for remote providers)await this.serviceHub.models().startModel(this.provider, this.modelId)- // For llamacpp provider, get session info and recreate the model with actual URL and API key- if (this.provider.provider === 'llamacpp') {- // Get session info which includes port and api_key- const sessionInfo = await invoke<SessionInfo | null>(- 'plugin:llamacpp|find_session_by_model',- { modelId: this.modelId }- )-- if (!sessionInfo) {- throw new Error(- `No running session found for model: ${this.modelId}`- )- }-- // Recreate the model with actual connection info- const openAICompatible = createOpenAICompatible({- name: 'llamacpp',- baseURL: `http://localhost:${sessionInfo.port}/v1`,- headers: {- Authorization: `Bearer ${sessionInfo.api_key}`,- Origin: 'tauri://localhost',- },- includeUsage: true,- })-- // Update the model with the new instance that has correct URL and API key- this.model = openAICompatible.languageModel(this.modelId, {- metadataExtractor: llamaCppMetadataExtractor,- })- } else {- // For all other providers (OpenAI, Azure, Anthropic, etc.)- // Create OpenAI-compatible model with provider's base_url and api_key- const headers: Record<string, string> = {}-- // Add custom headers if specified- if (this.provider.custom_header) {- this.provider.custom_header.forEach((customHeader) => {- headers[customHeader.header] = customHeader.value- })- }-- // Add authorization header if api_key is present- if (this.provider.api_key) {- headers['Authorization'] = `Bearer ${this.provider.api_key}`- }-- const openAICompatible = createOpenAICompatible({- name: this.provider.provider,- baseURL: this.provider.base_url || 'https://api.openai.com/v1',- headers,- includeUsage: true,- })-- // Create the model instance- this.model = openAICompatible.languageModel(this.modelId)- }+ // Create the model using the factory+ this.model = await ModelFactory.createModel(this.modelId, this.provider)} catch (error) {console.error('Failed to start model:', error)throw new Error(@@ -489,8 +341,9 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {// Convert image parts to image_url format for the APIconst messagesWithImageUrls = convertToImageUrlFormat(filteredMessages)- // Include tools if we have any loaded+ // Include tools only if we have tools loaded AND model supports themconst hasTools = Object.keys(this.tools).length > 0+ const shouldEnableTools = hasTools && this.modelSupportsTools// Track stream timing and token count for token speed calculationlet streamStartTime: number | undefined@@ -503,13 +356,14 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {// Pass URLs directly to the model instead of downloading// This avoids CORS issues with presigned S3 URLsexperimental_download: passUrlsDirectly,- tools: hasTools ? this.tools : undefined,- toolChoice: 'auto',+ tools: shouldEnableTools ? this.tools : undefined,+ toolChoice: shouldEnableTools ? 'auto' : undefined,system: this.systemMessage,})return result.toUIMessageStream({messageMetadata: ({ part }) => {+// Track stream start time on first text deltaif (part.type === 'text-delta') {if (!streamStartTime) {@@ -601,7 +455,6 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {| Record<string, unknown>| undefinedconst usage = metadata?.usage as LanguageModelUsage | undefined- console.log(usage)if (usage) {this.onTokenUsage?.(usage, responseMessage.id)}diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.tsnew file mode 100644index 000000000..5036dea04--- /dev/null+++ b/web-app/src/lib/model-factory.ts@@ -0,0 +1,245 @@+/**+ * Model Factory+ *+ * This factory provides a unified interface for creating language models from various providers.+ * It handles the complexity of initializing different AI SDK providers with their specific+ * configurations and returns a standard LanguageModel interface.+ *+ * Supported Providers:+ * - llamacpp: Local models via llama.cpp (requires running session)+ * - anthropic: Claude models via Anthropic API (@ai-sdk/anthropic v2.0)+ * - google/gemini: Gemini models via Google Generative AI API (@ai-sdk/google v2.0)+ * - OpenAI-compatible: OpenAI, Azure, Groq, Together, Fireworks, DeepSeek, Mistral, Cohere, etc.+ *+ * Usage:+ * ```typescript+ * const model = await ModelFactory.createModel(modelId, provider)+ * ```+ *+ * The factory automatically:+ * - Handles provider-specific authentication and headers+ * - Manages llamacpp session discovery and connection+ * - Configures custom headers for each provider+ * - Returns a unified LanguageModel interface compatible with Vercel AI SDK+ */++import { type LanguageModel } from 'ai'+import { createOpenAICompatible } from '@ai-sdk/openai-compatible'+import { createAnthropic } from '@ai-sdk/anthropic'+import { createGoogleGenerativeAI } from '@ai-sdk/google'+import { invoke } from '@tauri-apps/api/core'+import { SessionInfo } from '@janhq/core'++/**+ * Llama.cpp timings structure from the response+ */+interface LlamaCppTimings {+ prompt_n?: number+ predicted_n?: number+ predicted_per_second?: number+ prompt_per_second?: number+}++interface LlamaCppChunk {+ timings?: LlamaCppTimings+}++/**+ * Custom metadata extractor for llama.cpp that extracts timing information+ * and converts it to token usage format+ */+const llamaCppMetadataExtractor = {+ extractMetadata: async ({ parsedBody }: { parsedBody: unknown }) => {+ const body = parsedBody as LlamaCppChunk+ if (body?.timings) {+ return {+ llamacpp: {+ promptTokens: body.timings.prompt_n ?? null,+ completionTokens: body.timings.predicted_n ?? null,+ tokensPerSecond: body.timings.predicted_per_second ?? null,+ promptPerSecond: body.timings.prompt_per_second ?? null,+ },+ }+ }+ return undefined+ },+ createStreamExtractor: () => {+ let lastTimings: LlamaCppTimings | undefined++ return {+ processChunk: (parsedChunk: unknown) => {+ const chunk = parsedChunk as LlamaCppChunk+ if (chunk?.timings) {+ lastTimings = chunk.timings+ }+ },+ buildMetadata: () => {+ if (lastTimings) {+ return {+ llamacpp: {+ promptTokens: lastTimings.prompt_n ?? null,+ completionTokens: lastTimings.predicted_n ?? null,+ tokensPerSecond: lastTimings.predicted_per_second ?? null,+ promptPerSecond: lastTimings.prompt_per_second ?? null,+ },+ }+ }+ return undefined+ },+ }+ },+}++/**+ * Factory for creating language models based on provider type.+ * Supports native AI SDK providers (Anthropic, Google) and OpenAI-compatible providers.+ */+export class ModelFactory {+ /**+ * Create a language model instance based on the provider configuration+ */+ static async createModel(+ modelId: string,+ provider: ProviderObject+ ): Promise<LanguageModel> {+ const providerName = provider.provider.toLowerCase()++ switch (providerName) {+ case 'llamacpp':+ return this.createLlamaCppModel(modelId)++ case 'anthropic':+ return this.createAnthropicModel(modelId, provider)++ case 'google':+ case 'gemini':+ return this.createGoogleModel(modelId, provider)++ case 'openai':+ case 'azure':+ case 'groq':+ case 'together':+ case 'fireworks':+ case 'deepseek':+ case 'mistral':+ case 'cohere':+ case 'perplexity':+ case 'moonshot':+ default:+ return this.createOpenAICompatibleModel(modelId, provider)+ }+ }++ /**+ * Create a llamacpp model by finding the running session+ */+ private static async createLlamaCppModel(+ modelId: string+ ): Promise<LanguageModel> {+ // Get session info which includes port and api_key+ const sessionInfo = await invoke<SessionInfo | null>(+ 'plugin:llamacpp|find_session_by_model',+ { modelId }+ )++ if (!sessionInfo) {+ throw new Error(`No running session found for model: ${modelId}`)+ }++ // Create OpenAI-compatible client for llamacpp+ const openAICompatible = createOpenAICompatible({+ name: 'llamacpp',+ baseURL: `http://localhost:${sessionInfo.port}/v1`,+ headers: {+ Authorization: `Bearer ${sessionInfo.api_key}`,+ Origin: 'tauri://localhost',+ },+ includeUsage: true,+ })++ return openAICompatible.languageModel(modelId, {+ metadataExtractor: llamaCppMetadataExtractor,+ })+ }++ /**+ * Create an Anthropic model using the official AI SDK+ */+ private static createAnthropicModel(+ modelId: string,+ provider: ProviderObject+ ): LanguageModel {+ const headers: Record<string, string> = {}++ // Add custom headers if specified (e.g., anthropic-version)+ if (provider.custom_header) {+ provider.custom_header.forEach((customHeader) => {+ headers[customHeader.header] = customHeader.value+ })+ }++ const anthropic = createAnthropic({+ apiKey: provider.api_key,+ baseURL: provider.base_url,+ headers: Object.keys(headers).length > 0 ? headers : undefined,+ })++ return anthropic(modelId)+ }++ /**+ * Create a Google/Gemini model using the official AI SDK+ */+ private static createGoogleModel(+ modelId: string,+ provider: ProviderObject+ ): LanguageModel {+ const headers: Record<string, string> = {}++ // Add custom headers if specified+ if (provider.custom_header) {+ provider.custom_header.forEach((customHeader) => {+ headers[customHeader.header] = customHeader.value+ })+ }++ const google = createGoogleGenerativeAI({+ apiKey: provider.api_key,+ baseURL: provider.base_url,+ headers: Object.keys(headers).length > 0 ? headers : undefined,+ })++ return google(modelId)+ }++ /**+ * Create an OpenAI-compatible model for providers that support the OpenAI API format+ */+ private static createOpenAICompatibleModel(+ modelId: string,+ provider: ProviderObject+ ): LanguageModel {+ const headers: Record<string, string> = {}++ // Add custom headers if specified+ if (provider.custom_header) {+ provider.custom_header.forEach((customHeader) => {+ headers[customHeader.header] = customHeader.value+ })+ }++ // Add authorization header if api_key is present+ if (provider.api_key) {+ headers['Authorization'] = `Bearer ${provider.api_key}`+ }++ const openAICompatible = createOpenAICompatible({+ name: provider.provider,+ baseURL: provider.base_url || 'https://api.openai.com/v1',+ headers,+ includeUsage: true,+ })++ return openAICompatible.languageModel(modelId)+ }+}diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex 28b9129cf..e14276371 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -27,7 +27,6 @@ import {ConversationContent,ConversationScrollButton,} from '@/ai-elements/conversation'-import { Loader } from 'lucide-react'import { generateId, lastAssistantMessageIsCompleteWithToolCalls } from 'ai'import type { UIMessage } from '@ai-sdk/react'import { useChatSessions } from '@/stores/chat-session-store'@@ -44,6 +43,7 @@ import {} from '@/hooks/useChatAttachments'import { processAttachmentsForSend } from '@/lib/attachmentProcessing'import { useAttachments } from '@/hooks/useAttachments'+import { PromptProgress } from '@/components/PromptProgress'const CHAT_STATUS = {STREAMING: 'streaming',@@ -710,7 +710,7 @@ function ThreadDetail() {)})}{status === CHAT_STATUS.SUBMITTED && (- <Loader className="animate-spin w-4 h-4" />+ <PromptProgress />)}</ConversationContent><ConversationScrollButton />