DeepInfra Provider 接入指南:基于 AI SDK 使用 Llama、FLUX 与多模态模型的完整方案
2026/9/11 22:07:38 网站建设 项目流程

DeepInfra Provider 接入指南:基于 AI SDK 使用 Llama、FLUX 与多模态模型的完整方案

【免费下载链接】aiThe AI Toolkit for TypeScript. From the creators of Next.js, the AI SDK is a free open-source library for building AI-powered applications and agents项目地址: https://gitcode.com/GitHub_Trending/ai/ai

导读

本文围绕 AI SDK 官方@ai-sdk/deepinfra提供器,系统讲解如何在 TypeScript 项目中通过 DeepInfra API 调用 Llama 3、Mixtral、DeepSeek、Qwen 等开源大语言模型,以及 FLUX 系列图像生成与编辑模型、bge/e5 等嵌入模型。读完本文,你将掌握提供器实例的配置方式、文本生成/流式输出/图像生成/嵌入的完整调用姿势,并理解底层 OpenAI 兼容协议封装、Token 用量修正等源码级实现细节,可直接复制代码投入实战。


一、认识 DeepInfra Provider

@ai-sdk/deepinfra是 AI SDK 生态中对接 DeepInfra API 的官方提供器模块。它依托 DeepInfra 的托管推理平台,让你以 OpenAI 兼容的接口风格访问一大批开源前沿模型,包括:

  • 语言模型:Llama 3/3.1/3.2/3.3/4、Mixtral、DeepSeek-V3、Qwen2/2.5、Gemma 2 等;
  • 图像模型:black-forest-labs/FLUX 系列、stabilityai/sd3.5、sdxl-turbo 等;
  • 嵌入模型:BAAI/bge 系列、intfloat/e5 系列、sentence-transformers 系列等。

从源码结构看,该提供器模块包含完整的四类模型实现与配套测试(packages/deepinfra/src 目录):

文件职责
deepinfra-provider.ts提供器工厂createDeepInfra与默认实例deepInfra
deepinfra-chat-language-model.ts聊天语言模型封装(含 Token 用量修正)
deepinfra-image-model.ts图像生成/编辑模型封装
deepinfra-chat-options.ts内置聊天模型 ID 类型清单
deepinfra-embedding-options.ts内置嵌入模型 ID 类型清单
deepinfra-image-settings.ts内置图像模型 ID 类型清单
deepinfra-image-model-options.ts图像模型专用参数 Schema(providerOptions)
deepinfra-provider.test.ts提供器实例化与配置的测试用例

模块版本、依赖与构建脚本见 packages/deepinfra/package.json,其运行时依赖为@ai-sdk/openai-compatible@ai-sdk/provider@ai-sdk/provider-utils,要求 Node.js >= 22。


二、安装与快速上手

1. 安装提供器

在任意 AI SDK 项目中安装:

npm i @ai-sdk/deepinfra

该模块与ai(核心包)配合使用,核心包提供了generateTextstreamTextgenerateImageembed等高层 API。

2. 引入默认实例

@ai-sdk/deepinfra可以直接导入默认提供器实例deepInfra(README 中写作deepinfra,源码 index.ts 同时导出了deepInfra与作为兼容别名的deepinfra):

import { deepInfra } from '@ai-sdk/deepinfra';

3. 首个文本生成示例

import { deepInfra } from '@ai-sdk/deepinfra'; import { generateText } from 'ai'; const { text } = await generateText({ model: deepInfra('meta-llama/Llama-3.3-70B-Instruct'), prompt: 'Write a vegetarian lasagna recipe for 4 people.', });

调用deepInfra(modelId)即返回一个聊天语言模型实例。API Key 默认从环境变量DEEPINFRA_API_KEY读取(见下文),并自动以Authorization: Bearer <key>头发送。

4. 为 Coding Agent 添加 AI SDK Skill

如果你使用 Claude Code、Cursor 等编码代理,官方推荐在仓库中安装 AI SDK Skill,让代理获得编写 AI 应用的最佳实践:

npx skills add vercel/ai

三、自定义提供器实例与配置项

1. 使用 createDeepInfra 定制实例

默认实例开箱即用;需要自定义配置时,使用createDeepInfra工厂函数:

import { createDeepInfra } from '@ai-sdk/deepinfra'; const deepInfra = createDeepInfra({ apiKey: process.env.DEEPINFRA_API_KEY ?? '', });

