DeepInfra Provider 接入指南:基于 AI SDK 使用 Llama、FLUX 与多模态模型的完整方案
发布时间:2026/9/11 22:07:52
分类:文化教育
浏览:1234

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 Providerai-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与默认实例deepInfradeepinfra-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图像模型专用参数 SchemaproviderOptionsdeepinfra-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核心包配合使用核心包提供了generateText、streamText、generateImage、embed等高层 API。2. 引入默认实例从ai-sdk/deepinfra可以直接导入默认提供器实例deepInfraREADME 中写作deepinfra源码 index.ts 同时导出了deepInfra与作为兼容别名的deepinfraimport { 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_KEYbaseURLstringAPI 请求的基础 URL 前缀可用于代理服务器https://api.deepinfra.com/v1headersRecordstring, 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-hf到meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8、deepseek-ai/DeepSeek-V3、Qwen/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并重写了doGenerate与doStream核心目的是修正 DeepInfra 返回给 Gemini/Gemma 系列模型的错误 Token 统计见 deepinfra-chat-language-model.ts。问题场景DeepInfra 对 Gemini/Gemma 模型返回的completion_tokens不含推理 Tokenreasoning_tokens这违反了 OpenAI 兼容规范规范要求completion_tokens应包含 reasoning_tokens。例如{ completion_tokens: 84, completion_tokens_details: { reasoning_tokens: 1081 } }若直接使用会得到负数文本 Token84 - 1081 -997。修正逻辑当reasoning_tokens completion_tokens时将两者相加得到正确的完成 Token 数84 1081 1165并同步更新total_tokens随后重新计算inputTokens含noCache与cacheRead拆分与outputTokenstext与reasoning拆分。该修正同时作用于一次性生成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_formatb64_jsonOpenAI 兼容图像响应格式DeepInfra 目前支持b64_jsonqualitystringOpenAI 兼容的图像质量选项stylestringOpenAI 兼容的图像风格选项userstring终端用户的唯一标识其他未内置的模型专属字段同样可以放进providerOptions.deepinfra由 DeepInfra 服务端校验。3. 图像编辑三种实战姿势DeepInfra 通过Qwen/Qwen-Image-Edit等模型支持图像编辑。输入图片可来自Buffer、ArrayBuffer、Uint8Array或 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 上传model、prompt、image、可选mask、n、size等字段而标准文生图走{baseURL}/inference/{modelId}的 JSON 端点body 中包含num_images、aspect_ratio或width/height、seed等字段见 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-compatible的OpenAICompatibleEmbeddingModel见 deepinfra-provider.ts因此其请求/响应协议与 OpenAI 嵌入接口一致。2. 内置嵌入模型与能力对照模型 ID 类型见 deepinfra-embedding-options.ts完整文档给出的能力对照如下模型维度最大 TokenBAAI/bge-base-en-v1.5768512BAAI/bge-large-en-v1.51024512BAAI/bge-m310248192intfloat/e5-base-v2768512intfloat/e5-large-v21024512intfloat/multilingual-e5-large1024512sentence-transformers/all-MiniLM-L12-v2384256sentence-transformers/all-MiniLM-L6-v2384256sentence-transformers/all-mpnet-base-v2768384sentence-transformers/clip-ViT-B-3251277sentence-transformers/clip-ViT-B-32-multilingual-v151277sentence-transformers/multi-qa-mpnet-base-dot-v1768512sentence-transformers/paraphrase-MiniLM-L6-v2384128shibing624/text2vec-base-chinese768512thenlper/gte-base768512thenlper/gte-large1024512其中shibing624/text2vec-base-chinese为中文场景专用模型适合中文语义检索任务。选择嵌入模型时请结合维度影响向量存储大小与最大 Token影响可编码文本长度综合权衡。七、提供器方法总览DeepInfraProvider接口deepinfra-provider.ts暴露了完整的方法面覆盖文本、补全、图像、嵌入四类能力方法返回模型说明deepInfra(modelId)聊天语言模型提供器本身可调用等价于chatModelchatModel(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 22TypeScript完整类型由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),仅供参考