Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/ollama-prestream-run-error.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/ai-ollama': patch
---

Emit a `RUN_ERROR` event instead of throwing when the Ollama text adapter's `chatStream` fails before streaming begins (e.g. the initial `client.chat` call is rejected because the host is unreachable). The error is now surfaced as a structured chunk — with `message`, `code`, and any available `rawEvent` — so failures flow through the stream consistently with other adapters rather than escaping as an unhandled exception.
22 changes: 21 additions & 1 deletion packages/ai-ollama/src/adapters/text.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { EventType, normalizeSystemPrompts } from '@tanstack/ai'
import {
toRunErrorPayload,
toRunErrorRawEvent,
} from '@tanstack/ai/adapter-internals'
import { BaseTextAdapter } from '@tanstack/ai/adapters'
import { buildOllamaUsage } from '../usage'
import { createOllamaClient, generateId, getOllamaHostFromEnv } from '../utils'
Expand Down Expand Up @@ -112,11 +116,27 @@ export class OllamaTextAdapter<TModel extends string> extends BaseTextAdapter<
})
yield* this.processOllamaStreamChunks(response, options, logger)
} catch (error: unknown) {
const errorPayload = toRunErrorPayload(
error,
'An unknown error occurred during the chat stream.',
)
const rawEvent = toRunErrorRawEvent(error)
logger.errors('ollama.chatStream fatal', {
error,
source: 'ollama.chatStream',
})
throw error
yield {
type: EventType.RUN_ERROR,
model: options.model,
timestamp: Date.now(),
message: errorPayload.message,
code: errorPayload.code,
...(rawEvent !== undefined && { rawEvent }),
error: {
message: errorPayload.message,
code: errorPayload.code,
},
}
}
}

Expand Down
21 changes: 21 additions & 0 deletions packages/ai-ollama/tests/text-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -590,3 +590,24 @@ describe('OllamaTextAdapter system prompts', () => {
expect(roles).not.toContain('system')
})
})

describe('Ollama adapter error handling', () => {
it('emits RUN_ERROR on pre-stream client.chat rejection without throwing', async () => {
chatMock.mockRejectedValueOnce(new Error('connection refused'))
const adapter = createOllamaChat('llama3.2')
const chunks = await collectStream(
adapter.chatStream({
logger: testLogger,
model: 'llama3.2',
messages: [{ role: 'user', content: 'hi' }],
}),
)

expect(chunks).toHaveLength(1)
expect(chunks[0]?.type).toBe('RUN_ERROR')
if (chunks[0]?.type === 'RUN_ERROR') {
expect(chunks[0].message).toBe('connection refused')
expect(chunks[0].error?.message).toBe('connection refused')
}
})
})
Loading