2. 完整配置项说明

DeepInfraProviderSettings支持四个可选字段,源码定义见 deepinfra-provider.ts:

配置项类型说明默认值
apiKeystringDeepInfra API Key,通过Authorization头发送环境变量DEEPINFRA_API_KEY
baseURLstringAPI 请求的基础 URL 前缀,可用于代理服务器https://api.deepinfra.com/v1
headersRecord<string, string>附加的自定义请求头
fetchFetchFunction自定义 fetch 实现,可拦截请求或用于测试全局fetch

几点源码级细节值得注意:

  • Key 加载逻辑createDeepInfra内部通过loadApiKey解析 Key,优先取options.apiKey,否则回退到DEEPINFRA_API_KEY环境变量;该行为在 deepinfra-provider.test.ts 中有明确的断言测试。
  • URL 归一化baseURL会经withoutTrailingSlash去掉末尾斜杠,避免拼接出双斜杠 URL。
  • User-Agent:请求头会自动追加ai-sdk/deepinfra/<version>后缀,便于服务端识别 SDK 版本。
  • 端点路由差异:语言模型与嵌入模型走 OpenAI 兼容端点{baseURL}/openai,而图像模型走{baseURL}/inference(见 deepinfra-provider.ts)。

例如,通过代理访问时可这样配置:

const deepInfra = createDeepInfra({ baseURL: 'https://my-proxy.example.com/v1', headers: { 'X-Custom-Header': 'value' }, });

四、语言模型:文本生成与流式输出

1. 支持的模型 ID

聊天模型 ID 类型定义在 deepinfra-chat-options.ts,包含从meta-llama/Llama-2-7b-chat-hfmeta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8deepseek-ai/DeepSeek-V3Qwen/Qwen2.5-72B-Instruct等数十个内置 ID。类型末尾带有(string & {})兜底,意味着任何 DeepInfra 平台可用的模型 ID 都可以直接以字符串传入,无需等待 SDK 更新。

2. 文本生成

import { deepInfra } from '@ai-sdk/deepinfra'; import { generateText } from 'ai'; const { text } = await generateText({ model: deepInfra('meta-llama/Meta-Llama-3.1-70B-Instruct'), prompt: 'Write a vegetarian lasagna recipe for 4 people.', });

3. 流式输出

DeepInfra 语言模型同样支持streamText,适用于打字机效果的聊天界面:

import { deepInfra } from '@ai-sdk/deepinfra'; import { streamText } from 'ai'; const result = streamText({ model: deepInfra('meta-llama/Llama-3.3-70B-Instruct'), prompt: 'Explain quantum computing in simple terms.', }); for await (const textPart of result.textStream) { process.stdout.write(textPart); }

4. 模型能力速查

完整文档(content/providers/01-ai-sdk-providers/11-deepinfra.mdx)给出了热门模型的四维能力对照:Image Input(图像输入)、Object Generation(结构化对象生成)、Tool Usage(工具调用)、Tool Streaming(工具流式输出)。

模型图像输入对象生成工具调用工具流式
meta-llama/Llama-3.3-70B-Instruct
meta-llama/Meta-Llama-3.1-405B-Instruct
meta-llama/Meta-Llama-3.1-70B-Instruct
meta-llama/Llama-3.2-11B-Vision-Instruct
meta-llama/Llama-3.2-90B-Vision-Instruct
deepseek-ai/DeepSeek-V3
Qwen/Qwen2.5-72B-Instruct
mistralai/Mixtral-8x7B-Instruct-v0.1

上表仅列出热门模型;完整模型列表请查阅 DeepInfra 官方模型页。任何可用模型 ID 都可以直接以字符串传入。

5. 源码内幕:Gemini/Gemma 模型的 Token 用量修正

DeepInfraChatLanguageModel继承自OpenAICompatibleChatLanguageModel,并重写了doGeneratedoStream,核心目的是修正 DeepInfra 返回给 Gemini/Gemma 系列模型的错误 Token 统计(见 deepinfra-chat-language-model.ts)。

问题场景:DeepInfra 对 Gemini/Gemma 模型返回的completion_tokens不含推理 Token(reasoning_tokens),这违反了 OpenAI 兼容规范(规范要求completion_tokens应包含 reasoning_tokens)。例如:

{ "completion_tokens": 84, "completion_tokens_details": { "reasoning_tokens": 1081 } }

