-
Notifications
You must be signed in to change notification settings - Fork 4.2k
feat: integrate ai-sdk provider #10467
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
Merged
+408
−18
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
bf1772a
convert assistant tool call messages to ai sdk format
uinstinct 783fd2a
add ai sdk implementing basellmapi
uinstinct 73ee3e0
remove usage of aisdkprovider id
uinstinct 73b5db9
pass in the format of "provider/model"
uinstinct e5e62aa
revert unnecessary changes
uinstinct 1689ac2
remove from config yaml
uinstinct 2642558
make schema openai compatible
uinstinct da52388
use openai compatible over anthropic adapter
uinstinct ec8263d
add support for openrouter
uinstinct 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,303 @@ | ||
| import { createOpenAI } from "@ai-sdk/openai"; | ||
| import { | ||
| ChatCompletion, | ||
| ChatCompletionChunk, | ||
| ChatCompletionCreateParamsNonStreaming, | ||
| ChatCompletionCreateParamsStreaming, | ||
| Completion, | ||
| CompletionCreateParamsNonStreaming, | ||
| CompletionCreateParamsStreaming, | ||
| CreateEmbeddingResponse, | ||
| EmbeddingCreateParams, | ||
| Model, | ||
| } from "openai/resources/index"; | ||
| import { AiSdkConfig } from "../types.js"; | ||
| import { customFetch, embedding } from "../util.js"; | ||
| import { | ||
| BaseLlmApi, | ||
| CreateRerankResponse, | ||
| FimCreateParamsStreaming, | ||
| RerankCreateParams, | ||
| } from "./base.js"; | ||
|
|
||
| type AiSdkProviderCreator = (options: { | ||
| apiKey?: string; | ||
| baseURL?: string; | ||
| fetch?: typeof fetch; | ||
| }) => (modelId: string) => any; | ||
|
|
||
| const PROVIDER_MAP: Record<string, AiSdkProviderCreator> = { | ||
| openai: createOpenAI, | ||
| anthropic: (options) => | ||
| createOpenAI({ | ||
| ...options, | ||
| baseURL: options.baseURL ?? "https://api.anthropic.com/v1/", | ||
| }), | ||
| openrouter: (options) => | ||
| createOpenAI({ | ||
| ...options, | ||
| baseURL: options.baseURL ?? "https://openrouter.ai/api/v1/", | ||
| }), | ||
| }; | ||
|
|
||
| export class AiSdkApi implements BaseLlmApi { | ||
| private provider?: (modelId: string) => any; | ||
| private config: AiSdkConfig; | ||
| private providerId: string; | ||
| private modelId: string; | ||
|
|
||
| constructor(config: AiSdkConfig) { | ||
| this.config = config; | ||
| if (!config.model) { | ||
| throw new Error( | ||
| "AI SDK provider requires a model in the format '<provider>/<model>' (e.g., 'openai/gpt-4o')", | ||
| ); | ||
| } | ||
| const [providerId, ...modelParts] = config.model.split("/"); | ||
| this.providerId = providerId; | ||
| this.modelId = modelParts.join("/"); | ||
| } | ||
|
|
||
| private initializeProvider() { | ||
| if (this.provider) { | ||
| return; | ||
| } | ||
|
|
||
| const createFn = PROVIDER_MAP[this.providerId]; | ||
| if (!createFn) { | ||
| const supportedProviders = Object.keys(PROVIDER_MAP).join(", "); | ||
| throw new Error( | ||
| `Unknown AI SDK provider: "${this.providerId}". ` + | ||
| `Supported providers: ${supportedProviders}. ` + | ||
| `To use a different provider, install the @ai-sdk/* package and add it to the provider map.`, | ||
| ); | ||
| } | ||
|
|
||
| const hasRequestOptions = | ||
| this.config.requestOptions && | ||
| (this.config.requestOptions.headers || | ||
| this.config.requestOptions.proxy || | ||
| this.config.requestOptions.caBundlePath || | ||
| this.config.requestOptions.clientCertificate || | ||
| this.config.requestOptions.extraBodyProperties); | ||
|
|
||
| this.provider = createFn({ | ||
| apiKey: this.config.apiKey ?? "", | ||
| baseURL: this.config.apiBase, | ||
| fetch: hasRequestOptions | ||
| ? customFetch(this.config.requestOptions) | ||
| : undefined, | ||
| }); | ||
| } | ||
|
|
||
| async chatCompletionNonStream( | ||
| body: ChatCompletionCreateParamsNonStreaming, | ||
| signal: AbortSignal, | ||
| ): Promise<ChatCompletion> { | ||
| this.initializeProvider(); | ||
|
|
||
| const { generateText } = await import("ai"); | ||
| const { convertOpenAIMessagesToVercel } = await import( | ||
| "../openaiToVercelMessages.js" | ||
| ); | ||
| const { convertToolsToVercelFormat } = await import( | ||
| "../convertToolsToVercel.js" | ||
| ); | ||
| const { convertToolChoiceToVercel } = await import( | ||
| "../convertToolChoiceToVercel.js" | ||
| ); | ||
|
|
||
| const vercelMessages = convertOpenAIMessagesToVercel(body.messages); | ||
| const systemMsg = vercelMessages.find((msg) => msg.role === "system"); | ||
| const systemText = | ||
| systemMsg && typeof systemMsg.content === "string" | ||
| ? systemMsg.content | ||
| : undefined; | ||
| const nonSystemMessages = vercelMessages.filter( | ||
| (msg) => msg.role !== "system", | ||
| ); | ||
|
|
||
| const modelId = this.modelId ?? body.model; | ||
| const model = this.provider!(modelId); | ||
| const vercelTools = await convertToolsToVercelFormat(body.tools); | ||
|
|
||
| const result = await generateText({ | ||
| model, | ||
| system: systemText, | ||
| messages: nonSystemMessages as any, | ||
| temperature: body.temperature ?? undefined, | ||
| maxTokens: body.max_tokens ?? undefined, | ||
| topP: body.top_p ?? undefined, | ||
| stopSequences: body.stop | ||
| ? Array.isArray(body.stop) | ||
| ? body.stop | ||
| : [body.stop] | ||
| : undefined, | ||
| tools: vercelTools, | ||
| toolChoice: convertToolChoiceToVercel(body.tool_choice), | ||
| abortSignal: signal, | ||
| }); | ||
|
|
||
| const toolCalls = result.toolCalls?.map((tc) => ({ | ||
| id: tc.toolCallId, | ||
| type: "function" as const, | ||
| function: { | ||
| name: tc.toolName, | ||
| arguments: JSON.stringify(tc.args), | ||
| }, | ||
| })); | ||
|
|
||
| return { | ||
| id: result.response?.id ?? "", | ||
| object: "chat.completion", | ||
| created: Math.floor(Date.now() / 1000), | ||
| model: modelId, | ||
| choices: [ | ||
| { | ||
| index: 0, | ||
| message: { | ||
| role: "assistant", | ||
| content: result.text, | ||
| tool_calls: toolCalls, | ||
| refusal: null, | ||
| }, | ||
| finish_reason: | ||
| result.finishReason === "tool-calls" ? "tool_calls" : "stop", | ||
| logprobs: null, | ||
| }, | ||
| ], | ||
| usage: { | ||
| prompt_tokens: result.usage.promptTokens, | ||
| completion_tokens: result.usage.completionTokens, | ||
| total_tokens: result.usage.totalTokens, | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| async *chatCompletionStream( | ||
| body: ChatCompletionCreateParamsStreaming, | ||
| signal: AbortSignal, | ||
| ): AsyncGenerator<ChatCompletionChunk> { | ||
| this.initializeProvider(); | ||
|
|
||
| const { streamText } = await import("ai"); | ||
| const { convertOpenAIMessagesToVercel } = await import( | ||
| "../openaiToVercelMessages.js" | ||
| ); | ||
| const { convertToolsToVercelFormat } = await import( | ||
| "../convertToolsToVercel.js" | ||
| ); | ||
| const { convertVercelStream } = await import("../vercelStreamConverter.js"); | ||
| const { convertToolChoiceToVercel } = await import( | ||
| "../convertToolChoiceToVercel.js" | ||
| ); | ||
|
|
||
| const vercelMessages = convertOpenAIMessagesToVercel(body.messages); | ||
| const systemMsg = vercelMessages.find((msg) => msg.role === "system"); | ||
| const systemText = | ||
| systemMsg && typeof systemMsg.content === "string" | ||
| ? systemMsg.content | ||
| : undefined; | ||
| const nonSystemMessages = vercelMessages.filter( | ||
| (msg) => msg.role !== "system", | ||
| ); | ||
|
|
||
| const modelId = this.modelId ?? body.model; | ||
| const model = this.provider!(modelId); | ||
| const vercelTools = await convertToolsToVercelFormat(body.tools); | ||
|
|
||
| const result = streamText({ | ||
| model, | ||
| system: systemText, | ||
| messages: nonSystemMessages as any, | ||
| temperature: body.temperature ?? undefined, | ||
| maxTokens: body.max_tokens ?? undefined, | ||
| topP: body.top_p ?? undefined, | ||
| stopSequences: body.stop | ||
| ? Array.isArray(body.stop) | ||
| ? body.stop | ||
| : [body.stop] | ||
| : undefined, | ||
| tools: vercelTools, | ||
| toolChoice: convertToolChoiceToVercel(body.tool_choice), | ||
| abortSignal: signal, | ||
| }); | ||
|
|
||
| yield* convertVercelStream(result.fullStream as any, { model: modelId }); | ||
| } | ||
|
|
||
| async completionNonStream( | ||
| _body: CompletionCreateParamsNonStreaming, | ||
| _signal: AbortSignal, | ||
| ): Promise<Completion> { | ||
| throw new Error( | ||
| "AI SDK provider does not support legacy completions API. Use chat completions instead.", | ||
| ); | ||
| } | ||
|
|
||
| async *completionStream( | ||
| _body: CompletionCreateParamsStreaming, | ||
| _signal: AbortSignal, | ||
| ): AsyncGenerator<Completion> { | ||
| throw new Error( | ||
| "AI SDK provider does not support legacy completions API. Use chat completions instead.", | ||
| ); | ||
| } | ||
|
|
||
| async *fimStream( | ||
| _body: FimCreateParamsStreaming, | ||
| _signal: AbortSignal, | ||
| ): AsyncGenerator<ChatCompletionChunk> { | ||
| throw new Error( | ||
| "AI SDK provider does not support fill-in-the-middle (FIM) completions.", | ||
| ); | ||
| } | ||
|
|
||
| async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> { | ||
| this.initializeProvider(); | ||
|
|
||
| const { embed: aiEmbed, embedMany } = await import("ai"); | ||
|
|
||
| const modelId = typeof body.model === "string" ? body.model : body.model; | ||
| const model = this.provider!(modelId); | ||
|
|
||
| const inputs = Array.isArray(body.input) ? body.input : [body.input]; | ||
|
|
||
| if (inputs.length === 1) { | ||
| const result = await aiEmbed({ | ||
| model, | ||
| value: inputs[0], | ||
| }); | ||
| return embedding({ | ||
| data: [result.embedding], | ||
| model: modelId, | ||
| usage: { | ||
| prompt_tokens: result.usage?.tokens ?? 0, | ||
| total_tokens: result.usage?.tokens ?? 0, | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| const result = await embedMany({ | ||
| model, | ||
| values: inputs as string[], | ||
| }); | ||
|
|
||
| return embedding({ | ||
| data: result.embeddings, | ||
| model: modelId, | ||
| usage: { | ||
| prompt_tokens: result.usage?.tokens ?? 0, | ||
| total_tokens: result.usage?.tokens ?? 0, | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| async rerank(_body: RerankCreateParams): Promise<CreateRerankResponse> { | ||
| throw new Error("AI SDK provider does not support reranking."); | ||
| } | ||
|
|
||
| async list(): Promise<Model[]> { | ||
| return []; | ||
| } | ||
| } | ||
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.
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
P2: finish_reason mapping collapses "length" and "content-filter" into "stop", hiding truncation or content-filter events from OpenAI-style clients.
Prompt for AI agents