页面简介
Learn how to use Alibaba with AI Gateway and the direct provider.
正文摘录
AI SDK ProvidersMenuAlibabaCopy for LLMView MarkdownAsk AI about this pageAlibaba Cloud Model Studio provides access to the Qwen model series, including advanced reasoning capabilities. You can use Alibaba models through AI Gateway (recommended) or connect directly with @ai-sdk/alibaba. GatewayAlibabaalibaba/qwen3.7-maximport { generateText } from 'ai'; const { text } = await generateText({ model: "alibaba/qwen3.7-max", prompt: 'Write a vegetarian lasagna recipe for 4 people.', }); console.log(text); Using AI Gateway The AI SDK uses AI Gateway by default for model strings. Gateway provides access to models across providers through a single API key, with usage and cost tracking. Install ai: pnpmnpmyarnbun$ pnpm add ai Set an AI Gateway API key in your environment: export AI_GATEWAY_API_KEY=your_api_key_here Vercel deployments can also use OIDC authentication. See the AI Gateway provider documentation for configuration and the model catalog for available models. Gateway feature and provider-option support depends on the model and the provider serving the request. See Gateway provider options. Using @ai-sdk/alibaba For direct access to Alibaba, install ai and @ai-sdk/alibaba: pnpmnpmyarnbun$ pnpm add ai @ai-sdk/alibaba Set your Alibaba API credential in the ALIBABA_API_KEY environment variable: export ALIBABA_API_KEY=your_api_key_here AI Gateway does not expose every API in @ai-sdk/alibaba. Use the direct provider for provider-specific APIs or custom connection settings. The following sections document the direct @ai-sdk/alibaba provider, including its model factories and settings. Gateway model and feature availability can differ. API keys can be obtained from the Console. Provider Instance You can import the default provider instance alibaba from @ai-sdk/alibaba: import { alibaba } from '@ai-sdk/alibaba'; For custom configuration, you can import createAlibaba and create a provider instance with your settings: import { createAlibaba } from '@ai-sdk/alibaba'; const alibaba = createAlibaba({ apiKey: process.env.ALIBABA_API_KEY ?? '', }); You can use the following optional settings to customize the Alibaba provider instance: baseURL string Use a different URL prefix for API calls, e.g. to use proxy servers or regional endpoints. The default prefix is https://dashscope-intl.aliyuncs.com/compatible-mode/v1. videoBaseURL string Use a different URL prefix for video generation API calls. The video API uses the DashScope native endpoint (not the OpenAI-compatible endpoint). The default prefix is https://dashscope-intl.aliyuncs.com. embeddingBaseURL string Use a different URL prefix for embedding API calls. The embedding API uses the DashScope native endpoint (not the OpenAI-compatible endpoint). The default prefix is https://dashscope-intl.aliyuncs.com/api/v1. apiKey string | PromiseLike<string> | (() => string | PromiseLike<string>) API key that is being sent using the Authorization header. It defaults to the ALIBABA_API_KEY environment variable. A function is called before each request and may return a promise. Use it to supply refreshed credentials; a promise value resolves to the same key each time. headers Record<string,string> Custom headers to include in the requests. fetch (input: RequestInfo, init?: RequestInit) => Promise<Response> Custom fetch implementation. includeUsage boolean Include usage information in streaming responses. When enabled, token usage will be included in the final chunk. Defaults to true. Language Models You can create language models using a provider instance: import { alibaba } from '@ai-sdk/alibaba'; import { generateText } from 'ai'; const { text } = await generateText({ model: alibaba('qwen-plus'), prompt: 'Write a vegetarian lasagna recipe for 4 people.', }); You can also use the .chatModel() or .languageModel() factory methods: const model = alibaba.chatModel('qwen-plus'); // or const model = alibaba.languageModel('qwen-plus'); Alibaba language models can be used in the streamText function (see AI SDK Core). The following optional provider options are available for Alibaba models: enableThinking boolean Enable thinking/reasoning mode for supported models. When enabled, the model generates reasoning content before the response. Defaults to false. thinkingBudget number Maximum number of reasoning tokens to generate. Limits the length of thinking content. preserveThinking boolean Preserve reasoning from previous assistant messages for supported models. When enabled, reasoning is sent separately as Alibaba reasoning_content and preserve_thinking is enabled. Defaults to true for models that support preserved thinking; set to false to opt out. Append AI SDK responseMessages unchanged when continuing the conversation. See Alibaba's preserved-thinking documentation for the list of supported models. parallelToolCalls boolean Whether to enable parallel function calling during tool use. Defaults to true. Thinking Mode Alibaba's Qwen models support thinking/reasoning mode for complex problem-solving: import { alibaba, type AlibabaLanguageModelChatOptions } from '@ai-sdk/alibaba'; import { generateText } from 'ai'; const { text, reasoning } = await generateText({ model: alibaba('qwen3-max'), providerOptions: { alibaba: { enableThinking: true, thinkingBudget: 2048, } satisfies AlibabaLanguageModelChatOptions, }, prompt: 'How many "r"s are in the word "strawberry"?', }); console.log('Reasoning:', reasoning); console.log('Answer:', text); For models that are thinking-only (like qwen3-235b-a22b-thinking-2507), thinking mode is enabled by default. Preserved Thinking in Multi-Turn Conversations For models that support preserved thinking, the AI SDK replays reasoning from previous assistant messages as Alibaba reasoning_content by default, so the model can build on its earlier thought process: import { alibaba, type AlibabaLanguageModelChatOptions } from '@ai-sdk/alibaba'; import { generateText, type ModelMessage } from 'ai'; const providerOptions = { alibaba: { enableThinking: true, thinkingBudget: 2048, } satisfies AlibabaLanguageModelChatOptions, }; const opening: ModelMessage = { role: 'user', content: 'Is Kafka or RocketMQ a better fit for transactional messages?', }; const first = await generateText({ model: alibaba('qwen3.7-max'), messages: [opening], providerOptions, }); const second = await generateText({ model: alibaba('qwen3.7-max'), messages: [ opening, ...first.responseMessages, // append unchanged to keep the reasoning parts { role: 'user', content: 'Which tradeoff mattered most?' }, ], providerOptions, }); When continuing the conversation, append responseMessages unchanged. If you rebuild assistant history from visible text only, the reasoning parts are discarded before the provider can serialize them as reasoning_content. Set preserveThinking: false to opt out of replay, and note the following caveats: preserveThinking does not enable thinking by itself. Pair it with enableThinking/thinkingBudget or the top-level reasoning option. It is enabled by default only for models that Alibaba documents as supporting preserved thinking; for other models, preserve_thinking is not sent unless you set the option explicitly. See Alibaba's preserved-thinking documentation for the current list of supported models. Reasoning from the current tool-call round (after the last user message) is always sent back with tool results, as Alibaba recommends; the option only controls reasoning from earlier rounds. Preserved reasoning increases input token usage and billing. Historical reasoning remains separate from visible assistant text; it is never merged into content. Tool Calling Alibaba models support tool calling with parallel execution: import { alibaba } from '@ai-sdk/alibaba'; import { generateText, tool } from 'ai'; import { z } from 'zod'; const { text } = await generateText({ model: alibaba('qwen-plus'), tools: { weather: tool({ description: 'Get the weather in a location', inputSchema: z.object({ location: z.string().describe('The location to get the weather for'), }), execute: async ({ location }) => ({ location, temperature: 72 + Math.floor(Math.random() * 21) - 10, }), }), }, prompt: 'What is the weather in San Francisco?', }); Prompt Caching Alibaba supports both implicit and explicit prompt caching to reduce costs for repeated prompts. Implicit caching works automatically - the provider caches appropriate content without any configuration. For more control, you can use explicit caching by marking specific messages with cacheControl: Single message cache control import { alibaba } from '@ai-sdk/alibaba'; import { generateText } from 'ai'; const { text, usage } = await generateText({ model: alibaba('qwen-plus'), messages: [ { role: 'system', content: 'You are a helpful assistant. [... long system prompt ...]', providerOptions: { alibaba: { cacheControl: { type: 'ephemeral' }, }, }, }, ], }); Multi-part message cache control import { alibaba } from '@ai-sdk/alibaba'; import { generateText } from 'ai'; const longDocument = '... large document content ...'; const { text, usage } = await generateText({ model: alibaba('qwen-plus'), messages: [ { role: 'user', content: [ { type: 'text', text: 'Context: Please analyze this document.', }, { type: 'text', text: longDocument, providerOptions: { alibaba: { cacheControl: { type: 'ephemeral' }, }, }, }, ], }, ], }); Note: The minimum content length for a cache block is 1,024 tokens. Embedding Models You can create text embedding models using the .embedding() factory method. For more on embeddings with the AI SDK see embed() and embedMany(). const model = alibaba.embedding('text-embedding-v4'); You can use Alibaba embedding models to generate embeddings with the embed function: import { alibaba, type AlibabaEmbeddingModelOptions } from '@ai-sdk/alibaba'; import { embed } from 'ai'; const { embedding, usage } = await embed({ model: alibaba.embedding('text-embedding-v4'), value: 'sunny day at the beach', providerOptions: { alibaba: { textType: 'document', dimensio