Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat: add xAI provider (#7551)

Louis6a0adcd729ae
diff --git a/Makefile b/Makefile
index c20d9f277..ff7316999 100644
--- a/Makefile
+++ b/Makefile
@@ -52,7 +52,7 @@ install-ios-rust-targets:
dev: install-and-build
yarn download:bin
- make build-mlx-server
+ make build-mlx-server-if-exists
yarn dev
# Web application targets
@@ -120,7 +120,7 @@ endif
cargo test --manifest-path src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml
cargo test --manifest-path src-tauri/utils/Cargo.toml
-# Build MLX server (macOS Apple Silicon only)
+# Build MLX server (macOS Apple Silicon only) - always builds
build-mlx-server:
ifeq ($(shell uname -s),Darwin)
@echo "Building MLX server for Apple Silicon..."
@@ -152,6 +152,18 @@ else
@echo "Skipping MLX server build (macOS only)"
endif
+# Build MLX server only if not already present (for dev)
+build-mlx-server-if-exists:
+ifeq ($(shell uname -s),Darwin)
+ @if [ -f "src-tauri/resources/bin/mlx-server" ]; then \
+ echo "MLX server already exists at src-tauri/resources/bin/mlx-server, skipping build..."; \
+ else \
+ make build-mlx-server; \
+ fi
+else
+ @echo "Skipping MLX server build (macOS only)"
+endif
+
# Build
build: install-and-build install-rust-targets
yarn build
diff --git a/web-app/package.json b/web-app/package.json
index 1a4e94289..2f851b70d 100644
--- a/web-app/package.json
+++ b/web-app/package.json
@@ -16,6 +16,7 @@
"@ai-sdk/openai": "^2.0.0",
"@ai-sdk/openai-compatible": "^1.0.28",
"@ai-sdk/react": "^2.0.109",
+ "@ai-sdk/xai": "^2.0.0",
"@dnd-kit/core": "6.3.1",
"@dnd-kit/modifiers": "9.0.0",
"@dnd-kit/sortable": "10.0.0",
@@ -89,7 +90,6 @@
"sonner": "2.0.5",
"streamdown": "npm:@janhq/streamdown@^2.1.1",
"tailwindcss": "4.1.17",
- "token.js": "npm:[email protected]",
"tw-animate-css": "1.2.8",
"ulidx": "2.4.1",
"unified": "11.0.5",
diff --git a/web-app/public/images/model-provider/xai.svg b/web-app/public/images/model-provider/xai.svg
new file mode 100644
index 000000000..e20fdcd48
--- /dev/null
+++ b/web-app/public/images/model-provider/xai.svg
@@ -0,0 +1,3 @@
+<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
+ <path d="M2.30047 8.77631L12.0474 23H16.3799L6.63183 8.77631H2.30047ZM6.6285 16.6762L2.29492 23H6.63072L8.79584 19.8387L6.6285 16.6762ZM17.3709 1L9.88007 11.9308L12.0474 15.0944L21.7067 1H17.3709ZM18.1555 7.76374V23H21.7067V2.5818L18.1555 7.76374Z" fill="#fff" />
+</svg>
diff --git a/web-app/src/constants/models.ts b/web-app/src/constants/models.ts
index 579064c0f..6799f1850 100644
--- a/web-app/src/constants/models.ts
+++ b/web-app/src/constants/models.ts
@@ -13,3 +13,117 @@ export const SETUP_SCREEN_QUANTIZATIONS = ['q4_k_xl']
export const JAN_V2_VL_MODEL_HF_REPO = 'janhq/Jan-v2-VL-high-gguf'
export const JAN_V2_VL_QUANTIZATIONS = ['q4_k_m', 'q4_k_s', 'q4_0', 'q3_k_m']
+
+/**
+ * Provider model capabilities - copied from token.js package
+ */
+export const providerModels = {
+ openai: {
+ models: ['gpt-5', 'gpt-5-mini', 'gpt-4.5-preview', 'gpt-4.1', 'gpt-4o', 'gpt-4o-mini', 'o3-mini', 'gpt-4-turbo'],
+ supportsCompletion: true,
+ supportsStreaming: ['gpt-5', 'gpt-5-mini', 'gpt-4.5-preview', 'gpt-4.1', 'gpt-4o', 'gpt-4o-mini', 'o3-mini', 'gpt-4-turbo'],
+ supportsJSON: ['gpt-5', 'gpt-5-mini', 'gpt-4.5-preview', 'gpt-4.1', 'gpt-4o', 'gpt-4o-mini', 'o3-mini', 'gpt-4-turbo'],
+ supportsImages: ['gpt-5', 'gpt-5-mini', 'gpt-4.5-preview', 'gpt-4.1', 'gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo'],
+ supportsToolCalls: ['gpt-5', 'gpt-5-mini', 'gpt-4.5-preview', 'gpt-4.1', 'gpt-4o', 'gpt-4o-mini', 'o3-mini', 'gpt-4-turbo'],
+ supportsN: true,
+ },
+ ai21: {
+ models: ['jamba-instruct'],
+ supportsCompletion: true,
+ supportsStreaming: ['jamba-instruct'],
+ supportsJSON: [],
+ supportsImages: [],
+ supportsToolCalls: [],
+ supportsN: true,
+ },
+ anthropic: {
+ models: ['claude-sonnet-4-5', 'claude-haiku-4-5', 'claude-opus-4-1', 'claude-sonnet-4', 'claude-opus-4', 'claude-3-7-sonnet-20250219', 'claude-3-5-haiku-20241022', 'claude-3-haiku-20240307'],
+ supportsCompletion: true,
+ supportsStreaming: ['claude-sonnet-4-5', 'claude-haiku-4-5', 'claude-opus-4-1', 'claude-sonnet-4', 'claude-opus-4', 'claude-3-7-sonnet-20250219', 'claude-3-5-haiku-20241022', 'claude-3-haiku-20240307'],
+ supportsJSON: [],
+ supportsImages: ['claude-sonnet-4-5', 'claude-haiku-4-5', 'claude-opus-4-1', 'claude-sonnet-4', 'claude-opus-4', 'claude-3-7-sonnet-20250219', 'claude-3-5-haiku-20241022', 'claude-3-haiku-20240307'],
+ supportsToolCalls: ['claude-sonnet-4-5', 'claude-haiku-4-5', 'claude-opus-4-1', 'claude-sonnet-4', 'claude-opus-4', 'claude-3-7-sonnet-20250219', 'claude-3-5-haiku-20241022', 'claude-3-haiku-20240307'],
+ supportsN: true,
+ },
+ gemini: {
+ models: ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-2.5-flash-lite', 'gemini-2.0-flash', 'gemini-2.0-flash-lite', 'gemini-1.5-flash', 'gemini-1.5-flash-8b'],
+ supportsCompletion: true,
+ supportsStreaming: ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-2.5-flash-lite', 'gemini-2.0-flash', 'gemini-2.0-flash-lite', 'gemini-1.5-flash', 'gemini-1.5-flash-8b'],
+ supportsJSON: ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-2.5-flash-lite', 'gemini-2.0-flash', 'gemini-2.0-flash-lite', 'gemini-1.5-flash', 'gemini-1.5-flash-8b'],
+ supportsImages: ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-2.5-flash-lite', 'gemini-2.0-flash', 'gemini-2.0-flash-lite', 'gemini-1.5-flash', 'gemini-1.5-flash-8b'],
+ supportsToolCalls: ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-2.5-flash-lite', 'gemini-2.0-flash', 'gemini-2.0-flash-lite', 'gemini-1.5-flash', 'gemini-1.5-flash-8b'],
+ supportsN: true,
+ },
+ cohere: {
+ models: ['command-a-03-2025', 'command-r-08-2024', 'command-r-plus-08-2024'],
+ supportsCompletion: true,
+ supportsStreaming: ['command-a-03-2025', 'command-r-08-2024', 'command-r-plus-08-2024'],
+ supportsJSON: [],
+ supportsImages: [],
+ supportsToolCalls: ['command-a-03-2025', 'command-r-08-2024', 'command-r-plus-08-2024'],
+ supportsN: true,
+ },
+ bedrock: {
+ models: ['anthropic.claude-3-5-sonnet-20241022-v2:0', 'anthropic.claude-3-5-haiku-20241022-v1:0', 'cohere.command-r-plus-v1:0', 'cohere.command-r-v1:0', 'meta.llama3-70b-instruct-v1:0', 'meta.llama3-8b-instruct-v1:0', 'mistral.mistral-large-2402-v1:0', 'amazon.titan-text-express-v1'],
+ supportsCompletion: true,
+ supportsStreaming: ['anthropic.claude-3-5-sonnet-20241022-v2:0', 'anthropic.claude-3-5-haiku-20241022-v1:0', 'cohere.command-r-plus-v1:0', 'cohere.command-r-v1:0', 'meta.llama3-70b-instruct-v1:0', 'meta.llama3-8b-instruct-v1:0', 'mistral.mistral-large-2402-v1:0', 'amazon.titan-text-express-v1'],
+ supportsJSON: [],
+ supportsImages: ['anthropic.claude-3-5-sonnet-20241022-v2:0', 'anthropic.claude-3-5-haiku-20241022-v1:0'],
+ supportsToolCalls: ['anthropic.claude-3-5-sonnet-20241022-v2:0', 'anthropic.claude-3-5-haiku-20241022-v1:0', 'cohere.command-r-plus-v1:0', 'cohere.command-r-v1:0', 'mistral.mistral-large-2402-v1:0'],
+ supportsN: true,
+ },
+ mistral: {
+ models: ['mistral-large-2411', 'magistral-medium-2509', 'magistral-small-2509', 'pixtral-large-2411', 'pixtral-12b-2409', 'codestral-2508', 'mistral-small-2506', 'mistral-nemo-2407'],
+ supportsCompletion: true,
+ supportsStreaming: ['mistral-large-2411', 'magistral-medium-2509', 'magistral-small-2509', 'pixtral-large-2411', 'pixtral-12b-2409', 'codestral-2508', 'mistral-small-2506', 'mistral-nemo-2407'],
+ supportsJSON: ['mistral-large-2411', 'codestral-2508'],
+ supportsImages: ['magistral-medium-2509', 'magistral-small-2509', 'pixtral-large-2411', 'pixtral-12b-2409', 'mistral-small-2506'],
+ supportsToolCalls: ['mistral-large-2411', 'mistral-small-2506'],
+ supportsN: true,
+ },
+ groq: {
+ models: ['meta-llama/llama-4-maverick-17b-128e-instruct', 'meta-llama/llama-4-scout-17b-16e-instruct', 'llama-3.3-70b-versatile', 'llama-3.1-8b-instant', 'moonshotai/kimi-k2-instruct-0905', 'qwen/qwen3-32b', 'openai/gpt-oss-120b', 'whisper-large-v3-turbo'],
+ supportsCompletion: true,
+ supportsStreaming: ['meta-llama/llama-4-maverick-17b-128e-instruct', 'meta-llama/llama-4-scout-17b-16e-instruct', 'llama-3.3-70b-versatile', 'llama-3.1-8b-instant', 'moonshotai/kimi-k2-instruct-0905', 'qwen/qwen3-32b', 'openai/gpt-oss-120b'],
+ supportsJSON: ['llama-3.3-70b-versatile', 'llama-3.1-8b-instant', 'openai/gpt-oss-120b'],
+ supportsImages: ['meta-llama/llama-4-maverick-17b-128e-instruct', 'meta-llama/llama-4-scout-17b-16e-instruct'],
+ supportsToolCalls: [],
+ supportsN: true,
+ },
+ xai: {
+ models: ['grok-4-1-fast-reasoning', 'grok-4-fast-reasoning', 'grok-3', 'grok-3-mini', 'grok-2-vision-1212', 'grok-imagine-image'],
+ supportsCompletion: true,
+ supportsStreaming: ['grok-4-1-fast-reasoning', 'grok-4-fast-reasoning', 'grok-3', 'grok-3-mini', 'grok-2-vision-1212'],
+ supportsJSON: ['grok-4-1-fast-reasoning', 'grok-4-fast-reasoning', 'grok-3', 'grok-3-mini'],
+ supportsImages: ['grok-2-vision-1212'],
+ supportsToolCalls: ['grok-4-1-fast-reasoning', 'grok-4-fast-reasoning', 'grok-3', 'grok-3-mini'],
+ supportsN: true,
+ },
+ perplexity: {
+ models: ['sonar', 'sonar-pro', 'sonar-reasoning-pro'],
+ supportsCompletion: true,
+ supportsStreaming: ['sonar', 'sonar-pro', 'sonar-reasoning-pro'],
+ supportsJSON: ['sonar', 'sonar-pro', 'sonar-reasoning-pro'],
+ supportsImages: [],
+ supportsToolCalls: ['sonar', 'sonar-pro', 'sonar-reasoning-pro'],
+ supportsN: true,
+ },
+ openrouter: {
+ models: true,
+ supportsCompletion: true,
+ supportsStreaming: true,
+ supportsJSON: true,
+ supportsImages: true,
+ supportsToolCalls: true,
+ supportsN: true,
+ },
+ 'openai-compatible': {
+ models: true,
+ supportsCompletion: true,
+ supportsStreaming: true,
+ supportsJSON: true,
+ supportsImages: true,
+ supportsToolCalls: true,
+ supportsN: true,
+ },
+} as const
\ No newline at end of file
diff --git a/web-app/src/constants/providers.ts b/web-app/src/constants/providers.ts
index 868912e5b..ed3407141 100644
--- a/web-app/src/constants/providers.ts
+++ b/web-app/src/constants/providers.ts
@@ -256,6 +256,40 @@ export const predefinedProviders = [
],
models: [],
},
+ {
+ active: true,
+ api_key: '',
+ base_url: 'https://api.x.ai/v1',
+ explore_models_url: 'https://docs.x.ai/overview',
+ provider: 'xai',
+ settings: [
+ {
+ key: 'api-key',
+ title: 'API Key',
+ description:
+ "The xAI API uses API keys for authentication. Visit your [API Keys](https://console.x.ai/) page to retrieve the API key you'll use in your requests.",
+ controller_type: 'input',
+ controller_props: {
+ placeholder: 'Insert API Key',
+ value: '',
+ type: 'password',
+ input_actions: ['unobscure', 'copy'],
+ },
+ },
+ {
+ key: 'base-url',
+ title: 'Base URL',
+ description:
+ 'The base endpoint to use. See the [xAI API documentation](https://docs.x.ai/overview) for more information.',
+ controller_type: 'input',
+ controller_props: {
+ placeholder: 'https://api.x.ai/v1',
+ value: 'https://api.x.ai/v1',
+ },
+ },
+ ],
+ models: [],
+ },
{
active: true,
api_key: '',
diff --git a/web-app/src/hooks/__tests__/useAppState.test.ts b/web-app/src/hooks/__tests__/useAppState.test.ts
index c9304db47..1d26b1416 100644
--- a/web-app/src/hooks/__tests__/useAppState.test.ts
+++ b/web-app/src/hooks/__tests__/useAppState.test.ts
@@ -23,7 +23,7 @@ describe('useAppState', () => {
it('should initialize with default state', () => {
const { result } = renderHook(() => useAppState())
-
+
expect(result.current.streamingContent).toBeUndefined()
expect(result.current.loadingModel).toBe(false)
expect(result.current.tools).toEqual([])
@@ -52,98 +52,82 @@ describe('useAppState', () => {
it('should update loading model state', () => {
const { result } = renderHook(() => useAppState())
-
+
act(() => {
result.current.updateLoadingModel(true)
})
-
+
expect(result.current.loadingModel).toBe(true)
-
+
act(() => {
result.current.updateLoadingModel(false)
})
-
+
expect(result.current.loadingModel).toBe(false)
})
it('should update tools', () => {
const { result } = renderHook(() => useAppState())
-
+
const tools = [
{ name: 'tool1', description: 'First tool' },
{ name: 'tool2', description: 'Second tool' }
]
-
+
act(() => {
result.current.updateTools(tools)
})
-
+
expect(result.current.tools).toEqual(tools)
})
it('should update server status', () => {
const { result } = renderHook(() => useAppState())
-
+
act(() => {
result.current.setServerStatus('running')
})
-
+
expect(result.current.serverStatus).toBe('running')
-
+
act(() => {
result.current.setServerStatus('pending')
})
-
+
expect(result.current.serverStatus).toBe('pending')
})
it('should set abort controller', () => {
const { result } = renderHook(() => useAppState())
-
+
const controller = new AbortController()
-
+
act(() => {
result.current.setAbortController('thread-123', controller)
})
-
- expect(result.current.abortControllers['thread-123']).toBe(controller)
- })
- it('should update current tool call', () => {
- const { result } = renderHook(() => useAppState())
-
- const toolCall = {
- id: 'call-123',
- type: 'function' as const,
- function: { name: 'test_function', arguments: '{}' }
- }
-
- act(() => {
- result.current.updateCurrentToolCall(toolCall)
- })
-
- expect(result.current.currentToolCall).toEqual(toolCall)
+ expect(result.current.abortControllers['thread-123']).toBe(controller)
})
it('should set out of context dialog', () => {
const { result } = renderHook(() => useAppState())
-
+
act(() => {
result.current.setOutOfContextDialog(true)
})
-
+
expect(result.current.showOutOfContextDialog).toBe(true)
-
+
act(() => {
result.current.setOutOfContextDialog(false)
})
-
+
expect(result.current.showOutOfContextDialog).toBe(false)
})
it('should update token speed', () => {
const { result } = renderHook(() => useAppState())
-
+
const message = {
id: 'msg-1',
content: 'Hello world',
@@ -151,18 +135,18 @@ describe('useAppState', () => {
created_at: Date.now(),
thread_id: 'thread-123'
}
-
+
act(() => {
result.current.updateTokenSpeed(message)
})
-
+
// Token speed calculation depends on implementation
expect(result.current.tokenSpeed).toBeDefined()
})
it('should reset token speed', () => {
const { result } = renderHook(() => useAppState())
-
+
const message = {
id: 'msg-1',
content: 'Hello world',
@@ -170,17 +154,17 @@ describe('useAppState', () => {
created_at: Date.now(),
thread_id: 'thread-123'
}
-
+
act(() => {
result.current.updateTokenSpeed(message)
})
-
+
expect(result.current.tokenSpeed).toBeDefined()
-
+
act(() => {
result.current.resetTokenSpeed()
})
-
+
expect(result.current.tokenSpeed).toBeUndefined()
})
})
diff --git a/web-app/src/hooks/useAppState.ts b/web-app/src/hooks/useAppState.ts
index 1cde7b4cd..bf9d758f4 100644
--- a/web-app/src/hooks/useAppState.ts
+++ b/web-app/src/hooks/useAppState.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { ThreadMessage } from '@janhq/core'
import { MCPTool } from '@/types/completion'
-import { ChatCompletionMessageToolCall } from 'openai/resources'
export type PromptProgress = {
cache: number
@@ -25,7 +24,6 @@ type AppState = {
serverStatus: 'running' | 'stopped' | 'pending'
abortControllers: Record<string, AbortController>
tokenSpeed?: TokenSpeed
- currentToolCall?: ChatCompletionMessageToolCall
showOutOfContextDialog?: boolean
errorMessage?: AppErrorMessage
promptProgress?: PromptProgress
@@ -33,9 +31,6 @@ type AppState = {
cancelToolCall?: () => void
setServerStatus: (value: 'running' | 'stopped' | 'pending') => void
updateStreamingContent: (content: ThreadMessage | undefined) => void
- updateCurrentToolCall: (
- toolCall: ChatCompletionMessageToolCall | undefined
- ) => void
updateLoadingModel: (loading: boolean) => void
updateTools: (tools: MCPTool[]) => void
updateRagToolNames: (names: string[]) => void
@@ -79,11 +74,6 @@ export const useAppState = create<AppState>()((set) => ({
: undefined,
}))
},
- updateCurrentToolCall: (toolCall) => {
- set(() => ({
- currentToolCall: toolCall,
- }))
- },
updateLoadingModel: (loading) => {
set({ loadingModel: loading })
},
@@ -154,7 +144,6 @@ export const useAppState = create<AppState>()((set) => ({
streamingContent: undefined,
abortControllers: {},
tokenSpeed: undefined,
- currentToolCall: undefined,
cancelToolCall: undefined,
errorMessage: undefined,
showOutOfContextDialog: false,
diff --git a/web-app/src/lib/__tests__/messages.test.ts b/web-app/src/lib/__tests__/messages.test.ts
deleted file mode 100644
index 888682613..000000000
--- a/web-app/src/lib/__tests__/messages.test.ts
+++ /dev/null
@@ -1,567 +0,0 @@
-import { describe, it, expect } from 'vitest'
-import {
- CompletionMessagesBuilder,
-} from '../messages'
-import { ThreadMessage } from '@janhq/core'
-import { ChatCompletionMessageToolCall } from 'openai/resources'
-
-// Mock thread messages for testing
-const createMockThreadMessage = (
- role: 'user' | 'assistant' | 'system',
- content: string,
- hasError = false
-): ThreadMessage => ({
- id: 'msg-123',
- object: 'thread.message',
- thread_id: 'thread-123',
- role,
- content: [
- {
- type: 'text' as any,
- text: {
- value: content,
- annotations: [],
- },
- },
- ],
- status: 'completed' as any,
- created_at: Date.now(),
- completed_at: Date.now(),
- metadata: hasError ? { error: true } : {},
-})
-
-describe('CompletionMessagesBuilder', () => {
- describe('constructor', () => {
- it('should initialize with empty messages array when no system instruction', () => {
- const messages: ThreadMessage[] = []
- const builder = new CompletionMessagesBuilder(messages)
-
- expect(builder.getMessages()).toEqual([])
- })
-
- it('should add system message when system instruction provided', () => {
- const messages: ThreadMessage[] = []
- const systemInstruction = 'You are a helpful assistant.'
- const builder = new CompletionMessagesBuilder(messages, systemInstruction)
-
- const result = builder.getMessages()
- expect(result).toHaveLength(2)
- expect(result[0]).toEqual({
- role: 'system',
- content: systemInstruction,
- })
- expect(result[1]).toEqual({
- role: 'user',
- content: '.',
- })
- })
-
- it('should filter out messages with errors', () => {
- const messages: ThreadMessage[] = [
- createMockThreadMessage('user', 'Hello', false),
- createMockThreadMessage('assistant', 'Hi there', true), // has error
- createMockThreadMessage('user', 'How are you?', false),
- ]
-
- const builder = new CompletionMessagesBuilder(messages)
- const result = builder.getMessages()
-
- // getMessages() inserts a filler message between consecutive user messages
- expect(result).toHaveLength(3)
- expect(result[0].content).toBe('Hello')
- expect(result[1].role).toBe('assistant') // filler message
- expect(result[2].content).toBe('How are you?')
- })
-
- it('should normalize assistant message content', () => {
- const messages: ThreadMessage[] = [
- createMockThreadMessage(
- 'assistant',
- '<think>Let me think...</think>Hello there!'
- ),
- ]
-
- const builder = new CompletionMessagesBuilder(messages)
- const result = builder.getMessages()
-
- expect(result).toHaveLength(2)
- expect(result[0].content).toBe('.')
- expect(result[1].content).toBe('Hello there!')
- })
-
- it('should preserve user message content without normalization', () => {
- const messages: ThreadMessage[] = [
- createMockThreadMessage(
- 'user',
- '<think>This should not be normalized</think>Hello'
- ),
- ]
-
- const builder = new CompletionMessagesBuilder(messages)
- const result = builder.getMessages()
-
- expect(result).toHaveLength(1)
- expect(result[0].content).toBe(
- '<think>This should not be normalized</think>Hello'
- )
- })
-
- it('should handle messages with empty content', () => {
- const message: ThreadMessage = {
- ...createMockThreadMessage('user', ''),
- content: [{ type: 'text' as any, text: undefined }],
- }
-
- const builder = new CompletionMessagesBuilder([message])
- const result = builder.getMessages()
-
- expect(result).toHaveLength(1)
- expect(result[0].content).toBe('.')
- })
-
- it('should handle messages with missing text value', () => {
- const message: ThreadMessage = {
- ...createMockThreadMessage('user', ''),
- content: [
- { type: 'text' as any, text: { value: '', annotations: [] } },
- ],
- }
-
- const builder = new CompletionMessagesBuilder([message])
- const result = builder.getMessages()
-
- expect(result).toHaveLength(1)
- expect(result[0].content).toBe('.')
- })
- })
-
- describe('addUserMessage', () => {
- it('should add user message to messages array', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addUserMessage(
- createMockThreadMessage('user', 'Hello, how are you?')
- )
-
- const result = builder.getMessages()
- expect(result).toHaveLength(1)
- expect(result[0]).toEqual({
- role: 'user',
- content: 'Hello, how are you?',
- })
- })
-
- it('should not add consecutive user messages', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addUserMessage(createMockThreadMessage('user', 'First message'))
- builder.addUserMessage(createMockThreadMessage('user', 'Second message'))
-
- const result = builder.getMessages()
- expect(result).toHaveLength(1)
- expect(result[0].content).toBe('Second message')
- })
-
- it('should handle empty user message', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addUserMessage(createMockThreadMessage('user', ''))
-
- const result = builder.getMessages()
- expect(result).toHaveLength(1)
- expect(result[0].content).toBe('')
- })
- })
-
- describe('addAssistantMessage', () => {
- it('should add assistant message with normalized content', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addAssistantMessage('<think>Processing...</think>Hello!')
-
- const result = builder.getMessages()
- expect(result).toHaveLength(2)
- expect(result[0]).toEqual({
- role: 'user',
- content: '.',
- })
- expect(result[1]).toEqual({
- role: 'assistant',
- content: 'Hello!',
- refusal: undefined,
- tool_calls: undefined,
- })
- })
-
- it('should add assistant message with refusal', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addAssistantMessage(
- 'I cannot help with that',
- 'Content policy violation'
- )
-
- const result = builder.getMessages()
- expect(result).toHaveLength(2)
- expect(result[0]).toEqual({
- role: 'user',
- content: '.',
- })
- expect(result[1]).toEqual({
- role: 'assistant',
- content: 'I cannot help with that',
- refusal: 'Content policy violation',
- tool_calls: undefined,
- })
- })
-
- it('should add assistant message with tool calls', () => {
- const builder = new CompletionMessagesBuilder([])
- const toolCalls: ChatCompletionMessageToolCall[] = [
- {
- id: 'call_123',
- type: 'function',
- function: {
- name: 'get_weather',
- arguments: '{"location": "New York"}',
- },
- },
- ]
-
- builder.addAssistantMessage(
- 'Let me check the weather',
- undefined,
- toolCalls
- )
-
- const result = builder.getMessages()
- expect(result).toHaveLength(2)
- expect(result[0]).toEqual({
- role: 'user',
- content: '.',
- })
- expect(result[1]).toEqual({
- role: 'assistant',
- content: 'Let me check the weather',
- refusal: undefined,
- tool_calls: toolCalls,
- })
- })
-
- it('should handle assistant message with all parameters', () => {
- const builder = new CompletionMessagesBuilder([])
- const toolCalls: ChatCompletionMessageToolCall[] = [
- {
- id: 'call_456',
- type: 'function',
- function: {
- name: 'search',
- arguments: '{"query": "test"}',
- },
- },
- ]
-
- builder.addAssistantMessage(
- '<think>Searching...</think>Here are the results',
- 'Cannot search sensitive content',
- toolCalls
- )
-
- const result = builder.getMessages()
- expect(result).toHaveLength(2)
- expect(result[0]).toEqual({
- role: 'user',
- content: '.',
- })
- expect(result[1]).toEqual({
- role: 'assistant',
- content: 'Here are the results',
- refusal: 'Cannot search sensitive content',
- tool_calls: toolCalls,
- })
- })
- })
-
- describe('addToolMessage', () => {
- it('should add tool message with correct format', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addToolMessage('Weather data: 72°F', 'call_123')
-
- const result = builder.getMessages()
- expect(result).toHaveLength(2)
- expect(result[0]).toEqual({
- role: 'user',
- content: '.',
- })
- expect(result[1]).toEqual({
- role: 'tool',
- content: 'Weather data: 72°F',
- tool_call_id: 'call_123',
- })
- })
-
- it('should add multiple tool messages', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addToolMessage('First tool result', 'call_1')
- builder.addToolMessage('Second tool result', 'call_2')
-
- const result = builder.getMessages()
- // getMessages() inserts a filler message between consecutive tool messages
- expect(result).toHaveLength(4)
- expect(result[0].role).toBe('user') // initial filler message
- expect(result[1].tool_call_id).toBe('call_1')
- expect(result[2].role).toBe('assistant') // filler message
- expect(result[3].tool_call_id).toBe('call_2')
- })
-
- it('should handle empty tool content', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addToolMessage('', 'call_123')
-
- const result = builder.getMessages()
- expect(result).toHaveLength(2)
- expect(result[0]).toEqual({
- role: 'user',
- content: '.',
- })
- expect(result[1].content).toBe('')
- expect(result[1].tool_call_id).toBe('call_123')
- })
- })
-
- describe('getMessages', () => {
- it('should return messages in correct order', () => {
- const threadMessages: ThreadMessage[] = [
- createMockThreadMessage('user', 'Hello'),
- ]
- const builder = new CompletionMessagesBuilder(
- threadMessages,
- 'You are helpful'
- )
-
- builder.addUserMessage(createMockThreadMessage('user', 'How are you?'))
- builder.addAssistantMessage('I am well, thank you!')
- builder.addToolMessage('Tool response', 'call_123')
-
- const result = builder.getMessages()
- expect(result).toHaveLength(4)
- expect(result[0].role).toBe('system')
- expect(result[1].role).toBe('user')
- expect(result[2].role).toBe('assistant')
- expect(result[3].role).toBe('tool')
- })
-
- it('should return the same array reference (not immutable)', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addUserMessage(createMockThreadMessage('user', 'Test message'))
- const result1 = builder.getMessages()
-
- builder.addAssistantMessage('Response')
- const result2 = builder.getMessages()
-
- // getMessages() creates a new array each time, so references will be different
- expect(result1).not.toBe(result2) // Different references because getMessages creates new array
- expect(result1).toHaveLength(1) // First call had only 1 message
- expect(result2).toHaveLength(2) // Second call has 2 messages
- })
- })
-
- describe('content normalization', () => {
- it('should remove thinking content from the beginning', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addAssistantMessage(
- '<think>Let me analyze this...</think>The answer is 42.'
- )
-
- const result = builder.getMessages()
- expect(result[1].content).toBe('The answer is 42.')
- })
-
- it('should handle nested thinking tags', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addAssistantMessage(
- '<think>First thought<think>Nested</think>More thinking</think>Final answer'
- )
-
- const result = builder.getMessages()
- expect(result[1].content).toBe('More thinking</think>Final answer')
- })
-
- it('should handle multiple thinking blocks', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addAssistantMessage(
- '<think>First</think>Answer<think>Second</think>More content'
- )
-
- const result = builder.getMessages()
- expect(result[1].content).toBe('Answer<think>Second</think>More content')
- })
-
- it('should handle content without thinking tags', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addAssistantMessage('Just a normal response')
-
- const result = builder.getMessages()
- expect(result[1].content).toBe('Just a normal response')
- })
-
- it('should handle empty content after removing thinking', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addAssistantMessage('<think>Only thinking content</think>')
-
- const result = builder.getMessages()
- expect(result[1].content).toBe('')
- })
-
- it('should handle unclosed thinking tags', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addAssistantMessage(
- '<think>Unclosed thinking tag... Regular content'
- )
-
- const result = builder.getMessages()
- expect(result[1].content).toBe(
- '<think>Unclosed thinking tag... Regular content'
- )
- })
-
- it('should handle thinking tags with whitespace', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addAssistantMessage(
- '<think> \n Some thinking \n </think> \n Clean answer'
- )
-
- const result = builder.getMessages()
- expect(result[1].content).toBe('Clean answer')
- })
-
- it('should remove analysis channel reasoning content', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addAssistantMessage(
- '<|channel|>analysis<|message|>Let me analyze this step by step...<|start|>assistant<|channel|>final<|message|>The final answer is 42.'
- )
-
- const result = builder.getMessages()
- expect(result[1].content).toBe('The final answer is 42.')
- })
-
- it('should handle analysis channel without final message', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addAssistantMessage(
- '<|channel|>analysis<|message|>Only analysis content here...'
- )
-
- const result = builder.getMessages()
- expect(result[1].content).toBe('<|channel|>analysis<|message|>Only analysis content here...')
- })
-
- it('should handle analysis channel with multiline content', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addAssistantMessage(
- '<|channel|>analysis<|message|>Step 1: First analysis\nStep 2: Second analysis\nStep 3: Final analysis<|start|>assistant<|channel|>final<|message|>Based on my analysis, here is the result.'
- )
-
- const result = builder.getMessages()
- expect(result[1].content).toBe('Based on my analysis, here is the result.')
- })
-
- it('should handle both think and analysis channel tags', () => {
- const builder = new CompletionMessagesBuilder([])
-
- builder.addAssistantMessage(
- '<think>Initial thought</think><|channel|>analysis<|message|>Detailed analysis<|start|>assistant<|channel|>final<|message|>Final response'
- )
-
- const result = builder.getMessages()
- expect(result[1].content).toBe('Final response')
- })
- })
-
- describe('integration tests', () => {
- it('should handle complex conversation flow', () => {
- const threadMessages: ThreadMessage[] = [
- createMockThreadMessage('user', 'What is the weather like?'),
- createMockThreadMessage(
- 'assistant',
- '<think>I need to call weather API</think>Let me check the weather for you.'
- ),
- ]
-
- const builder = new CompletionMessagesBuilder(
- threadMessages,
- 'You are a weather assistant'
- )
-
- // Add tool call and response
- const toolCalls: ChatCompletionMessageToolCall[] = [
- {
- id: 'call_weather',
- type: 'function',
- function: {
- name: 'get_weather',
- arguments: '{"location": "user_location"}',
- },
- },
- ]
-
- builder.addAssistantMessage(
- 'Calling weather service...',
- undefined,
- toolCalls
- )
- builder.addToolMessage(
- '{"temperature": 72, "condition": "sunny"}',
- 'call_weather'
- )
- builder.addAssistantMessage(
- '<think>The weather is nice</think>The weather is 72°F and sunny!'
- )
-
- const result = builder.getMessages()
-
- // getMessages() adds filler messages between consecutive assistant messages
- expect(result).toHaveLength(7)
- expect(result[0].role).toBe('system')
- expect(result[1].role).toBe('user')
- expect(result[2].role).toBe('assistant')
- expect(result[2].content).toBe('Let me check the weather for you.')
- expect(result[3].role).toBe('user') // filler message inserted between consecutive assistant messages
- expect(result[4].role).toBe('assistant')
- expect(result[4].tool_calls).toEqual(toolCalls)
- expect(result[5].role).toBe('tool')
- expect(result[6].role).toBe('assistant')
- expect(result[6].content).toBe('The weather is 72°F and sunny!')
- })
-
- it('should handle empty thread messages with system instruction', () => {
- const builder = new CompletionMessagesBuilder([], 'System instruction')
-
- const result = builder.getMessages()
-
- expect(result).toHaveLength(2)
- expect(result[0]).toEqual({
- role: 'system',
- content: 'System instruction',
- })
- expect(result[1]).toEqual({
- role: 'user',
- content: '.',
- })
- })
- })
-})
-
diff --git a/web-app/src/lib/__tests__/models.test.ts b/web-app/src/lib/__tests__/models.test.ts
index bba4a64a1..00cd81589 100644
--- a/web-app/src/lib/__tests__/models.test.ts
+++ b/web-app/src/lib/__tests__/models.test.ts
@@ -13,14 +13,14 @@ import { ModelCapabilities } from '@/types/models'
vi.mock('token.js', () => ({
models: {
openai: {
- models: ['gpt-3.5-turbo', 'gpt-4'],
- supportsToolCalls: ['gpt-3.5-turbo', 'gpt-4'],
+ models: ['gpt-5', 'gpt-4'],
+ supportsToolCalls: ['gpt-5', 'gpt-4'],
supportsImages: ['gpt-4-vision-preview'],
},
anthropic: {
- models: ['claude-3-sonnet', 'claude-3-haiku'],
- supportsToolCalls: ['claude-3-sonnet'],
- supportsImages: ['claude-3-sonnet', 'claude-3-haiku'],
+ models: ['claude-sonnet-4-5', 'claude-3-haiku'],
+ supportsToolCalls: ['claude-sonnet-4-5'],
+ supportsImages: ['claude-sonnet-4-5', 'claude-3-haiku'],
},
mistral: {
models: ['mistral-7b', 'mistral-8x7b'],
@@ -35,20 +35,20 @@ vi.mock('token.js', () => ({
describe('defaultModel', () => {
it('returns first OpenAI model when no provider is given', () => {
- expect(defaultModel()).toBe('gpt-3.5-turbo')
+ expect(defaultModel()).toBe('gpt-5')
})
it('returns first OpenAI model when unknown provider is given', () => {
- expect(defaultModel('unknown')).toBe('gpt-3.5-turbo')
+ expect(defaultModel('unknown')).toBe('gpt-5')
})
it('returns first model for known providers', () => {
- expect(defaultModel('anthropic')).toBe('claude-3-sonnet')
- expect(defaultModel('mistral')).toBe('mistral-7b')
+ expect(defaultModel('anthropic')).toBe('claude-sonnet-4-5')
+ expect(defaultModel('mistral')).toBe('mistral-large-2411')
})
it('handles empty string provider', () => {
- expect(defaultModel('')).toBe('gpt-3.5-turbo')
+ expect(defaultModel('')).toBe('gpt-5')
})
})
@@ -237,42 +237,42 @@ describe('extractModelRepo', () => {
describe('getModelCapabilities', () => {
it('returns completion capability for all models', () => {
- const capabilities = getModelCapabilities('openai', 'gpt-3.5-turbo')
+ const capabilities = getModelCapabilities('openai', 'gpt-5')
expect(capabilities).toContain(ModelCapabilities.COMPLETION)
})
it('includes tools capability when model supports it', () => {
- const capabilities = getModelCapabilities('openai', 'gpt-3.5-turbo')
+ const capabilities = getModelCapabilities('openai', 'gpt-5')
expect(capabilities).toContain(ModelCapabilities.TOOLS)
expect(capabilities).toContain(ModelCapabilities.COMPLETION)
})
it('excludes tools capability when model does not support it', () => {
- const capabilities = getModelCapabilities('mistral', 'mistral-7b')
+ const capabilities = getModelCapabilities('mistral', 'mistral-nemo-2407')
expect(capabilities).not.toContain(ModelCapabilities.TOOLS)
expect(capabilities).toContain(ModelCapabilities.COMPLETION)
})
it('includes vision capability when model supports it', () => {
- const capabilities = getModelCapabilities('openai', 'gpt-4-vision-preview')
+ const capabilities = getModelCapabilities('openai', 'gpt-4o')
expect(capabilities).toContain(ModelCapabilities.VISION)
expect(capabilities).toContain(ModelCapabilities.COMPLETION)
})
it('excludes vision capability when model does not support it', () => {
- const capabilities = getModelCapabilities('openai', 'gpt-3.5-turbo')
+ const capabilities = getModelCapabilities('openai', 'gpt-4')
expect(capabilities).not.toContain(ModelCapabilities.VISION)
})
it('includes both tools and vision when model supports both', () => {
- const capabilities = getModelCapabilities('anthropic', 'claude-3-sonnet')
+ const capabilities = getModelCapabilities('anthropic', 'claude-sonnet-4-5')
expect(capabilities).toContain(ModelCapabilities.COMPLETION)
expect(capabilities).toContain(ModelCapabilities.TOOLS)
expect(capabilities).toContain(ModelCapabilities.VISION)
})
it('handles provider with no capability arrays gracefully', () => {
- const capabilities = getModelCapabilities('cohere', 'command')
+ const capabilities = getModelCapabilities('ai21', 'jamba-instruct')
expect(capabilities).toEqual([ModelCapabilities.COMPLETION])
expect(capabilities).not.toContain(ModelCapabilities.TOOLS)
expect(capabilities).not.toContain(ModelCapabilities.VISION)
@@ -286,7 +286,7 @@ describe('getModelCapabilities', () => {
})
it('handles model not in capability list', () => {
- const capabilities = getModelCapabilities('anthropic', 'claude-3-haiku')
+ const capabilities = getModelCapabilities('xai', 'grok-2-vision-1212')
expect(capabilities).toContain(ModelCapabilities.COMPLETION)
expect(capabilities).toContain(ModelCapabilities.VISION)
expect(capabilities).not.toContain(ModelCapabilities.TOOLS)
@@ -294,12 +294,12 @@ describe('getModelCapabilities', () => {
it('returns only completion for provider with partial capability data', () => {
// Mistral has supportsToolCalls but no supportsImages
- const capabilities = getModelCapabilities('mistral', 'mistral-7b')
+ const capabilities = getModelCapabilities('mistral', 'mistral-nemo-2407')
expect(capabilities).toEqual([ModelCapabilities.COMPLETION])
})
it('handles model that supports tools but not vision', () => {
- const capabilities = getModelCapabilities('mistral', 'mistral-8x7b')
+ const capabilities = getModelCapabilities('mistral', 'mistral-large-2411')
expect(capabilities).toContain(ModelCapabilities.COMPLETION)
expect(capabilities).toContain(ModelCapabilities.TOOLS)
expect(capabilities).not.toContain(ModelCapabilities.VISION)
diff --git a/web-app/src/lib/messages.ts b/web-app/src/lib/messages.ts
index 9b6dd50c9..5ba01d3da 100644
--- a/web-app/src/lib/messages.ts
+++ b/web-app/src/lib/messages.ts
@@ -1,8 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
-import { ChatCompletionMessageParam } from 'token.js'
-import { ChatCompletionMessageToolCall } from 'openai/resources'
import { ThreadMessage, ContentType, MessageStatus } from '@janhq/core'
-import { removeReasoningContent } from '@/utils/reasoning'
import type { UIMessage } from '@ai-sdk/react'
// Attachments are now handled upstream in newUserThreadContent
@@ -136,261 +133,6 @@ export type ToolResult = {
error?: string
}
-// Helper function to convert the tool's output part into an API content part
-const convertToolPartToApiContentPart = (part: ToolResult['content'][0]) => {
- if (part.text) {
- return { type: 'text', text: part.text }
- }
-
- // Handle base64 image data
- if (part.data) {
- // Assume default image type, though a proper tool should return the mime type
- const mimeType =
- part.type === 'image' ? 'image/png' : part.type || 'image/png'
- const dataUrl = `data:${mimeType};base64,${part.data}`
-
- return {
- type: 'image_url',
- image_url: {
- url: dataUrl,
- detail: 'auto',
- },
- }
- }
-
- // Handle pre-formatted image URL
- if (part.image_url) {
- return { type: 'image_url', image_url: part.image_url }
- }
-
- // Fallback to text stringification for structured but unhandled data
- return { type: 'text', text: JSON.stringify(part) }
-}
-
-/**
- * @fileoverview Helper functions for creating chat completion request.
- * These functions are used to create chat completion request objects
- */
-export class CompletionMessagesBuilder {
- private messages: ChatCompletionMessageParam[] = []
-
- constructor(messages: ThreadMessage[], systemInstruction?: string) {
- if (systemInstruction) {
- this.messages.push({
- role: 'system',
- content: systemInstruction,
- })
- }
- this.messages.push(
- ...messages
- .filter((e) => !e.metadata?.error)
- .map<ChatCompletionMessageParam>((msg) => {
- const param = this.toCompletionParamFromThread(msg)
- // In constructor context, normalize empty user text to a placeholder
- if (
- param.role === 'user' &&
- typeof param.content === 'string' &&
- param.content === ''
- ) {
- return { ...param, content: '.' }
- }
- return param
- })
- )
- }
-
- // Normalize a ThreadMessage into a ChatCompletionMessageParam for Token.js
- private toCompletionParamFromThread(
- msg: ThreadMessage
- ): ChatCompletionMessageParam {
- const inlineFileContents = Array.isArray(
- (msg.metadata as any)?.inline_file_contents
- )
- ? ((msg.metadata as any)?.inline_file_contents as Array<{
- name?: string
- content?: string
- }>).filter((f) => f?.content)
- : []
-
- const buildInlineText = (base: string) => {
- if (!inlineFileContents.length) return base
- const formatted = inlineFileContents
- .map((f) => `File: ${f.name || 'attachment'}\n${f.content ?? ''}`)
- .join('\n\n')
- return base ? `${base}\n\n${formatted}` : formatted
- }
-
- if (msg.role === 'assistant') {
- return {
- role: 'assistant',
- content: removeReasoningContent(msg.content?.[0]?.text?.value || '.'),
- } as ChatCompletionMessageParam
- }
-
- // System messages are uncommon here; normalize to plain text
- if (msg.role === 'system') {
- return {
- role: 'system',
- content: msg.content?.[0]?.text?.value || '.',
- } as ChatCompletionMessageParam
- }
-
- // User messages: handle multimodal content
- if (Array.isArray(msg.content) && msg.content.length > 1) {
- const content = msg.content.map((part: ThreadContent) => {
- if (part.type === ContentType.Text) {
- return {
- type: 'text' as const,
- text: buildInlineText(part.text?.value ?? ''),
- }
- }
- if (part.type === ContentType.Image) {
- return {
- type: 'image_url' as const,
- image_url: {
- url: part.image_url?.url || '',
- detail: part.image_url?.detail || 'auto',
- },
- }
- }
- // Fallback for unknown content types
- return { type: 'text' as const, text: '' }
- })
- return { role: 'user', content } as ChatCompletionMessageParam
- }
- // Single text part
- const text = msg?.content?.[0]?.text?.value ?? '.'
- return { role: 'user', content: buildInlineText(text) }
- }
-
- /**
- * Add a user message to the messages array from a parsed ThreadMessage.
- * Upstream code should construct the message via newUserThreadContent
- * and pass it here to avoid duplicated logic.
- */
- addUserMessage(message: ThreadMessage) {
- if (message.role !== 'user') {
- throw new Error('addUserMessage expects a user ThreadMessage')
- }
- // Ensure no consecutive user messages
- if (this.messages[this.messages.length - 1]?.role === 'user') {
- this.messages.pop()
- }
- this.messages.push(this.toCompletionParamFromThread(message))
- }
-
- /**
- * Add an assistant message to the messages array.
- * @param content - The content of the assistant message.
- * @param refusal - Optional refusal message.
- * @param calls - Optional tool calls associated with the message.
- */
- addAssistantMessage(
- content: string,
- refusal?: string,
- calls?: ChatCompletionMessageToolCall[]
- ) {
- this.messages.push({
- role: 'assistant',
- content: removeReasoningContent(content),
- refusal: refusal,
- tool_calls: calls,
- })
- }
-
- /**
- * Add a tool message to the messages array.
- * @param content - The content of the tool message (string or ToolResult object).
- * @param toolCallId - The ID of the tool call associated with the message.
- */
- addToolMessage(result: string | ToolResult, toolCallId: string) {
- let content: string | any[] = ''
-
- // Handle simple string case
- if (typeof result === 'string') {
- content = result
- } else {
- // Check for multimodal content (more than just a simple text string)
- const hasMultimodalContent = result.content?.some(
- (p) => p.data || p.image_url
- )
-
- if (hasMultimodalContent) {
- // Build the structured content array
- content = result.content.map(convertToolPartToApiContentPart)
- } else if (result.content?.[0]?.text) {
- // Standard text case
- content = result.content[0].text
- } else if (result.error) {
- // Error case
- content = `Tool execution failed: ${result.error}`
- } else {
- // Fallback: serialize the whole result structure if content is unexpected
- try {
- content = JSON.stringify(result)
- } catch {
- content = 'Tool call completed, unexpected output format.'
- }
- }
- }
- this.messages.push({
- role: 'tool',
- // for role 'tool', need to use 'as ChatCompletionMessageParam'
- content: content as any,
- tool_call_id: toolCallId,
- })
- }
-
- /**
- * Return the messages array.
- * @returns The array of chat completion messages.
- */
- getMessages(): ChatCompletionMessageParam[] {
- const result: ChatCompletionMessageParam[] = []
- let prevRole: string | undefined
-
- for (let i = 0; i < this.messages.length; i++) {
- const msg = this.messages[i]
-
- // Handle first message
- if (i === 0) {
- if (msg.role === 'user') {
- result.push(msg)
- prevRole = msg.role
- continue
- } else if (msg.role === 'system') {
- result.push(msg)
- prevRole = msg.role
- // Check next message
- const nextMsg = this.messages[i + 1]
- if (!nextMsg || nextMsg.role !== 'user') {
- result.push({ role: 'user', content: '.' })
- prevRole = 'user'
- }
- continue
- } else {
- // First message is not user or system — insert user message
- result.push({ role: 'user', content: '.' })
- result.push(msg)
- prevRole = msg.role
- continue
- }
- }
-
- // Avoid consecutive same roles
- if (msg.role === prevRole) {
- const oppositeRole = prevRole === 'assistant' ? 'user' : 'assistant'
- result.push({ role: oppositeRole, content: '.' })
- prevRole = oppositeRole
- }
- result.push(msg)
- prevRole = msg.role
- }
-
- return result
- }
-}
-
/**
* Parse reasoning segments from the given text.
* @param text - The text to parse reasoning from.
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index 7e5de5a08..93433d5ae 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -51,6 +51,7 @@ import {
OpenAICompatibleChatLanguageModel,
} from '@ai-sdk/openai-compatible'
import { createAnthropic } from '@ai-sdk/anthropic'
+import { createXai } from '@ai-sdk/xai'
import { invoke } from '@tauri-apps/api/core'
import { SessionInfo } from '@janhq/core'
import { fetch as httpFetch } from '@tauri-apps/plugin-http'
@@ -180,6 +181,9 @@ export class ModelFactory {
case 'perplexity':
case 'moonshot':
return this.createOpenAICompatibleModel(modelId, provider)
+
+ case 'xai':
+ return this.createXaiModel(modelId, provider)
default:
return this.createOpenAICompatibleModel(modelId, provider, parameters)
}
@@ -390,6 +394,33 @@ export class ModelFactory {
return openai(modelId)
}
+ /**
+ * Create an XAI (Grok) model using the official AI SDK
+ */
+ private static createXaiModel(
+ modelId: string,
+ provider: ProviderObject,
+ parameters: Record<string, unknown> = {}
+ ): 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 xai = createXai({
+ apiKey: provider.api_key,
+ baseURL: provider.base_url,
+ headers: Object.keys(headers).length > 0 ? headers : undefined,
+ fetch: createCustomFetch(httpFetch, parameters),
+ })
+
+ return xai(modelId)
+ }
+
/**
* Create an OpenAI-compatible model for providers that support the OpenAI API format
*/
diff --git a/web-app/src/lib/models.ts b/web-app/src/lib/models.ts
index 25a35c7f3..2c6736032 100644
--- a/web-app/src/lib/models.ts
+++ b/web-app/src/lib/models.ts
@@ -1,4 +1,4 @@
-import { models } from 'token.js'
+import { providerModels as models } from '@/constants/models'
import { ModelCapabilities } from '@/types/models'
export const defaultModel = (provider?: string) => {
diff --git a/web-app/src/lib/utils.ts b/web-app/src/lib/utils.ts
index e30409200..992c8b273 100644
--- a/web-app/src/lib/utils.ts
+++ b/web-app/src/lib/utils.ts
@@ -4,26 +4,25 @@ import type { Node, Position } from 'unist'
import type { Code, Paragraph, Parent, Text } from 'mdast'
import { visit } from 'unist-util-visit'
import { ExtensionManager } from './extension'
-import path from "path"
-
+import path from 'path'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function basenameNoExt(filePath: string): string {
- const base = path.basename(filePath);
- const VALID_EXTENSIONS = [".tar.gz", ".zip"];
+ const base = path.basename(filePath)
+ const VALID_EXTENSIONS = ['.tar.gz', '.zip']
// handle VALID extensions first
for (const ext of VALID_EXTENSIONS) {
if (base.toLowerCase().endsWith(ext)) {
- return base.slice(0, -ext.length);
+ return base.slice(0, -ext.length)
}
}
// fallback: remove only the last extension
- return base.slice(0, -path.extname(base).length);
+ return base.slice(0, -path.extname(base).length)
}
/**
@@ -42,12 +41,12 @@ export function disableIndentedCodeBlockPlugin() {
const textNode: Text = {
type: 'text',
value: node.value,
- position: nodePosition
+ position: nodePosition,
}
const paragraphNode: Paragraph = {
type: 'paragraph',
children: [textNode],
- position: nodePosition
+ position: nodePosition,
}
parent.children[index] = paragraphNode
}
@@ -88,6 +87,8 @@ export function getProviderLogo(provider: string) {
return '/images/model-provider/openai.svg'
case 'azure':
return '/images/model-provider/azure.svg'
+ case 'xai':
+ return '/images/model-provider/xai.svg'
default:
return undefined
}
@@ -109,6 +110,8 @@ export const getProviderTitle = (provider: string) => {
return 'Gemini'
case 'huggingface':
return 'Hugging Face'
+ case 'xai':
+ return 'xAI'
default:
return provider.charAt(0).toUpperCase() + provider.slice(1)
}
diff --git a/web-app/src/services/providers/tauri.ts b/web-app/src/services/providers/tauri.ts
index 82dd4a4bf..acd5e7844 100644
--- a/web-app/src/services/providers/tauri.ts
+++ b/web-app/src/services/providers/tauri.ts
@@ -2,8 +2,8 @@
* Tauri Providers Service - Desktop implementation
*/
-import { models as providerModels } from 'token.js'
import { predefinedProviders } from '@/constants/providers'
+import { providerModels } from '@/constants/models'
import { EngineManager, SettingComponentProps } from '@janhq/core'
import { ModelCapabilities } from '@/types/models'
import { modelSettings } from '@/lib/predefined'
diff --git a/web-app/src/utils/__tests__/reasoning.test.ts b/web-app/src/utils/__tests__/reasoning.test.ts
deleted file mode 100644
index 76c7853d9..000000000
--- a/web-app/src/utils/__tests__/reasoning.test.ts
+++ /dev/null
@@ -1,381 +0,0 @@
-import { describe, it, expect, beforeEach } from 'vitest'
-import {
- ReasoningProcessor,
- extractReasoningFromMessage,
-} from '../reasoning'
-import { CompletionResponseChunk } from 'token.js'
-import { chatCompletionChunk, chatCompletionRequestMessage } from '@janhq/core'
-
-describe('extractReasoningFromMessage', () => {
- it('should extract reasoning from message with reasoning_content property', () => {
- const message = {
- role: 'assistant' as const,
- content: 'Hello',
- reasoning_content: 'This is my reasoning content',
- }
-
- const result = extractReasoningFromMessage(message)
- expect(result).toBe('This is my reasoning content')
- })
-
- it('should extract reasoning from message with legacy reasoning property', () => {
- const message = {
- role: 'assistant' as const,
- content: 'Hello',
- reasoning: 'This is my reasoning',
- }
-
- const result = extractReasoningFromMessage(message)
- expect(result).toBe('This is my reasoning')
- })
-
- it('should prefer reasoning_content over reasoning property', () => {
- const message = {
- role: 'assistant' as const,
- content: 'Hello',
- reasoning_content: 'New reasoning content',
- reasoning: 'Old reasoning',
- }
-
- const result = extractReasoningFromMessage(message)
- expect(result).toBe('New reasoning content')
- })
-
- it('should return null for message without reasoning', () => {
- const message = {
- role: 'assistant' as const,
- content: 'Hello',
- }
-
- const result = extractReasoningFromMessage(message)
- expect(result).toBeNull()
- })
-
- it('should return null for null/undefined message', () => {
- expect(extractReasoningFromMessage(null as any)).toBeNull()
- expect(extractReasoningFromMessage(undefined as any)).toBeNull()
- })
-})
-
-describe('ReasoningProcessor', () => {
- let processor: ReasoningProcessor
-
- beforeEach(() => {
- processor = new ReasoningProcessor()
- })
-
- describe('processReasoningChunk', () => {
- it('should start reasoning with opening think tag using reasoning_content', () => {
- const chunk: chatCompletionChunk = {
- choices: [{
- delta: {
- reasoning_content: 'Let me think about this...',
- },
- }],
- }
-
- const result = processor.processReasoningChunk(chunk)
- expect(result).toBe('<think>Let me think about this...')
- expect(processor.isReasoningInProgress()).toBe(true)
- })
-
- it('should start reasoning with opening think tag using legacy reasoning', () => {
- const chunk: chatCompletionChunk = {
- choices: [{
- delta: {
- reasoning: 'Let me think about this...',
- },
- }],
- }
-
- const result = processor.processReasoningChunk(chunk)
- expect(result).toBe('<think>Let me think about this...')
- expect(processor.isReasoningInProgress()).toBe(true)
- })
-
- it('should continue reasoning without opening tag', () => {
- // Start reasoning
- const chunk1: chatCompletionChunk = {
- choices: [{
- delta: {
- reasoning_content: 'First part',
- },
- }],
- }
- processor.processReasoningChunk(chunk1)
-
- // Continue reasoning
- const chunk2: chatCompletionChunk = {
- choices: [{
- delta: {
- reasoning_content: ' second part',
- },
- }],
- }
-
- const result = processor.processReasoningChunk(chunk2)
- expect(result).toBe(' second part')
- expect(processor.isReasoningInProgress()).toBe(true)
- })
-
- it('should end reasoning when content starts', () => {
- // Start reasoning
- const chunk1: chatCompletionChunk = {
- choices: [{
- delta: {
- reasoning_content: 'Thinking...',
- },
- }],
- }
- processor.processReasoningChunk(chunk1)
-
- // End reasoning with content
- const chunk2: chatCompletionChunk = {
- choices: [{
- delta: {
- content: 'Now I respond',
- },
- }],
- }
-
- const result = processor.processReasoningChunk(chunk2)
- expect(result).toBe('</think>')
- expect(processor.isReasoningInProgress()).toBe(false)
- })
-
- it('should handle empty reasoning chunks', () => {
- const chunk: chatCompletionChunk = {
- choices: [{
- delta: {
- reasoning_content: '',
- },
- }],
- }
-
- const result = processor.processReasoningChunk(chunk)
- expect(result).toBe('')
- expect(processor.isReasoningInProgress()).toBe(false)
- })
-
- it('should handle whitespace-only reasoning', () => {
- const chunk: chatCompletionChunk = {
- choices: [{
- delta: {
- reasoning_content: ' \n ',
- },
- }],
- }
-
- const result = processor.processReasoningChunk(chunk)
- expect(result).toBe('')
- expect(processor.isReasoningInProgress()).toBe(false)
- })
-
- it('should handle non-string reasoning', () => {
- const chunk: chatCompletionChunk = {
- choices: [{
- delta: {
- reasoning_content: null as any,
- },
- }],
- }
-
- const result = processor.processReasoningChunk(chunk)
- expect(result).toBe('')
- expect(processor.isReasoningInProgress()).toBe(false)
- })
-
- it('should handle chunk without choices', () => {
- const chunk: chatCompletionChunk = {
- choices: undefined as any,
- }
-
- const result = processor.processReasoningChunk(chunk)
- expect(result).toBe('')
- expect(processor.isReasoningInProgress()).toBe(false)
- })
-
- it('should handle chunk without delta', () => {
- const chunk: chatCompletionChunk = {
- choices: [{
- delta: undefined as any,
- }],
- }
-
- const result = processor.processReasoningChunk(chunk)
- expect(result).toBe('')
- expect(processor.isReasoningInProgress()).toBe(false)
- })
-
- it('should handle content without active reasoning', () => {
- const chunk: chatCompletionChunk = {
- choices: [{
- delta: {
- content: 'Regular content',
- },
- }],
- }
-
- const result = processor.processReasoningChunk(chunk)
- expect(result).toBe('')
- expect(processor.isReasoningInProgress()).toBe(false)
- })
- })
-
- describe('finalize', () => {
- it('should close reasoning if still active', () => {
- // Start reasoning
- const chunk: chatCompletionChunk = {
- choices: [{
- delta: {
- reasoning_content: 'Unfinished thinking',
- },
- }],
- }
- processor.processReasoningChunk(chunk)
-
- const result = processor.finalize()
- expect(result).toBe('</think>')
- expect(processor.isReasoningInProgress()).toBe(false)
- })
-
- it('should return empty string if no active reasoning', () => {
- const result = processor.finalize()
- expect(result).toBe('')
- expect(processor.isReasoningInProgress()).toBe(false)
- })
-
- it('should handle multiple finalize calls', () => {
- // Start reasoning
- const chunk: chatCompletionChunk = {
- choices: [{
- delta: {
- reasoning_content: 'Thinking',
- },
- }],
- }
- processor.processReasoningChunk(chunk)
-
- // First finalize
- const result1 = processor.finalize()
- expect(result1).toBe('</think>')
-
- // Second finalize should return empty
- const result2 = processor.finalize()
- expect(result2).toBe('')
- })
- })
-
- describe('isReasoningInProgress', () => {
- it('should track reasoning state correctly', () => {
- expect(processor.isReasoningInProgress()).toBe(false)
-
- // Start reasoning
- const chunk1: chatCompletionChunk = {
- choices: [{
- delta: {
- reasoning_content: 'Start thinking',
- },
- }],
- }
- processor.processReasoningChunk(chunk1)
- expect(processor.isReasoningInProgress()).toBe(true)
-
- // End with content
- const chunk2: chatCompletionChunk = {
- choices: [{
- delta: {
- content: 'Response',
- },
- }],
- }
- processor.processReasoningChunk(chunk2)
- expect(processor.isReasoningInProgress()).toBe(false)
- })
- })
-
- describe('integration scenarios', () => {
- it('should handle complete reasoning flow', () => {
- const chunks: chatCompletionChunk[] = [
- {
- choices: [{
- delta: { reasoning_content: 'Let me think' },
- }],
- },
- {
- choices: [{
- delta: { reasoning_content: ' about this problem' },
- }],
- },
- {
- choices: [{
- delta: { reasoning_content: ' step by step.' },
- }],
- },
- {
- choices: [{
- delta: { content: 'Based on my analysis,' },
- }],
- },
- {
- choices: [{
- delta: { content: ' the answer is 42.' },
- }],
- },
- ]
-
- const results = chunks.map(chunk => processor.processReasoningChunk(chunk))
-
- expect(results[0]).toBe('<think>Let me think')
- expect(results[1]).toBe(' about this problem')
- expect(results[2]).toBe(' step by step.')
- expect(results[3]).toBe('</think>')
- expect(results[4]).toBe('')
-
- expect(processor.isReasoningInProgress()).toBe(false)
- })
-
- it('should handle reasoning without content', () => {
- const chunk: chatCompletionChunk = {
- choices: [{
- delta: { reasoning_content: 'Only reasoning, no content' },
- }],
- }
-
- const result1 = processor.processReasoningChunk(chunk)
- expect(result1).toBe('<think>Only reasoning, no content')
-
- const result2 = processor.finalize()
- expect(result2).toBe('</think>')
- })
-
- it('should handle mixed reasoning and content chunks', () => {
- // Reasoning then content then reasoning again (edge case)
- const chunk1: chatCompletionChunk = {
- choices: [{
- delta: { reasoning_content: 'First thought' },
- }],
- }
-
- const chunk2: chatCompletionChunk = {
- choices: [{
- delta: { content: 'Some content' },
- }],
- }
-
- const chunk3: chatCompletionChunk = {
- choices: [{
- delta: { reasoning_content: 'Second thought' },
- }],
- }
-
- const result1 = processor.processReasoningChunk(chunk1)
- const result2 = processor.processReasoningChunk(chunk2)
- const result3 = processor.processReasoningChunk(chunk3)
-
- expect(result1).toBe('<think>First thought')
- expect(result2).toBe('</think>')
- expect(result3).toBe('<think>Second thought')
- })
- })
-})
diff --git a/web-app/src/utils/reasoning.ts b/web-app/src/utils/reasoning.ts
index 32b2958e6..b5a29c9f2 100644
--- a/web-app/src/utils/reasoning.ts
+++ b/web-app/src/utils/reasoning.ts
@@ -1,6 +1,4 @@
-import { CompletionResponseChunk } from 'token.js'
import {
- chatCompletionChunk,
ChatCompletionMessage,
chatCompletionRequestMessage,
} from '@janhq/core'
@@ -51,61 +49,3 @@ export function extractReasoningFromMessage(
const extendedMessage = message as chatCompletionRequestMessage
return getReasoning(extendedMessage)
}
-
-// Extract reasoning from a chunk (for streaming responses)
-function extractReasoningFromChunk(
- chunk: CompletionResponseChunk | chatCompletionChunk
-): string | null {
- if (!chunk.choices?.[0]?.delta) return null
-
- const delta = chunk.choices[0].delta as chatCompletionRequestMessage
- const reasoning = getReasoning(delta)
-
- // Return null for falsy values, non-strings, or whitespace-only strings
- if (!reasoning || typeof reasoning !== 'string' || !reasoning.trim())
- return null
-
- return reasoning
-}
-
-// Tracks reasoning state and appends reasoning tokens with proper think tags
-export class ReasoningProcessor {
- private isReasoningActive = false
-
- processReasoningChunk(
- chunk: CompletionResponseChunk | chatCompletionChunk
- ): string {
- const reasoning = extractReasoningFromChunk(chunk)
- const chunkContent = chunk.choices?.[0]?.delta?.content || ''
-
- // Handle reasoning tokens
- if (reasoning) {
- if (!this.isReasoningActive) {
- this.isReasoningActive = true
- return '<think>' + reasoning
- }
- return reasoning
- }
-
- // Handle reasoning end when content starts
- if (this.isReasoningActive && chunkContent) {
- this.isReasoningActive = false
- return '</think>'
- }
-
- // No reasoning to process
- return ''
- }
-
- finalize(): string {
- if (this.isReasoningActive) {
- this.isReasoningActive = false
- return '</think>'
- }
- return ''
- }
-
- isReasoningInProgress(): boolean {
- return this.isReasoningActive
- }
-}