-
Notifications
You must be signed in to change notification settings - Fork 65
feat: multi-provider cover letters via the AI SDK, with AI Gateway model discovery #44
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dorddis
wants to merge
6
commits into
neeilya:master
Choose a base branch
from
dorddis:feat/ai-sdk-gateway
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
be5e263
feat(ai): add the AI SDK and a provider catalog
dorddis 15f72a9
feat(ai): store the AI connection as one record and migrate the legac…
dorddis ef3b9f0
feat(ai): stream cover letters through the AI SDK with typed failures
dorddis b1fce78
feat(ai): declare provider origins as optional host permissions
dorddis 53df583
feat(ai): let users pick a provider, key and model in settings
dorddis c234c9e
docs: describe the multi-provider cover letter path
dorddis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| import { AiSettings } from '@/utils/aiSettings' | ||
| import { findProvider, ModelPreset } from '@/utils/aiCatalog' | ||
| import { AiErrorCode } from '@/utils/runtime' | ||
| import { createAnthropic } from '@ai-sdk/anthropic' | ||
| import { createGoogle } from '@ai-sdk/google' | ||
| import { createOpenAI } from '@ai-sdk/openai' | ||
| import { createOpenAICompatible } from '@ai-sdk/openai-compatible' | ||
| import { APICallError, createGateway, LanguageModel, streamText } from 'ai' | ||
|
|
||
| const DIAGNOSTIC_BODY_LIMIT = 500 | ||
|
|
||
| export type AiFailure = { | ||
| code: AiErrorCode | ||
| /** False for failures the user can fix themselves; those are not bugs. */ | ||
| reportable: boolean | ||
| diagnostics: { url?: string; status?: number; body?: string } | ||
| } | ||
|
|
||
| const createModel = (settings: AiSettings): LanguageModel => { | ||
| if (settings.mode === 'gateway') { | ||
| return createGateway({ apiKey: settings.gatewayApiKey })( | ||
| settings.gatewayModel | ||
| ) | ||
| } | ||
|
|
||
| const provider = findProvider(settings.provider) | ||
|
|
||
| if (!provider) { | ||
| throw new Error(`Unknown AI provider: ${settings.provider}`) | ||
| } | ||
|
|
||
| const apiKey = settings.apiKey | ||
|
|
||
| switch (provider.kind) { | ||
| case 'openai': | ||
| return createOpenAI({ apiKey })(settings.model) | ||
| case 'google': | ||
| return createGoogle({ apiKey })(settings.model) | ||
| case 'anthropic': | ||
| // The Claude API rejects browser-originated requests unless they opt in. | ||
| return createAnthropic({ | ||
| apiKey, | ||
| headers: { 'anthropic-dangerous-direct-browser-access': 'true' }, | ||
| })(settings.model) | ||
| case 'openai-compatible': | ||
| return createOpenAICompatible({ | ||
| apiKey, | ||
| name: provider.id, | ||
| baseURL: provider.baseUrl, | ||
| })(settings.model) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Streams a cover letter from the configured provider, delivering each token | ||
| * through `onChunk` as it arrives. | ||
| */ | ||
| const generateCoverLetter = async (props: { | ||
| settings: AiSettings | ||
| prompt: string | ||
| signal?: AbortSignal | ||
| onChunk: (chunk: string) => void | ||
| }): Promise<void> => { | ||
| const result = streamText({ | ||
| model: createModel(props.settings), | ||
| prompt: props.prompt, | ||
| abortSignal: props.signal, | ||
| }) | ||
|
|
||
| let received = false | ||
|
|
||
| for await (const part of result.fullStream) { | ||
| if (part.type === 'text-delta') { | ||
| received = true | ||
| props.onChunk(part.text) | ||
| continue | ||
| } | ||
|
|
||
| // `streamText` reports a failure as an in-band part and then closes the | ||
| // stream normally, so consuming `textStream` instead would report success | ||
| // with an empty result. | ||
| if (part.type === 'error') { | ||
| throw part.error | ||
| } | ||
| } | ||
|
|
||
| if (!received) { | ||
| throw new Error('The provider returned an empty cover letter') | ||
| } | ||
| } | ||
|
|
||
| const fetchGatewayModels = async (apiKey: string): Promise<ModelPreset[]> => { | ||
| const { models } = await createGateway({ apiKey }).getAvailableModels() | ||
|
|
||
| return models | ||
| .filter( | ||
| (model) => model.modelType == null || model.modelType === 'language' | ||
| ) | ||
| .map((model) => ({ id: model.id, label: model.name || model.id })) | ||
| .sort((a, b) => a.label.localeCompare(b.label)) | ||
| } | ||
|
|
||
| /** Provider error bodies quote the rejected credential back at you. */ | ||
| const redactSecrets = (body: string) => | ||
| body.replace(/[A-Za-z0-9_-]{24,}/g, '[redacted]') | ||
|
|
||
| const matchesQuota = (body: string) => | ||
| /insufficient_quota|insufficient credit|exceeded your current quota|billing|payment required/i.test( | ||
| body | ||
| ) | ||
|
|
||
| const matchesUnknownModel = (body: string) => | ||
| /model.{0,30}(not found|does not exist|is not available|invalid)/i.test(body) | ||
|
|
||
| const classifyError = (error: unknown): AiFailure => { | ||
| if (!APICallError.isInstance(error)) { | ||
| return { code: 'GENERATION_FAILED', reportable: true, diagnostics: {} } | ||
| } | ||
|
|
||
| const body = (error.responseBody ?? '').slice(0, DIAGNOSTIC_BODY_LIMIT) | ||
| const diagnostics = { | ||
| url: error.url, | ||
| status: error.statusCode, | ||
| body: redactSecrets(body), | ||
| } | ||
|
|
||
| const userFixable = (code: AiErrorCode): AiFailure => ({ | ||
| code, | ||
| reportable: false, | ||
| diagnostics, | ||
| }) | ||
|
|
||
| switch (error.statusCode) { | ||
| case 401: | ||
| case 403: | ||
| return userFixable('INVALID_API_KEY') | ||
| case 402: | ||
| return userFixable('INSUFFICIENT_QUOTA') | ||
| case 404: | ||
| return userFixable('MODEL_UNAVAILABLE') | ||
| case 429: | ||
| // OpenAI never returns 402; it signals an exhausted balance with a 429 | ||
| // whose body carries `insufficient_quota`. | ||
| return userFixable( | ||
| matchesQuota(body) ? 'INSUFFICIENT_QUOTA' : 'RATE_LIMITED' | ||
| ) | ||
| case 400: | ||
| if (matchesUnknownModel(body)) return userFixable('MODEL_UNAVAILABLE') | ||
| break | ||
| } | ||
|
|
||
| return { code: 'GENERATION_FAILED', reportable: true, diagnostics } | ||
| } | ||
|
|
||
| export default { generateCoverLetter, fetchGatewayModels, classifyError } |
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Guard the permission check so a rejection still answers the port.
browser.permissions.contains()runs outside a try/catch inside an async listener. If it rejects, the handler throws, no message is posted, and the port stays connected. The content dialog then keeps showing the streaming state until the user cancels.🛡️ Proposed fix
📝 Committable suggestion
🤖 Prompt for AI Agents