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.

fix: out of context handling

Louisdd6e71d36c4a
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 274348010..69a49ba42 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -357,7 +357,7 @@ export const MessageItem = memo(
{/* Message actions for assistant messages (non-tool) */}
{message.role === 'assistant' &&
- message.parts.some((p) => p.type === 'text') && (
+ message.parts.some((p) => p.type === 'text' && p.text.length > 0) && (
<div className="flex items-center gap-2 text-main-view-fg/60 text-xs">
<div
className={cn(
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 5cef9149e..b85863e3b 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -41,9 +41,6 @@ export type ServiceHub = {
Array<{ name: string; description: string; inputSchema: unknown }>
>
}
- models(): {
- startModel(provider: ProviderObject, model: string): Promise<unknown>
- }
}
export class CustomChatTransport implements ChatTransport<UIMessage> {
@@ -225,20 +222,17 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
const updatedProvider = useModelProvider
.getState()
.getProviderByName(this.provider.provider)
- // Start the model (this will be a no-op for remote providers)
- await this.serviceHub
- .models()
- .startModel(updatedProvider ?? this.provider, this.modelId)
// Create the model using the factory
+ // For llamacpp provider, startModel is called internally in ModelFactory.createLlamaCppModel
this.model = await ModelFactory.createModel(
this.modelId,
updatedProvider ?? this.provider
)
} catch (error) {
- console.error('Failed to start model:', error)
+ console.error('Failed to create model:', error)
throw new Error(
- `Failed to start model: ${error instanceof Error ? error.message : String(error)}`
+ `Failed to create model: ${error instanceof Error ? error.message : JSON.stringify(error)}`
)
}
} else {
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index 5036dea04..87cf89140 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -106,7 +106,7 @@ export class ModelFactory {
switch (providerName) {
case 'llamacpp':
- return this.createLlamaCppModel(modelId)
+ return this.createLlamaCppModel(modelId, provider)
case 'anthropic':
return this.createAnthropicModel(modelId, provider)
@@ -131,11 +131,29 @@ export class ModelFactory {
}
/**
- * Create a llamacpp model by finding the running session
+ * Create a llamacpp model by starting the model and finding the running session
*/
private static async createLlamaCppModel(
- modelId: string
+ modelId: string,
+ provider?: ProviderObject
): Promise<LanguageModel> {
+ // Start the model first if provider is available
+ if (provider) {
+ try {
+ const { useServiceStore } = await import('@/hooks/useServiceHub')
+ const serviceHub = useServiceStore.getState().serviceHub
+
+ if (serviceHub) {
+ await serviceHub.models().startModel(provider, modelId)
+ }
+ } catch (error) {
+ console.error('Failed to start llamacpp model:', error)
+ throw new Error(
+ `Failed to start model: ${error instanceof Error ? error.message : JSON.stringify(error)}`
+ )
+ }
+ }
+
// Get session info which includes port and api_key
const sessionInfo = await invoke<SessionInfo | null>(
'plugin:llamacpp|find_session_by_model',
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index fc74fc023..34b00077c 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -45,6 +45,10 @@ import { processAttachmentsForSend } from '@/lib/attachmentProcessing'
import { useAttachments } from '@/hooks/useAttachments'
import { PromptProgress } from '@/components/PromptProgress'
import { useToolAvailable } from '@/hooks/useToolAvailable'
+import { OUT_OF_CONTEXT_SIZE } from '@/utils/error'
+import { useContextSizeApproval } from '@/hooks/useModelContextApproval'
+import { Button } from '@/components/ui/button'
+import { IconAlertCircle } from '@tabler/icons-react'
const CHAT_STATUS = {
STREAMING: 'streaming',
@@ -74,6 +78,11 @@ function ThreadDetail() {
const isMobile = useMobileScreen()
useTools()
+ // Context size approval for out-of-context errors
+ const showApprovalModal = useContextSizeApproval(
+ (state) => state.showApprovalModal
+ )
+
// Get attachments for this thread
const attachmentsKey = threadId ?? NEW_THREAD_ATTACHMENT_KEY
const getAttachments = useChatAttachments((state) => state.getAttachments)
@@ -151,6 +160,7 @@ function ThreadDetail() {
const {
messages: chatMessages,
status,
+ error,
sendMessage,
regenerate,
setMessages: setChatMessages,
@@ -533,12 +543,7 @@ function ThreadDetail() {
}
})()
}
- }, [
- threadId,
- languageModelId,
- languageModelProvider,
- processAndSendMessage,
- ])
+ }, [threadId, languageModelId, languageModelProvider, processAndSendMessage])
// Handle submit from ChatInput
const handleSubmit = useCallback(
@@ -600,6 +605,94 @@ function ThreadDetail() {
// and generating a new response from the selected message
regenerate(messageId ? { messageId } : undefined)
}
+
+ // Handler for increasing context size or enabling context shift
+ const handleContextSizeIncrease = useCallback(async () => {
+ if (!selectedModel) return
+
+ const result = await showApprovalModal()
+ if (!result) return
+
+ const updateProvider = useModelProvider.getState().updateProvider
+ const provider = getProviderByName(selectedProvider)
+ if (!provider) return
+
+ const modelIndex = provider.models.findIndex(
+ (m) => m.id === selectedModel.id
+ )
+ if (modelIndex === -1) return
+
+ const model = provider.models[modelIndex]
+
+ if (result === 'ctx_len') {
+ // Increase context length by 50%
+ const currentCtxLen =
+ (model.settings?.ctx_len?.controller_props?.value as number) ?? 8192
+ const newCtxLen = Math.round(Math.max(8192, currentCtxLen) * 1.5)
+
+ const updatedModel = {
+ ...model,
+ settings: {
+ ...model.settings,
+ ctx_len: {
+ ...(model.settings?.ctx_len ?? {}),
+ controller_props: {
+ ...(model.settings?.ctx_len?.controller_props ?? {}),
+ value: newCtxLen,
+ },
+ },
+ },
+ }
+
+ const updatedModels = [...provider.models]
+ updatedModels[modelIndex] = updatedModel as Model
+
+ updateProvider(provider.provider, {
+ models: updatedModels,
+ })
+
+ await serviceHub.models().stopModel(selectedModel.id)
+
+ setTimeout(() => {
+ handleRegenerate()
+ }, 1000)
+ } else if (result === 'context_shift') {
+ // Enable context shift
+ const updatedModel = {
+ ...model,
+ settings: {
+ ...model.settings,
+ context_shift: {
+ ...(model.settings?.context_shift ?? {}),
+ controller_props: {
+ ...(model.settings?.context_shift?.controller_props ?? {}),
+ value: true,
+ },
+ },
+ },
+ }
+
+ const updatedModels = [...provider.models]
+ updatedModels[modelIndex] = updatedModel as Model
+
+ updateProvider(provider.provider, {
+ models: updatedModels,
+ })
+
+ await serviceHub.models().stopModel(selectedModel.id)
+
+ setTimeout(() => {
+ handleRegenerate()
+ }, 1000)
+ }
+ }, [
+ selectedModel,
+ selectedProvider,
+ getProviderByName,
+ showApprovalModal,
+ serviceHub,
+ ])
+
const threadModel = useMemo(() => thread?.model, [thread])
if (!threadModel) return null
@@ -657,6 +750,36 @@ function ThreadDetail() {
)
})}
{status === CHAT_STATUS.SUBMITTED && <PromptProgress />}
+ {error && (
+ <div className="px-4 py-3 mx-4 my-2 rounded-lg border border-destructive/50 bg-destructive/10">
+ <div className="flex items-start gap-3">
+ <IconAlertCircle className="size-5 text-destructive flex-shrink-0 mt-0.5" />
+ <div className="flex-1">
+ <p className="text-sm font-medium text-destructive mb-1">
+ Error generating response
+ </p>
+ <p className="text-sm text-main-view-fg/70">
+ {error.message}
+ </p>
+ {(error.message.toLowerCase().includes('context') &&
+ (error.message.toLowerCase().includes('size') ||
+ error.message.toLowerCase().includes('length') ||
+ error.message.toLowerCase().includes('limit'))) ||
+ error.message === OUT_OF_CONTEXT_SIZE ? (
+ <Button
+ variant="outline"
+ size="sm"
+ className="mt-3"
+ onClick={handleContextSizeIncrease}
+ >
+ <IconAlertCircle className="size-4 mr-2" />
+ Increase Context Size
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ )}
</ConversationContent>
<ConversationScrollButton />
</Conversation>