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(chat): let a model without tool support take documents as prompt text (#9388)

Thinh Le44aee093ae5a
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index f0d2feba6..3acc2e31e 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -106,6 +106,7 @@ import {
import {
applyIngestionChoices,
needsIngestionChoice,
+ parseModeForModel,
promptIngestionChoices,
resolveAutoInlineBudget,
} from '@/lib/attachmentProcessing'
@@ -1106,6 +1107,8 @@ const ChatInput = memo(function ChatInput({
const paths = Array.isArray(selection) ? selection : [selection]
if (!paths.length) return
+ const modelSupportsTools = !!selectedModel?.capabilities?.includes('tools')
+
// Prepare attachments with file sizes
const preparedAttachments: Attachment[] = []
for (const p of paths) {
@@ -1124,7 +1127,7 @@ const ChatInput = memo(function ChatInput({
path: p,
fileType,
size,
- parseMode: parsePreference,
+ parseMode: parseModeForModel(parsePreference, modelSupportsTools),
})
)
}
@@ -1179,6 +1182,12 @@ const ChatInput = memo(function ChatInput({
}
if (newDocAttachments.length > 0) {
+ if (!modelSupportsTools) {
+ toast.info('Documents are added to the prompt', {
+ description:
+ "This model can't search files, so each document is sent as text with your message.",
+ })
+ }
await processNewDocumentAttachments(newDocAttachments)
}
} catch (e) {
@@ -2378,10 +2387,7 @@ const ChatInput = memo(function ChatInput({
</DropdownMenuItem>
)}
{/* RAG document attachments - desktop-only via dialog; shown when feature enabled */}
- <DropdownMenuItem
- onClick={handleAttachDocsIngest}
- disabled={!selectedModel?.capabilities?.includes('tools')}
- >
+ <DropdownMenuItem onClick={handleAttachDocsIngest}>
{ingestingDocs ? (
<IconLoader2
size={18}
diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsx
index 646eb28a2..59201fddb 100644
--- a/web-app/src/containers/__tests__/ChatInput.test.tsx
+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx
@@ -852,4 +852,22 @@ describe('ChatInput', () => {
}
})
})
+
+ // #9363: the option was greyed out, with no reason given, for any model
+ // without the `tools` capability, so such a model could take no document at
+ // all. A document can still go into the prompt as text.
+ describe('document attachments', () => {
+ const attachDocs = () =>
+ screen.getByText('Add documents or files').closest('button')!
+
+ it('stay available for a model that cannot call tools', () => {
+ selectedModelOverride = {
+ id: 'no-tools-model',
+ capabilities: ['completion'],
+ provider: 'llamacpp',
+ }
+ renderInput()
+ expect(attachDocs()).not.toBeDisabled()
+ })
+ })
})
diff --git a/web-app/src/lib/__tests__/attachmentProcessing.test.ts b/web-app/src/lib/__tests__/attachmentProcessing.test.ts
index 6e68d23b3..77ad626b3 100644
--- a/web-app/src/lib/__tests__/attachmentProcessing.test.ts
+++ b/web-app/src/lib/__tests__/attachmentProcessing.test.ts
@@ -2,12 +2,14 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
applyIngestionChoices,
needsIngestionChoice,
+ parseModeForModel,
processAttachmentsForSend,
promptIngestionChoices,
resolveAutoInlineBudget,
type AttachmentProcessingResult,
} from '../attachmentProcessing'
import type { Attachment } from '@/types/attachment'
+import type { ServiceHub } from '@/services'
import { useAttachmentIngestionPrompt } from '@/hooks/useAttachmentIngestionPrompt'
// Minimal mock for ServiceHub methods used by processAttachmentsForSend
@@ -160,6 +162,42 @@ describe('processAttachmentsForSend', () => {
expect(result.hasEmbeddedDocuments).toBe(true)
})
+ it('rejects a document that cannot be read as text for a model without tool support', async () => {
+ const failingParse = vi.fn().mockRejectedValue(new Error('parse failed'))
+ const hub = {
+ ...createMockServiceHub(),
+ rag: () => ({ parseDocument: failingParse }),
+ }
+ const doc = docAttachment({ parseMode: 'inline' })
+
+ await expect(
+ processAttachmentsForSend({
+ attachments: [doc],
+ threadId,
+ serviceHub: hub as unknown as ServiceHub,
+ parsePreference: 'auto',
+ modelSupportsTools: false,
+ })
+ ).rejects.toThrow(/can't search files/)
+ })
+
+ it('inlines a large document for a model without tool support whatever the budget', async () => {
+ const hub = createMockServiceHub()
+ const doc = docAttachment({ parseMode: 'auto' })
+
+ const result = await processAttachmentsForSend({
+ attachments: [doc],
+ threadId,
+ serviceHub: hub as unknown as ServiceHub,
+ parsePreference: 'auto',
+ contextThreshold: 1,
+ modelSupportsTools: false,
+ })
+
+ expect(result.processedAttachments[0].injectionMode).toBe('inline')
+ expect(result.hasEmbeddedDocuments).toBe(false)
+ })
+
it('skips already-processed documents', async () => {
const hub = createMockServiceHub()
const doc = docAttachment({
@@ -194,6 +232,27 @@ describe('processAttachmentsForSend', () => {
expect(result.processedAttachments[0].injectionMode).toBe('embeddings')
expect(result.processedAttachments[0].id).toBe('proj-doc-1')
})
+
+ it('inlines project documents for a model without tool support', async () => {
+ const hub = createMockServiceHub()
+ const doc = docAttachment({ parseMode: 'inline' })
+
+ const result = await processAttachmentsForSend({
+ attachments: [doc],
+ threadId,
+ projectId: 'proj-1',
+ // The mock implements only the slice of ServiceHub this path touches.
+ serviceHub: hub as unknown as ServiceHub,
+ parsePreference: 'auto',
+ modelSupportsTools: false,
+ })
+
+ expect(result.processedAttachments[0].injectionMode).toBe('inline')
+ expect(result.processedAttachments[0].inlineContent).toBe(
+ 'parsed document text'
+ )
+ expect(result.hasEmbeddedDocuments).toBe(false)
+ })
})
describe('callbacks', () => {
@@ -262,6 +321,22 @@ describe('processAttachmentsForSend', () => {
})
})
+ // #9363: a document is read back through the retrieval tool when it is
+ // embedded, so a model that cannot call tools gets it in the prompt instead.
+ describe('parseModeForModel', () => {
+ it('keeps the preference for a model that can call tools', () => {
+ for (const pref of ['auto', 'inline', 'embeddings', 'prompt'] as const) {
+ expect(parseModeForModel(pref, true)).toBe(pref)
+ }
+ })
+
+ it('puts the document in the prompt for a model that cannot, whatever the preference', () => {
+ for (const pref of ['auto', 'inline', 'embeddings', 'prompt'] as const) {
+ expect(parseModeForModel(pref, false)).toBe('inline')
+ }
+ })
+ })
+
describe('resolveAutoInlineBudget', () => {
beforeEach(() => {
getModelPropsMock.mockReset()
diff --git a/web-app/src/lib/attachmentProcessing.ts b/web-app/src/lib/attachmentProcessing.ts
index bb62ec58e..7b12f60aa 100644
--- a/web-app/src/lib/attachmentProcessing.ts
+++ b/web-app/src/lib/attachmentProcessing.ts
@@ -21,6 +21,11 @@ type AttachmentProcessingOptions = {
projectId?: string
serviceHub: ServiceHub
selectedProvider?: string
+ /**
+ * Whether the selected model can call tools. Project documents are embedded
+ * unless this is false, since only a tool-capable model can retrieve them.
+ */
+ modelSupportsTools?: boolean
/** Token budget under which an 'auto' document is inlined; see resolveAutoInlineBudget. */
contextThreshold?: number
parsePreference: 'auto' | 'inline' | 'embeddings' | 'prompt'
@@ -129,6 +134,17 @@ export const needsIngestionChoice = (
return preference === 'prompt' || (preference === 'auto' && !hasInlineBudget)
}
+/**
+ * How a new document is parsed for the selected model. An embedded document is
+ * read back through the retrieval tool, which a model without tool support can
+ * never call, so such a model gets the document in the prompt whatever the
+ * preference says (#9363).
+ */
+export const parseModeForModel = (
+ parsePreference: ParsePreference,
+ modelSupportsTools: boolean
+): ParsePreference => (modelSupportsTools ? parsePreference : 'inline')
+
export type IngestionChoice = 'inline' | 'embeddings'
/**
@@ -174,6 +190,10 @@ export const processAttachmentsForSend = async (
updateAttachmentProcessing,
onIngestProgress,
} = options
+ const inlineAllowed = !projectId || options.modelSupportsTools === false
+ // A model that cannot call the retrieval tool can only use a document that
+ // is in its prompt, whatever the preference or the document's size.
+ const needsInline = options.modelSupportsTools === false
const processedAttachments: Attachment[] = []
let hasEmbeddedDocuments = false
@@ -280,15 +300,19 @@ export const processAttachmentsForSend = async (
notifyUpdate(doc.name, 'processing')
const targetPreference = doc.parseMode ?? parsePreference
- // Project files always use embeddings, never inline. 'prompt' documents
+ // Project files use embeddings, never inline, unless the model cannot
+ // call the retrieval tool: an embedded document would then be
+ // unreachable, so it goes in the prompt (#9363). 'prompt' documents
// carry the user's pick in parseMode, so reaching here means no pick
// was recorded and the safe default applies.
const decideBySize =
- !projectId &&
+ inlineAllowed &&
+ !needsInline &&
targetPreference === 'auto' &&
effectiveContextThreshold !== undefined
const wantsInline =
- !projectId && (targetPreference === 'inline' || decideBySize)
+ inlineAllowed &&
+ (needsInline || targetPreference === 'inline' || decideBySize)
let targetMode: 'inline' | 'embeddings' = 'embeddings'
let parsedContent: string | undefined
@@ -302,6 +326,15 @@ export const processAttachmentsForSend = async (
}
}
+ // An embedded copy is unreachable for this model, so a document that
+ // could not be read as text must fail the send, not go through
+ // without its content.
+ if (needsInline && !parsedContent) {
+ throw new Error(
+ `Couldn't read ${doc.name} as text. This model can't search files, so the document can't be added.`
+ )
+ }
+
if (parsedContent) {
const tokens = estimateTokens(parsedContent)
targetMode =
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index cd8a264cd..c5bdc1624 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -1527,6 +1527,10 @@ function ThreadDetail() {
projectId,
serviceHub,
selectedProvider,
+ modelSupportsTools:
+ useModelProvider
+ .getState()
+ .selectedModel?.capabilities?.includes('tools') ?? false,
parsePreference,
contextThreshold,
})
@@ -1558,6 +1562,24 @@ function ThreadDetail() {
prev.filter((m) => m.id !== messageId)
)
}
+ // ChatInput cleared the input on submit and nothing was sent, so
+ // hand the draft and attachments back; the user fixes the cause and
+ // sends again. Attachments are keyed by thread and go back in front
+ // of anything added since. The prompt store is shared by every
+ // thread and Home, so the draft returns only while this thread is
+ // still the open one (the store clears it on leaving) and only if
+ // nothing has been typed there since.
+ setAttachmentsForThread(attachmentsKey, (prev) => [
+ ...allAttachments,
+ ...prev,
+ ])
+ const composer = usePrompt.getState()
+ if (
+ useThreads.getState().currentThreadId === threadId &&
+ !composer.prompt
+ ) {
+ composer.setPrompt(draft)
+ }
return
} finally {
useAppState.getState().setThreadEmbedding(threadId, false)
diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
index 5c2045282..da6f7b34c 100644
--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx
+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
@@ -699,6 +699,63 @@ describe('ThreadDetail route', () => {
h.attachmentsState.getAttachments = vi.fn(() => [])
})
+ describe('when processing a document fails', () => {
+ const sheet = { name: 'sheet.xlsx', type: 'document', path: '/sheet.xlsx' }
+ const later = { name: 'later.png', type: 'image', path: '/later.png' }
+
+ // `openThreadId` is the thread the store reports as open when the failure
+ // lands: its own, or null after the user went Home. The attachments are
+ // keyed by thread, so they go back to it either way.
+ const sendAndFail = async (openThreadId: string | null = 'thread-1') => {
+ h.threadsState.currentThreadId = openThreadId ?? undefined
+ h.attachmentsState.getAttachments = vi.fn(() => [sheet])
+ vi.mocked(processAttachmentsForSend).mockRejectedValueOnce(
+ new Error("Couldn't read sheet.xlsx as text.")
+ )
+ renderComponent()
+ await act(async () => {
+ screen.getByTestId('chat-send').click()
+ })
+ await waitFor(() => {
+ expect(h.attachmentsState.setAttachments).toHaveBeenCalledWith(
+ 'thread-1',
+ expect.any(Function)
+ )
+ })
+ }
+
+ afterEach(() => {
+ h.attachmentsState.getAttachments = vi.fn(() => [])
+ delete h.threadsState.currentThreadId
+ usePrompt.getState().resetPrompt()
+ })
+
+ it('gives back the draft and attachments, ahead of any added since', async () => {
+ await sendAndFail()
+
+ const updater = vi
+ .mocked(h.attachmentsState.setAttachments)
+ .mock.calls.map((c) => c[1])
+ .find((u) => typeof u === 'function')
+ expect(updater?.([later])).toEqual([sheet, later])
+ expect(usePrompt.getState().prompt).toBe('hello world')
+ expect(h.mockSendMessage).not.toHaveBeenCalled()
+ })
+
+ it('keeps what the user typed while the document was processing', async () => {
+ usePrompt.getState().setPrompt('typed meanwhile')
+ await sendAndFail()
+
+ expect(usePrompt.getState().prompt).toBe('typed meanwhile')
+ })
+
+ it('does not write the draft into another screen after the user left the thread', async () => {
+ await sendAndFail(null)
+
+ expect(usePrompt.getState().prompt).toBe('')
+ })
+ })
+
describe('when the auto-inline budget is gone at send time', () => {
const sheet = {
name: 'sheet.xlsx',