### Install Qwen AI Provider with npm Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Installs the `qwen-ai-provider-v5` package and `ai` SDK for AI SDK v6 using npm. Ensure you have npm installed. ```bash # For npm (AI SDK v6) npm install qwen-ai-provider-v5@^2 ai@^6.0.0 ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/CONTRIBUTING.md Install project dependencies and run all tests to ensure your changes do not break existing functionality. ```bash pnpm install pnpm test ``` -------------------------------- ### Install Qwen AI Provider with pnpm Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Installs the `qwen-ai-provider-v5` package and `ai` SDK for AI SDK v6 using pnpm. Ensure you have pnpm installed. ```bash # For pnpm (AI SDK v6) pnpm add qwen-ai-provider-v5@^2 ai@^6.0.0 ``` -------------------------------- ### Install Qwen AI Provider with yarn Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Installs the `qwen-ai-provider-v5` package and `ai` SDK for AI SDK v6 using yarn. Ensure you have yarn installed. ```bash # For yarn (AI SDK v6) yarn add qwen-ai-provider-v5@^2 ai@^6.0.0 ``` -------------------------------- ### Clone Repository Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/CONTRIBUTING.md Clone your forked repository to your local machine to start making changes. ```bash git clone https://github.com//qwen-ai-provider.git ``` -------------------------------- ### Use Default Qwen Provider Instance Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Utilize the default pre-built Qwen provider instance, which automatically reads the API key from the environment. This instance can be directly used to get a chat model. ```typescript import { qwen } from "qwen-ai-provider-v5" // Equivalent to: const qwen = createQwen() // Used directly as a function to get a chat model: const model = qwen("qwen-plus") ``` -------------------------------- ### qwen Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt A default provider instance created using `createQwen()` without any arguments. This instance automatically reads the `DASHSCOPE_API_KEY` from the environment and can be used directly to get a chat model. ```APIDOC ## qwen ### Description A pre-built provider instance using `createQwen()` with no arguments. Reads `DASHSCOPE_API_KEY` from the environment automatically. ### Usage Used directly as a function to get a chat model. ### Request Example ```typescript import { qwen } from "qwen-ai-provider-v5" // Equivalent to: const qwen = createQwen() // Used directly as a function to get a chat model: const model = qwen("qwen-plus") ``` ``` -------------------------------- ### Generate Chat Response with Qwen Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Generate a chat response using the 'generateText' function with a conversational history. This example demonstrates setting a system message and providing user and assistant turns. ```typescript import { generateText } from "ai" import { qwen } from "qwen-ai-provider-v5" const result = await generateText({ model: qwen("qwen-plus"), maxTokens: 1024, system: "You are a helpful chatbot.", messages: [ { role: "user", content: "Hello!", }, { role: "assistant", content: "Hello! How can I help you today?", }, { role: "user", content: "I need help with my computer.", }, ], }) console.log(result.text) ``` -------------------------------- ### Import Default Qwen Provider Instance Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Import the default Qwen provider instance for immediate use. ```typescript import { qwen } from "qwen-ai-provider-v5" ``` -------------------------------- ### createQwen(options?) Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Creates a custom provider instance for Qwen models. This instance can then be used to create chat, completion, embedding, and reranking models. Options include apiKey, baseURL, headers, queryParams, and a custom fetch implementation. ```APIDOC ## createQwen(options?) ### Description Creates a custom provider instance that can be used to generate chat, completion, embedding, and reranking models. All options are optional; the API key defaults to the `DASHSCOPE_API_KEY` environment variable. ### Parameters #### Options - **apiKey** (string) - Optional - Your DashScope API key. Defaults to `DASHSCOPE_API_KEY` environment variable. - **baseURL** (string) - Optional - The base URL for the DashScope API. Defaults to the international endpoint. - **headers** (object) - Optional - Custom headers to be sent with every request. - **queryParams** (object) - Optional - URL query parameters to be appended to every request. - **fetch** (function) - Optional - A custom fetch implementation for proxying or testing scenarios. ### Request Example ```typescript import { createQwen } from "qwen-ai-provider-v5" // Default international endpoint const qwen = createQwen({ apiKey: process.env.DASHSCOPE_API_KEY, baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", headers: { "X-Custom-Header": "my-app" }, // Optional: URL query parameters appended to every request queryParams: { source: "my-app" }, // Optional: custom fetch for proxying or testing fetch: (url, init) => { console.log("Request to:", url) return globalThis.fetch(url, init) }, }) // For Chinese (domestic) API keys: const qwenCN = createQwen({ baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1", }) ``` ``` -------------------------------- ### Configure Qwen Reranking Model with Instruction Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Instantiate a Qwen reranking model, specifying 'qwen3-rerank' and providing a custom instruction for task-specific ranking. The default instruction for QA retrieval is also noted. ```typescript // Custom instruction for semantic similarity ranking const model = qwen.rerankingModel("qwen3-rerank", { instruct: "Retrieve semantically similar text." }) // Default instruction (QA retrieval): // "Given a web search query, retrieve relevant passages that answer the query." ``` -------------------------------- ### Configure Qwen Provider Settings Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Set up the Qwen provider with optional configurations like baseURL, API key, custom headers, query parameters, and a custom fetch function. This allows for proxying, authentication, and request customization. ```typescript import { createQwen } from "qwen-ai-provider-v5" const qwen = createQwen({ // Override API endpoint (e.g. for proxy, domestic CN endpoint, or local mock) baseURL: "https://my-proxy.example.com/qwen/v1", // API key (defaults to process.env.DASHSCOPE_API_KEY) apiKey: "sk-xxxxxxxxxxxxxxxxxxxx", // Extra HTTP headers sent with every request headers: { "X-App-Name": "my-nextjs-app", "X-Request-Source": "server", }, // Extra URL query params appended to every request URL queryParams: { region: "us-east-1" }, // Custom fetch: useful for logging, mocking in tests, or corporate proxies fetch: async (input, init) => { const start = Date.now() const response = await globalThis.fetch(input, init) console.log(`[Qwen] ${init?.method} ${input} → ${response.status} (${Date.now() - start}ms)`) return response }, }) // All four model types share the same provider config: const chatModel = qwen("qwen-max") const completionMdl = qwen.completion("qwen-plus") const embeddingMdl = qwen.embeddingModel("text-embedding-v3") const rerankingMdl = qwen.rerankingModel("gte-rerank-v2") ``` -------------------------------- ### Create Customized Qwen Provider Instance Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Create a Qwen provider instance with custom settings like baseURL, apiKey, headers, or a custom fetch implementation. ```typescript import { createQwen } from "qwen-ai-provider-v5" const qwen = createQwen({ // optional settings, e.g. // baseURL: 'https://qwen/api/v1', }) ``` -------------------------------- ### Create Qwen Language Model Instance Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Create a language model instance by specifying the model ID, such as 'qwen-plus'. ```typescript const model = qwen("qwen-plus") ``` -------------------------------- ### Create Custom Qwen Provider Instance Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Instantiate a custom Qwen provider with optional configurations for API key, base URL, headers, query parameters, and a custom fetch implementation. Supports both international and Chinese domestic endpoints. ```typescript import { createQwen } from "qwen-ai-provider-v5" // Default international endpoint const qwen = createQwen({ apiKey: process.env.DASHSCOPE_API_KEY, baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", headers: { "X-Custom-Header": "my-app" }, // Optional: URL query parameters appended to every request queryParams: { source: "my-app" }, // Optional: custom fetch for proxying or testing fetch: (url, init) => { console.log("Request to:", url) return globalThis.fetch(url, init) }, }) // For Chinese (domestic) API keys: const qwenCN = createQwen({ baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1", }) ``` -------------------------------- ### createQwen Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Creates a Qwen AI provider instance with customizable settings. This allows for overriding the API endpoint, setting API keys, and configuring custom headers, query parameters, and fetch behavior. ```APIDOC ## createQwen(settings) ### Description Configuration object accepted by `createQwen()`. All fields are optional. ### Parameters #### Path Parameters - **settings** (QwenProviderSettings) - Optional - Configuration object for the Qwen provider. - **baseURL** (string) - Optional - Override API endpoint (e.g. for proxy, domestic CN endpoint, or local mock). - **apiKey** (string) - Optional - API key (defaults to process.env.DASHSCOPE_API_KEY). - **headers** (object) - Optional - Extra HTTP headers sent with every request. - **queryParams** (object) - Optional - Extra URL query params appended to every request URL. - **fetch** (function) - Optional - Custom fetch function, useful for logging, mocking in tests, or corporate proxies. ### Request Example ```typescript import { createQwen } from "qwen-ai-provider-v5" const qwen = createQwen({ // Override API endpoint (e.g. for proxy, domestic CN endpoint, or local mock) baseURL: "https://my-proxy.example.com/qwen/v1", // API key (defaults to process.env.DASHSCOPE_API_KEY) apiKey: "sk-xxxxxxxxxxxxxxxxxxxx", // Extra HTTP headers sent with every request headers: { "X-App-Name": "my-nextjs-app", "X-Request-Source": "server", }, // Extra URL query params appended to every request URL queryParams: { region: "us-east-1" }, // Custom fetch: useful for logging, mocking in tests, or corporate proxies fetch: async (input, init) => { const start = Date.now() const response = await globalThis.fetch(input, init) console.log(`[Qwen] ${init?.method} ${input} → ${response.status} (${Date.now() - start}ms)`) return response }, }) // All four model types share the same provider config: const chatModel = qwen("qwen-max") const completionMdl = qwen.completion("qwen-plus") const embeddingMdl = qwen.embeddingModel("text-embedding-v3") const rerankingMdl = qwen.rerankingModel("gte-rerank-v2") ``` ``` -------------------------------- ### Configure Qwen Reranking Settings Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Adjust settings for Qwen reranking models, such as enabling document inclusion in the response or providing specific instructions for the reranking task. These options vary by model, with `returnDocuments` for `gte-rerank-v2` and `instruct` for `qwen3-rerank`. ```typescript import { rerank } from "ai" import { qwen } from "qwen-ai-provider-v5" // returnDocuments: only supported by gte-rerank-v2 const { ranking } = await rerank({ model: qwen.rerankingModel("gte-rerank-v2", { returnDocuments: true, // Include document text in response }), documents: ["AI is changing the world.", "The sun is a star."], query: "artificial intelligence", }) // instruct: only supported by qwen3-rerank const { ranking: r2 } = await rerank({ model: qwen.rerankingModel("qwen3-rerank", { instruct: "Given a question, retrieve passages that directly answer it.", }), documents: ["Photosynthesis is the process by which plants make food."], query: "How do plants produce energy?", }) ``` -------------------------------- ### `qwen.completion(modelId, settings?)` — Completion language model Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Creates a `LanguageModelV3` for raw text completions. Does not support tools or JSON response format. Supports `echo`, `logitBias`, and `suffix` settings. ```APIDOC ## `qwen.completion(modelId, settings?)` — Completion language model ### Description Creates a `LanguageModelV3` for raw text completions (non-chat, `/completions` endpoint). Does not support tools or JSON response format. Supports `echo`, `logitBias`, and `suffix` settings. ### Usage Examples **Non-streaming completion:** ```typescript import { generateText } from "ai" import { qwen } from "qwen-ai-provider-v5" const { text } = await generateText({ model: qwen.completion("qwen-plus", { echo: false, // Do not echo the prompt in the response suffix: " [END]", // Append a string after the generated text user: "user-42", // End-user identifier for abuse monitoring }), prompt: "The quick brown fox", maxOutputTokens: 50, temperature: 0.5, stopSequences: ["\n", "END"], }) console.log(text) // "jumps over the lazy dog [END]" ``` **Streaming completion:** ```typescript import { streamText } from "ai" import { qwen } from "qwen-ai-provider-v5" const stream = streamText({ model: qwen.completion("qwen-turbo"), prompt: "Once upon a time", maxOutputTokens: 200, }) for await (const delta of stream.textStream) { process.stdout.write(delta) } ``` ``` -------------------------------- ### mapQwenFinishReason Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Converts Qwen/OpenAI finish_reason strings into the AI SDK v6 LanguageModelV3FinishReason object. This utility is used internally by chat and completion models and is also available for custom integrations. ```APIDOC ## mapQwenFinishReason(finishReason) ### Description Exported utility that converts Qwen/OpenAI `finish_reason` strings into the AI SDK v6 `LanguageModelV3FinishReason` object `{ unified, raw }`. Used internally by chat and completion models; also available for custom integrations. ### Parameters #### Path Parameters - **finishReason** (string | null) - Required - The finish reason string from Qwen or null. ### Request Example ```typescript import { mapQwenFinishReason } from "qwen-ai-provider-v5" console.log(mapQwenFinishReason("stop")) // { unified: "stop", raw: "stop" } console.log(mapQwenFinishReason("tool_calls")) // { unified: "tool-calls", raw: "tool_calls" } console.log(mapQwenFinishReason("length")) // { unified: "length", raw: "length" } console.log(mapQwenFinishReason("content_filter")) // { unified: "content-filter", raw: "content_filter" } console.log(mapQwenFinishReason(null)) // { unified: "other", raw: undefined } ``` ### Response #### Success Response (200) - **unified** (string) - The unified finish reason. - **raw** (string | undefined) - The raw finish reason from the provider. ### Response Example ```json { "unified": "stop", "raw": "stop" } ``` ``` -------------------------------- ### Create Qwen Reranking Model Instance Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Create a reranking model instance using the `rerankingModel` factory method to improve search relevance by reordering documents. ```typescript const model = qwen.rerankingModel("gte-rerank-v2") ``` -------------------------------- ### Mermaid Diagram of Qwen Provider Integration Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Illustrates the architecture of how the Qwen provider integrates with the Vercel AI SDK, including environment variables and API endpoints. ```mermaid graph TD A[Next.js Application] --> B[Vercel AI SDK Core] B --> C{AI Provider} C --> D[qwen-ai-provider] C --> E[Community Providers] D --> F[Qwen API Endpoints] F --> G[Qwen-plus] F --> H[Qwen-vl-max] F --> I[Qwen-max] B --> J[AI SDK Functions] J --> K["generateText()"] J --> L["streamText()"] J --> M["generateObject()"] J --> N["streamUI()"] A --> O[Environment Variables] O --> P["DASHSCOPE_API_KEY"] O --> Q["AI_PROVIDER=qwen"] subgraph Provider Configuration D --> R["createQwen({ baseURL: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1', apiKey: env.DASHSCOPE_API_KEY })"] R --> S[Model Instance] S --> T["qwen('qwen-plus')"] end subgraph Response Handling K --> U[Text Output] L --> V[Streaming Response] M --> W[Structured JSON] N --> X[UI Components] end style D fill:#74aa63,color:#fff style E fill:#4f46e5,color:#fff style J fill:#f59e0b,color:#000 ``` -------------------------------- ### Create Qwen Chat Language Model Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Use `qwen` or `qwen.chatModel` to create a chat language model. Supports text generation, multi-turn conversations, vision input, structured output, tool calling, and streaming. `topK` is not supported. ```typescript import { generateText, streamText, tool } from "ai" import { qwen } from "qwen-ai-provider-v5" import { z } from "zod" // --- Basic text generation --- const { text } = await generateText({ model: qwen("qwen-plus"), prompt: "Explain the theory of relativity in two sentences.", }) console.log(text) ``` ```typescript // --- Multi-turn conversation with system prompt --- const { text: reply } = await generateText({ model: qwen("qwen-max"), maxOutputTokens: 512, temperature: 0.7, system: "You are a helpful assistant that speaks concisely.", messages: [ { role: "user", content: "Hello!" }, { role: "assistant", content: "Hi! How can I help?" }, { role: "user", content: "What is the capital of Japan?" }, ], }) ``` ```typescript // --- Vision: image understanding (qwen-vl-max) --- const { text: imageDesc } = await generateText({ model: qwen("qwen-vl-max"), messages: [{ role: "user", content: [ { type: "text", text: "Describe this image." }, { type: "image", image: new URL("https://example.com/photo.jpg") }, ], }], }) ``` ```typescript // --- Structured output with Zod schema (AI SDK v6 style) --- const { object } = await generateText({ model: qwen("qwen-plus"), output: { schema: z.object({ recipe: z.object({ name: z.string(), ingredients: z.array(z.object({ name: z.string(), amount: z.string() })), steps: z.array(z.string()), }), }), }, prompt: "Generate a simple pasta recipe.", }) console.log(JSON.stringify(object.recipe, null, 2)) ``` ```typescript // --- Tool calling --- const result = await generateText({ model: qwen("qwen-plus"), tools: { getWeather: tool({ description: "Get current weather for a city", parameters: z.object({ city: z.string().describe("The city name"), }), execute: async ({ city }) => ({ city, temperature: 22, unit: "C" }), }), }, prompt: "What is the weather in Tokyo?", }) console.log(result.text) // Tool calls are automatically executed; result.text contains the final answer ``` ```typescript // --- Streaming --- const stream = streamText({ model: qwen("qwen-plus"), prompt: "Write a haiku about the sea.", onFinish({ usage, finishReason }) { console.log("Tokens used:", usage.inputTokens.total, "+", usage.outputTokens.total) console.log("Finish reason:", finishReason.unified) // "stop" | "length" | "tool-calls" | etc. }, }) for await (const chunk of stream.textStream) { process.stdout.write(chunk) } ``` ```typescript // --- simulateStreaming setting (for models that don't support SSE) --- const chatModel = qwen("qwen-turbo", { simulateStreaming: true }) ``` -------------------------------- ### Generate Text with Qwen Language Model Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Use the `generateText` function with a Qwen model to generate text based on a prompt. Ensure 'ai' and 'qwen-ai-provider-v5' are imported. ```typescript import { generateText } from "ai" import { qwen } from "qwen-ai-provider-v5" const { text } = await generateText({ model: qwen("qwen-plus"), prompt: "Write a vegetarian lasagna recipe for 4 people.", }) ``` -------------------------------- ### `qwen(modelId, settings?)` / `qwen.chatModel(modelId, settings?)` — Chat language model Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Creates a `LanguageModelV3` for chat completions. Supports text generation, multi-turn conversations, vision input, structured output, tool calling, streaming, and reasoning content. `topK` is not supported. ```APIDOC ## `qwen(modelId, settings?)` / `qwen.chatModel(modelId, settings?)` — Chat language model ### Description Creates a `LanguageModelV3` for chat completions. Supports text generation, multi-turn conversations, vision input (image URLs or base64), structured output, tool calling, streaming, and reasoning content. `topK` is not supported and will produce a warning. ### Usage Examples **Basic text generation:** ```typescript import { generateText } from "ai" import { qwen } from "qwen-ai-provider-v5" const { text } = await generateText({ model: qwen("qwen-plus"), prompt: "Explain the theory of relativity in two sentences." }) console.log(text) ``` **Multi-turn conversation with system prompt:** ```typescript import { generateText } from "ai" import { qwen } from "qwen-ai-provider-v5" const { text: reply } = await generateText({ model: qwen("qwen-max"), maxOutputTokens: 512, temperature: 0.7, system: "You are a helpful assistant that speaks concisely.", messages: [ { role: "user", content: "Hello!" }, { role: "assistant", content: "Hi! How can I help?" }, { role: "user", content: "What is the capital of Japan?" }, ] }) console.log(reply) ``` **Vision: image understanding (qwen-vl-max):** ```typescript import { generateText } from "ai" import { qwen } from "qwen-ai-provider-v5" const { text: imageDesc } = await generateText({ model: qwen("qwen-vl-max"), messages: [{ role: "user", content: [ { type: "text", text: "Describe this image." }, { type: "image", image: new URL("https://example.com/photo.jpg") }, ], }] }) console.log(imageDesc) ``` **Structured output with Zod schema:** ```typescript import { generateText } from "ai" import { qwen } from "qwen-ai-provider-v5" import { z } from "zod" const { object } = await generateText({ model: qwen("qwen-plus"), output: { schema: z.object({ recipe: z.object({ name: z.string(), ingredients: z.array(z.object({ name: z.string(), amount: z.string() })), steps: z.array(z.string()), }), }), }, prompt: "Generate a simple pasta recipe." }) console.log(JSON.stringify(object.recipe, null, 2)) ``` **Tool calling:** ```typescript import { generateText, tool } from "ai" import { qwen } from "qwen-ai-provider-v5" import { z } from "zod" const result = await generateText({ model: qwen("qwen-plus"), tools: { getWeather: tool({ description: "Get current weather for a city", parameters: z.object({ city: z.string().describe("The city name") }), execute: async ({ city }) => ({ city, temperature: 22, unit: "C" }) }) }, prompt: "What is the weather in Tokyo?" }) console.log(result.text) ``` **Streaming:** ```typescript import { streamText } from "ai" import { qwen } from "qwen-ai-provider-v5" const stream = streamText({ model: qwen("qwen-plus"), prompt: "Write a haiku about the sea.", onFinish({ usage, finishReason }) { console.log("Tokens used:", usage.inputTokens.total, "+", usage.outputTokens.total) console.log("Finish reason:", finishReason.unified) }, }) for await (const chunk of stream.textStream) { process.stdout.write(chunk) } ``` **`simulateStreaming` setting:** ```typescript import { qwen } from "qwen-ai-provider-v5" const chatModel = qwen("qwen-turbo", { simulateStreaming: true }) ``` ``` -------------------------------- ### Create Qwen Completion Language Model Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Use `qwen.completion` for raw text completions. Does not support tools or JSON response format. Supports `echo`, `logitBias`, and `suffix` settings. ```typescript import { generateText, streamText } from "ai" import { qwen } from "qwen-ai-provider-v5" // Non-streaming completion const { text } = await generateText({ model: qwen.completion("qwen-plus", { echo: false, // Do not echo the prompt in the response suffix: " [END]", // Append a string after the generated text user: "user-42", // End-user identifier for abuse monitoring }), prompt: "The quick brown fox", maxOutputTokens: 50, temperature: 0.5, stopSequences: ["\n", "END"], }) console.log(text) // "jumps over the lazy dog [END]" ``` ```typescript // Streaming completion const stream = streamText({ model: qwen.completion("qwen-turbo"), prompt: "Once upon a time", maxOutputTokens: 200, }) for await (const delta of stream.textStream) { process.stdout.write(delta) } ``` -------------------------------- ### Map Qwen Finish Reason to AI SDK v6 Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Converts Qwen/OpenAI finish_reason strings to the AI SDK v6 LanguageModelV3FinishReason object. Useful for custom post-processing of model responses, especially when handling truncated content. ```typescript import { mapQwenFinishReason } from "qwen-ai-provider-v5" console.log(mapQwenFinishReason("stop")) // { unified: "stop", raw: "stop" } console.log(mapQwenFinishReason("tool_calls")) // { unified: "tool-calls", raw: "tool_calls" } console.log(mapQwenFinishReason("length")) // { unified: "length", raw: "length" } console.log(mapQwenFinishReason("content_filter")) // { unified: "content-filter", raw: "content_filter" } console.log(mapQwenFinishReason(null)) // { unified: "other", raw: undefined } ``` ```typescript import { generateText } from "ai" import { qwen } from "qwen-ai-provider-v5" const result = await generateText({ model: qwen("qwen-plus"), prompt: "Hi" }) const reason = result.finishReason // reason.unified === "stop" // reason.raw === "stop" if (reason.unified === "length") { console.warn("Response was truncated! Consider increasing maxOutputTokens.") } ``` -------------------------------- ### Create Qwen Provider Instance with Domestic Endpoint Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md For Chinese users with a domestic API key, specify the domestic endpoint when creating the Qwen provider instance. ```typescript import { createQwen } from "qwen-ai-provider-v5" const qwen = createQwen({ baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1", }) ``` -------------------------------- ### Configure Qwen Chat Settings Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Apply optional settings for Qwen chat models, such as specifying a unique end-user ID for monitoring or simulating streaming for models that do not natively support SSE. These settings are passed during model instantiation. ```typescript import { streamText } from "ai" import { qwen } from "qwen-ai-provider-v5" const model = qwen("qwen-plus", { // Unique end-user ID for monitoring and abuse detection user: "user-abc123", // Simulate streaming for models that don't support SSE // (wraps doGenerate and emits chunks from the full response) simulateStreaming: false, }) const stream = streamText({ model, prompt: "Tell me a joke." }) for await (const chunk of stream.textStream) { process.stdout.write(chunk) } ``` -------------------------------- ### Generate Object with Reasoning Model Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md This snippet imports both 'generateObject' and 'generateText' from the 'ai' package, indicating potential use cases for generating structured data with or without explicit reasoning steps. ```typescript import { generateObject, generateText } from "ai" ``` -------------------------------- ### Generate Text with Image Prompt using Qwen Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Utilize the 'generateText' function with a multimodal prompt that includes both text and an image. This allows the AI to process and respond to image-based queries. ```typescript import { generateText } from "ai" import { qwen } from "qwen-ai-provider-v5" const result = await generateText({ model: qwen("qwen-plus"), maxTokens: 512, messages: [ { role: "user", content: [ { type: "text", text: "what are the red things in this image?", }, { type: "image", image: new URL( "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3e/2024_Solar_Eclipse_Prominences.jpg/720px-2024_Solar_Eclipse_Prominences.jpg", ), }, ], }, ], }) console.log(result) ``` -------------------------------- ### Create Qwen Embedding Model Instance Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Create an embedding model instance using the `embeddingModel` factory method. The 'text-embedding-v3' model is recommended. ```typescript // Recommended: Use embeddingModel (AI SDK v6) const model = qwen.embeddingModel("text-embedding-v3") ``` -------------------------------- ### qwen.rerankingModel Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Creates a RerankingModelV3 for reordering documents by relevance to a query. Supports both DashScope native API (`gte-rerank`, `gte-rerank-v2`, `gte-rerank-hybrid-v1`) and OpenAI-compatible API (`qwen3-rerank`). Returns a ranked list sorted by `relevanceScore` descending. ```APIDOC ## `qwen.rerankingModel(modelId, settings?)` — Reranking model Creates a `RerankingModelV3` for reordering documents by relevance to a query. Supports both DashScope native API (`gte-rerank`, `gte-rerank-v2`, `gte-rerank-hybrid-v1`) and OpenAI-compatible API (`qwen3-rerank`). Returns a ranked list sorted by `relevanceScore` descending. ### Parameters - **modelId** (string) - Required - The ID of the reranking model to use (e.g., `"gte-rerank-v2"`, `"qwen3-rerank"`). - **settings** (object) - Optional - Configuration settings for the reranking model. - **instruct** (string) - Optional - A custom instruction to guide the reranking process. Defaults to a general search relevance instruction. - **returnDocuments** (boolean) - Optional - Whether to return the original documents along with the ranking. Defaults to false. ### Usage Examples #### Basic Reranking ```typescript import { rerank } from "ai" import { qwen } from "qwen-ai-provider-v5" const documents = [ "Machine learning is a subset of artificial intelligence.", "Paris is the capital city of France.", "Neural networks are inspired by the human brain.", "The Eiffel Tower is located in Paris.", "Deep learning uses multiple layers of neural networks.", ] const { ranking, rerankedDocuments } = await rerank({ model: qwen.rerankingModel("gte-rerank-v2"), documents, query: "What is artificial intelligence and machine learning?", topN: 3, }) console.log("Top 3 documents:", rerankedDocuments) console.log("Ranking with scores:") ranking.forEach(({ originalIndex, relevanceScore, document }) => { console.log(` [${originalIndex}] score=${relevanceScore.toFixed(4)}: ${document}`) }) ``` #### Reranking with Custom Instruction ```typescript import { rerank } from "ai" import { qwen } from "qwen-ai-provider-v5" const { ranking: semanticRanking } = await rerank({ model: qwen.rerankingModel("qwen3-rerank", { instruct: "Retrieve semantically similar text.", }), documents: [ "The cat sat on the mat.", "A feline rested on a rug.", "Dogs love to play fetch.", ], query: "A cat lying on a carpet.", topN: 2, }) console.log("Most similar:", semanticRanking[0]) ``` #### Reranking Object Documents ```typescript import { rerank } from "ai" import { qwen } from "qwen-ai-provider-v5" const objectDocs = [ { id: "1", title: "AI Basics", body: "Machine learning is a subset of AI." }, { id: "2", title: "Geography", body: "Paris is the capital of France." }, { id: "3", title: "Neural Nets", body: "Neural networks are brain-inspired." }, ] const { ranking: objRanking } = await rerank({ model: qwen.rerankingModel("gte-rerank-v2", { returnDocuments: true }), documents: objectDocs, query: "How does artificial intelligence work?", topN: 2, }) console.log("Best match:", objRanking[0].document) ``` ``` -------------------------------- ### Generate Text with Qwen Model Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Generate text using the 'generateText' function from the AI package and the 'qwen-plus' model from the Qwen provider. This is suitable for standard text generation tasks. ```typescript // Import the text generation function from the AI package import { generateText } from "ai" // Import the qwen function from qwen-ai-provider-v5 to select the AI model import { qwen } from "qwen-ai-provider-v5" // Use generateText with a specific model and prompt to generate AI text // The qwen function selects the 'qwen-plus' model const result = await generateText({ model: qwen("qwen-plus"), // Select the desired AI model prompt: "Why is the sky blue?", // Define the prompt for the AI }) // Log the result from the AI text generation console.log(result) ``` -------------------------------- ### Push Branch to Fork Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/CONTRIBUTING.md Push your local branch with your changes to your forked repository on GitHub. ```bash git push origin my-feature ``` -------------------------------- ### Create Qwen Embedding Model Instance (Legacy) Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Create an embedding model instance using the deprecated `textEmbeddingModel` factory method for backward compatibility. ```typescript // Also supported: textEmbeddingModel (deprecated, but still works) const modelLegacy = qwen.textEmbeddingModel("text-embedding-v3") ``` -------------------------------- ### Configure Qwen Embedding Settings Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Customize settings for Qwen embedding models, including output vector dimensions, text type for queries or documents, output type (dense, sparse, or both), and an end-user identifier. These settings are applied when creating the embedding model instance. ```typescript import { embedMany } from "ai" import { qwen } from "qwen-ai-provider-v5" const { embeddings } = await embedMany({ model: qwen.embeddingModel("text-embedding-v3", { dimensions: 512, // Output vector size: 1024 (default), 768, or 512 text_type: "query", // "query" for search queries, "document" for stored texts output_type: "sparse", // "dense", "sparse", or "dense&sparse" user: "user-xyz", // End-user identifier }), values: ["What is quantum computing?", "How does blockchain work?"], }) console.log(embeddings[0].length) // 512 ``` -------------------------------- ### Qwen Reranking Model Settings Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Optional settings for Qwen reranking models, passed to `qwen.rerankingModel(modelId, settings)`. ```APIDOC ## qwen.rerankingModel(modelId, settings) ### Description Optional settings for `qwen.rerankingModel(modelId, settings)`. ### Parameters #### Path Parameters - **modelId** (string) - Required - The ID of the Qwen reranking model to use. - **settings** (QwenRerankingSettings) - Optional - Reranking-specific settings. - **returnDocuments** (boolean) - Optional - Include document text in response (only supported by gte-rerank-v2). - **instruct** (string) - Optional - Instruction for the reranking model (only supported by qwen3-rerank). ### Request Example ```typescript import { rerank } from "ai" import { qwen } from "qwen-ai-provider-v5" // returnDocuments: only supported by gte-rerank-v2 const { ranking } = await rerank({ model: qwen.rerankingModel("gte-rerank-v2", { returnDocuments: true, // Include document text in response }), documents: ["AI is changing the world.", "The sun is a star."], query: "artificial intelligence", }) // instruct: only supported by qwen3-rerank const { ranking: r2 } = await rerank({ model: qwen.rerankingModel("qwen3-rerank", { instruct: "Given a question, retrieve passages that directly answer it.", }), documents: ["Photosynthesis is the process by which plants make food."], query: "How do plants produce energy?", }) ``` ``` -------------------------------- ### Call Tools with Generate Text Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Define and use tools with `generateText` to allow the AI to perform actions. The `tools` object maps tool names to their definitions, including descriptions and parameters. ```typescript import { generateText, tool } from "ai" import { qwen } from "qwen-ai-provider-v5" import { z } from "zod" const result = await generateText({ model: qwen("qwen-plus"), tools: { weather: tool({ description: "Get the weather in a location", parameters: 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, }), }), cityAttractions: tool({ parameters: z.object({ city: z.string() }), }), }, prompt: "What is the weather in San Francisco and what attractions should I visit?", }) ``` -------------------------------- ### Create New Branch Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/CONTRIBUTING.md Always create a new branch for your work to keep changes organized and separate. ```bash git checkout -b my-feature ``` -------------------------------- ### Generate Structured Object with Qwen and Zod Source: https://github.com/bolechen/qwen-ai-provider-v5/blob/main/README.md Generate a structured object using 'generateText' with an output schema defined by Zod. This is useful for parsing AI-generated content into a predictable format, such as a recipe. ```typescript import { generateText } from "ai" import { qwen } from "qwen-ai-provider-v5" import { z } from "zod" // AI SDK v6: Use generateText with output setting instead of generateObject const result = await generateText({ model: qwen("qwen-plus"), output: { schema: z.object({ recipe: z.object({ name: z.string(), ingredients: z.array( z.object({ name: z.string(), amount: z.string(), }), ), steps: z.array(z.string()), }), }), }, prompt: "Generate a lasagna recipe.", }) console.log(JSON.stringify(result.object.recipe, null, 2)) ``` -------------------------------- ### Qwen Chat Model Settings Source: https://context7.com/bolechen/qwen-ai-provider-v5/llms.txt Optional settings for Qwen chat models. These can be passed as the second argument to `qwen(modelId, settings)` or `qwen.chatModel(modelId, settings)`. ```APIDOC ## qwen(modelId, settings) or qwen.chatModel(modelId, settings) ### Description Optional settings passed as the second argument to `qwen(modelId, settings)` or `qwen.chatModel(modelId, settings)`. ### Parameters #### Path Parameters - **modelId** (string) - Required - The ID of the Qwen model to use. - **settings** (QwenChatSettings) - Optional - Chat-specific settings. - **user** (string) - Optional - Unique end-user ID for monitoring and abuse detection. - **simulateStreaming** (boolean) - Optional - Simulate streaming for models that don't support SSE (wraps doGenerate and emits chunks from the full response). ### Request Example ```typescript import { streamText } from "ai" import { qwen } from "qwen-ai-provider-v5" const model = qwen("qwen-plus", { // Unique end-user ID for monitoring and abuse detection user: "user-abc123", // Simulate streaming for models that don't support SSE // (wraps doGenerate and emits chunks from the full response) simulateStreaming: false, }) const stream = streamText({ model, prompt: "Tell me a joke." }) for await (const chunk of stream.textStream) { process.stdout.write(chunk) } ``` ```