若直接使用会得到负数文本 Token(84 - 1081 = -997)。

修正逻辑:当reasoning_tokens > completion_tokens时,将两者相加得到正确的完成 Token 数(84 + 1081 = 1165),并同步更新total_tokens;随后重新计算inputTokens(含noCachecacheRead拆分)与outputTokenstextreasoning拆分)。该修正同时作用于一次性生成(doGenerate)和流式响应(doStream会包装流,在finish块中修正 usage)。


五、图像生成与编辑

1. 基础图像生成

通过.image()工厂方法创建图像模型,配合核心包generateImage使用:

import { deepInfra, type DeepInfraImageModelOptions } from '@ai-sdk/deepinfra'; import { generateImage } from 'ai'; const { image } = await generateImage({ model: deepInfra.image('stabilityai/sd3.5'), prompt: 'A futuristic cityscape at sunset', aspectRatio: '16:9', });

2. 模型专用参数(providerOptions.deepinfra)

不同图像模型支持不同的专有参数,通过providerOptions.deepinfra字段透传,并用DeepInfraImageModelOptions类型约束:

const { image } = await generateImage({ model: deepInfra.image('stabilityai/sd3.5'), prompt: 'A futuristic cityscape at sunset', aspectRatio: '16:9', providerOptions: { deepinfra: { num_inference_steps: 30, } satisfies DeepInfraImageModelOptions, }, });

Schema 定义在 deepinfra-image-model-options.ts,可用参数如下:

参数类型说明
negative_promptstring生成图像中要避免内容的文本描述
num_inference_stepsnumber支持该选项的模型的去噪步数
guidance_scalenumber支持该选项的模型的引导系数
guidancenumber图像编辑模型暴露的引导值
response_format'b64_json'OpenAI 兼容图像响应格式,DeepInfra 目前支持b64_json
qualitystringOpenAI 兼容的图像质量选项
stylestringOpenAI 兼容的图像风格选项
userstring终端用户的唯一标识

其他未内置的模型专属字段同样可以放进providerOptions.deepinfra,由 DeepInfra 服务端校验。

3. 图像编辑:三种实战姿势

DeepInfra 通过Qwen/Qwen-Image-Edit等模型支持图像编辑。输入图片可来自BufferArrayBufferUint8Array或 base64 字符串。

基础编辑——用文本指令改造现有图片:

const imageBuffer = readFileSync('./input-image.png'); const { images } = await generateImage({ model: deepInfra.image('Qwen/Qwen-Image-Edit'), prompt: { text: 'Turn the cat into a golden retriever dog', images: [imageBuffer], }, size: '1024x1024', });

Mask 局部重绘(Inpainting)——mask 中的透明区域表示需要编辑的部位:

const image = readFileSync('./input-image.png'); const mask = readFileSync('./mask.png'); const { images } = await generateImage({ model: deepInfra.image('Qwen/Qwen-Image-Edit'), prompt: { text: 'A sunlit indoor lounge area with a pool containing a flamingo', images: [image], mask: mask, }, });

多图融合——将多张参考图合成为一张输出:

const cat = readFileSync('./cat.png'); const dog = readFileSync('./dog.png'); const { images } = await generateImage({ model: deepInfra.image('Qwen/Qwen-Image-Edit'), prompt: { text: 'Create a scene with both animals together, playing as friends', images: [cat, dog], }, });

从实现看(deepinfra-image-model.ts),当传入files(即 prompt.images)时,请求走 OpenAI 兼容的/images/edits端点(https://api.deepinfra.com/v1/openai/images/edits),以 multipart/form-data 上传modelpromptimage、可选masknsize等字段;而标准文生图走{baseURL}/inference/{modelId}的 JSON 端点,body 中包含num_imagesaspect_ratiowidth/heightseed等字段(见 deepinfra-image-model.ts)。

4. 图像模型能力速查

尺寸约束要点:

  • 支持 aspectRatio 的模型常用比例:1:1(默认)、16:9、1:9、3:2、2:3、4:5、5:4、9:16、9:21
  • 支持 size 的模型要求:宽高为 32 的倍数、介于 256~1440 像素之间,默认1024x1024
模型尺寸规范说明
stabilityai/sd3.5Aspect Ratio8B 参数的旗舰基础模型
black-forest-labs/FLUX-1.1-proSize最新 SOTA 模型,提示词跟随能力强
black-forest-labs/FLUX-1-schnellSize1-4 步快速生成
black-forest-labs/FLUX-1-devSize针对解剖学准确度优化
black-forest-labs/FLUX-proSize旗舰版 FLUX 模型
black-forest-labs/FLUX.1-Kontext-devSize图像编辑与变换模型
black-forest-labs/FLUX.1-Kontext-proSize专业级图像编辑与变换
stabilityai/sd3.5-mediumAspect Ratio2.5B 参数的均衡模型
stabilityai/sdxl-turboAspect Ratio面向快速生成优化

六、嵌入模型

1. 生成文本嵌入

通过.embeddingModel()工厂方法创建嵌入模型,配合embed使用:

import { deepInfra } from '@ai-sdk/deepinfra'; import { embed } from 'ai'; const { embedding } = await embed({ model: deepInfra.embeddingModel('BAAI/bge-large-en-v1.5'), value: 'sunny day at the beach', });

DeepInfraEmbeddingModel底层复用了@ai-sdk/openai-compatibleOpenAICompatibleEmbeddingModel(见 deepinfra-provider.ts),因此其请求/响应协议与 OpenAI 嵌入接口一致。

2. 内置嵌入模型与能力对照

模型 ID 类型见 deepinfra-embedding-options.ts,完整文档给出的能力对照如下:

模型维度最大 Token
BAAI/bge-base-en-v1.5768512
BAAI/bge-large-en-v1.51024512
BAAI/bge-m310248192
intfloat/e5-base-v2768512
intfloat/e5-large-v21024512
intfloat/multilingual-e5-large1024512
sentence-transformers/all-MiniLM-L12-v2384256
sentence-transformers/all-MiniLM-L6-v2384256
sentence-transformers/all-mpnet-base-v2768384
sentence-transformers/clip-ViT-B-3251277
sentence-transformers/clip-ViT-B-32-multilingual-v151277
sentence-transformers/multi-qa-mpnet-base-dot-v1768512
sentence-transformers/paraphrase-MiniLM-L6-v2384128
shibing624/text2vec-base-chinese768512
thenlper/gte-base768512
thenlper/gte-large1024512

其中shibing624/text2vec-base-chinese为中文场景专用模型,适合中文语义检索任务。选择嵌入模型时,请结合维度(影响向量存储大小)与最大 Token(影响可编码文本长度)综合权衡。


七、提供器方法总览

DeepInfraProvider接口(deepinfra-provider.ts)暴露了完整的方法面,覆盖文本、补全、图像、嵌入四类能力:

方法返回模型说明
deepInfra(modelId)聊天语言模型提供器本身可调用,等价于chatModel
chatModel(modelId)聊天语言模型显式创建聊天模型
languageModel(modelId)聊天语言模型同上,语义化别名
completionModel(modelId)语言模型创建补全(completion)模型
image(modelId)/imageModel(modelId)图像模型创建图像生成/编辑模型
embeddingModel(modelId)嵌入模型创建嵌入模型
textEmbeddingModel(modelId)嵌入模型已废弃,请改用embeddingModel

所有模型的创建都经由getCommonModelConfig统一注入provider: deepinfra.<type>标识、URL 拼接逻辑与鉴权头,确保各类型请求的行为一致。补全模型 ID 与聊天模型 ID 共用同一集合(见 deepinfra-completion-options.ts)。


八、环境变量与运行前提

  • API Key:设置环境变量DEEPINFRA_API_KEY(在 DeepInfra 控制台 申请),或在createDeepInfra({ apiKey })中显式传入;
  • Node 版本:包声明engines.node >= 22
  • TypeScript:完整类型由@ai-sdk/deepinfra自动携带,模型 ID 均有字符串字面量类型提示,同时支持任意字符串兜底;
  • Vercel 部署提示:使用 Vercel AI Gateway 时,无需额外安装本包、配置 API Key 或支付额外费用,即可通过网关访问 DeepInfra 及数百个其他提供商的模型。

相关完整文档位于仓库 content/providers/01-ai-sdk-providers/11-deepinfra.mdx,源码实现与测试可在 packages/deepinfra/src 目录下继续深入研读。

【免费下载链接】aiThe AI Toolkit for TypeScript. From the creators of Next.js, the AI SDK is a free open-source library for building AI-powered applications and agents项目地址: https://gitcode.com/GitHub_Trending/ai/ai

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询