Skip to main content

Web search

The training data for large language models has a knowledge cutoff date, preventing them from answering real-time questions. Enabling web search lets the model retrieve real-time data and accurately answer time-sensitive questions, such as stock prices, weather forecasts, and breaking news.

Usage

You can enable web search using the four API calls below, each requiring different parameters.
Some models, such as glm-5.2 and kimi-k3, support web search only through the Responses API.
  • OpenAI-compatible: Responses API
  • OpenAI-compatible: Chat Completions API
  • DashScope
  • Anthropic-compatible
Add the web_search tool to the tools parameter to enable web search.
The Responses API supports only some models. For the supported models, see Web search with Responses API.
# Import dependencies and create a client...
response = client.responses.create(
    model="qwen3.8-max",
    input="Hangzhou weather",
    tools=[
        {"type": "web_search"},
        {"type": "web_extractor"},
        {"type": "code_interpreter"}
    ],
    extra_body={"enable_thinking": True}
)

Web search with multimodal models

The Qwen3.8 Max, Flash, and open-source series, Qwen3.7-Flash, Qwen3.7-Plus, the Qwen3.6 series, and the Qwen3.5 series (including qwen3.5-plus, qwen3.5-flash, the qwen3.5-omni series, and Qwen open-source models) accept multimodal input (images, video) and are multimodal models. Call these models through the multimodal API (the multimodal-generation endpoint): use MultiModalConversation in both Python and Java, not Generation (the text-generation endpoint), which is for text-only models. For the basics of calling multimodal models, see the Visual reasoning and Image and video understanding topics. Search strategy support varies by series: the qwen3.5-omni series supports only the agent strategy; qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, and qwen3.8-27b do not support the agent strategy on the multimodal API (use the default turbo or max)—to run Qwen3.8 with agent-style retrieval, use Web search with the Responses API; other models listed in this section support the turbo, max, and agent strategies.
Calling the multimodal models above with Generation (the text-generation endpoint) returns 400 url error, please check url. Use MultiModalConversation (the multimodal-generation endpoint) instead.In the Java SDK, MultiModalConversationParam provides enableSearch(true) to enable web search, but does not provide a searchOptions() method. Inject the search strategy and other options through the generic parameter("search_options", ...) method. In Python, MultiModalConversation.call accepts search_options directly.Web search on multimodal models requires streaming calls (use streamCall in Java, or set stream=True in Python); otherwise the request returns a Non-streaming mode does not support Web Search error.
Python
import os
import dashscope
from dashscope import MultiModalConversation
# The following uses the Singapore region. Replace {WorkspaceId} with your actual workspace ID; the configuration differs by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
responses = MultiModalConversation.call(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Use a multimodal model that supports web search.
    model="qwen3.5-plus",
    messages=[{"role": "user", "content": [{"text": "What is the weather in Hangzhou today?"}]}],
    # The multimodal API accepts enable_search and search_options directly.
    enable_search=True,
    search_options={
        # The qwen3.5-omni series requires agent. On the multimodal API the Qwen3.8 series does not support agent; keep the default.
        "search_strategy": "agent",
        "enable_source": True,
    },
    # Streaming is required when web search is enabled for multimodal models.
    stream=True,
    incremental_output=True,
)
for response in responses:
    print(response.output.choices[0].message.content)

Supported models

The following models support web search. Models with multimodal input (the Qwen3.8 series, Qwen3.7-Flash/Plus, the Qwen3.6 series, the Qwen3.5 series, and Qwen open-source models) must be called through the multimodal API. See Web search with multimodal models.
  • China (Beijing)
  • Singapore
  • Global
  • Qwen
    • Qwen3.8 series: qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, qwen3.8-27b (search_strategy: agent is not supported; for agent-style retrieval, use the web_search tool through the Responses API)
    • Qwen3.7 series: qwen3.7-max, qwen3.7-max-preview, qwen3.7-max-2026-05-17 and later snapshots, qwen3.7-plus, qwen3.7-plus-2026-05-26 and later snapshots, qwen3.7-flash, qwen3.7-flash-2026-07-15 and later snapshots
    • Qwen3.6 series: qwen3.6-plus, qwen3.6-plus-2026-04-02 and later snapshots, qwen3.6-flash, qwen3.6-flash-2026-04-16 and later snapshots, qwen3.6-27b, qwen3.6-35b-a3b
    • Qwen3.5 series: qwen3.5-plus, qwen3.5-plus-2026-02-15 and later snapshots, qwen3.5-flash, qwen3.5-flash-2026-02-23 and later snapshots, qwen3.5-27b, qwen3.5-35b-a3b, qwen3.5-122b-a10b, qwen3.5-397b-a17b
    • Qwen-Max: qwen-max and later snapshots
    • Qwen-Plus: qwen-plus, qwen-plus-latest, qwen-plus-2025-07-14 and later snapshots
    • Qwen-Flash: qwen-flash, qwen-flash-2025-07-28 and later snapshots
    • Qwen-Omni: qwen3.8-omni-flash, qwen3.5-omni-plus, qwen3.5-omni-plus-2026-03-15, qwen3.5-omni-flash, qwen3.5-omni-flash-2026-03-15 (the search strategy must be set to agent)
    • Qwen-Omni-Realtime: qwen3.8-omni-flash-realtime, qwen3.5-omni-plus-realtime, qwen3.5-omni-plus-realtime-2026-03-15, qwen3.5-omni-flash-realtime, qwen3.5-omni-flash-realtime-2026-03-15 (the search strategy must be set to agent)
    • Role-playing: qwen-plus-character, qwen-flash-character, qwen-flash-character-2026-02-26 (the agent strategy is not supported)
    Qwen-Max, Qwen-Plus, and Qwen-Flash models released after July 2025 automatically support web search.
  • Third-party models
    • DeepSeek: deepseek-v4-pro, deepseek-v4-pro-0813, deepseek-v4-flash-0731 (the deepseek-v4 series also supports the Responses API)
    • GLM: glm-5.2 (supported only by the Responses API)
    • Kimi: kimi-k3 (supported only by the Responses API)

Quick start

This example shows how to query weather information using web search.
  • OpenAI compatible
  • DashScope
Set enable_search=True to enable web search. For qwen3.8-omni-flash, also set search_options={"search_strategy": "agent"}. When using the Responses API, configure tools=[{"type": "web_search"}] instead. See Web search with the Responses API.
  • Python
  • Node.js
  • Curl
import os
from openai import OpenAI

client = OpenAI(
    # If the environment variable is not set, provide your Model Studio API key directly: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following configuration is for the China (Beijing) region. Replace {WorkspaceId} with your actual Workspace ID. Configurations vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-plus",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is the weather in Hangzhou tomorrow?"},
    ],
    extra_body={"enable_search": True}
)
print(completion.choices[0].message.content)
Sample response
According to the available data, the weather forecast for Hangzhou on September 17, 2025 (tomorrow) is as follows:

- **Weather conditions**: Partly cloudy to clear, with a chance of light rain in some areas.
- **Temperature**: Daytime high of about 30°C to 34°C, nighttime low of about 24°C to 26°C.
- **Wind**: Light winds, generally from the east, southeast, or west, with speeds less than level 3.
- **Humidity**: Relative humidity of about 77%.
- **Air quality**: Good, with an air quality index of about 34 to 38.
- **Clothing suggestion**: We recommend wearing cool and breathable clothing, such as cotton or linen shirts, light long skirts, or thin T-shirts.

In addition, a cold front will arrive in Zhejiang tomorrow afternoon and evening, gradually bringing cooler temperatures, but the high temperatures will persist until the afternoon. Starting from the 18th, the high temperatures across the province will completely subside.

Please pay attention to the weather changes and adjust your travel and clothing plans accordingly.

Core features

In addition to basic search, web search supports advanced features such as forced search, search policy settings, and returning search sources. The DashScope protocol supports all of these features. By contrast, the OpenAI-compatible protocol does not support returning search sources or superscript annotation. The table below details these differences.

Feature

DashScope

OpenAI compatible: Chat completions

OpenAI compatible: Responses

basic web search

Supported

Supported

Supported

forced web search

Supported

Supported

Not supported

search volume strategy

Supported

Supported

Not supported

domain-specific search

Supported

Supported

Not supported

search timeliness

Supported

Supported

Not supported

source site restriction

Supported

Supported

Not supported

natural language scope control

Supported

Supported

Not supported

search source citation

Supported

Not supported

Not supported

citation markers

Supported

Not supported

Not supported

early source return

Supported

Not supported

Not supported

mixed text and image output

Supported

Supported

Not supported

Search strategy

Use the search_strategy parameter to balance cost, quality, and response speed. Valid values for search_strategy:
  • turbo (default): Balances response speed and search quality. Suitable for most scenarios.
  • max: Uses a more comprehensive search strategy that queries multiple search engines for more detailed results but may increase response time.
  • agent: Integrates information over multiple rounds by repeatedly calling the web search tool and the large model.
    This strategy is applicable to the Qwen3.5 series (including open-source and Omni models), the Qwen3.6 series, and the Qwen3.7 series. Streaming calls are required when using the text endpoint. Qwen3.8-Omni-Flash also supports this strategy through Chat Completions. qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, and qwen3.8-27b do not support search_strategy: agent on Chat Completions or DashScope, but they can achieve equivalent agent-style multi-turn retrieval through the web_search tool on the Responses API. Role-playing models do not support the agent strategy.
    When this strategy is enabled, only return search sources (enable_source: true) is supported. Other web search features are unavailable.
    Enabling this strategy incurs an additional fee per call. For more information, see billing.
  • agent_max: Expands on the agent strategy by adding support for the web extractor. For more information, see web extractor.
    When this strategy is enabled, only return search sources (enable_source: true) is supported. Other web search features are unavailable.
    Enabling this strategy incurs an additional fee per call. For more information, see billing.
Use the default turbo strategy for routine queries. For high-precision tasks like research or report generation that require multi-source cross-validation, choose the max or agent strategy. The agent strategy is particularly effective for queries in English.
  • OpenAI compatible
  • DashScope
  • Python
  • Node.js
  • curl
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following configuration is for the China (Beijing) region. Replace {WorkspaceId} with your actual Workspace ID. Configurations vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-plus",
    messages=[
        {"role": "user", "content": "What models did Qwen release in September 2025?"},
    ],
    extra_body={
        "enable_search": True,
        "search_options": {
            "search_strategy": "max"  # Use the "max" strategy for more comprehensive results
        }
    }
)
print(completion.choices[0].message.content)
Sample response
Based on the information from the knowledge base, Alibaba released the following models in September 2025:

1. **Qwen3-Max-Preview**:
   - Release Date: September 5, 2025.
   - Features: This is the first model in the Qwen series with over **1 trillion** parameters, marking a major breakthrough for Chinese AI technology in the field of ultra-large-scale models.
   - Other Functions: Supports a context window of up to 256K tokens and covers over 100 languages.

2. **Qwen3-Next**:
   - Release Date: September 12, 2025.
   - Architectural Features: Adopts a **high-sparsity Mixture-of-Experts (MoE) architecture**, with a total of 80 billion (80B) parameters, but activates only 3 billion parameters for each inference, significantly reducing inference cost.
   - Performance: Performance is comparable to the 235-billion-parameter Qwen3 flagship model, while training cost is reduced by over 90% compared to the previous dense model (Qwen3-32B).
   - Technical Innovations: Introduces a hybrid attention mechanism and a multi-token prediction mechanism, significantly improving long-text processing efficiency and inference speed (in 32K+ context scenarios, the speed is more than 10 times that of Qwen3-32B).

3. **Qwen3-Next-80B-A3B Series Models**:
   - Developed based on the Qwen3-Next architecture and open-sourced concurrently.
   - Features: Supports an ultra-long context of millions of tokens, suitable for complex tasks and large-scale data processing.

Summary:
- **Qwen3-Max-Preview** is an ultra-large-scale model focused on achieving a new milestone in parameter count.
- **Qwen3-Next** and its series of models (such as Qwen3-Next-80B-A3B) achieve a better balance between performance, efficiency, and cost through architectural innovation.
By default, the model decides whether to perform a web search. For use cases that rely on real-time information, you can set the forced_search parameter to true to force a web search. Valid values for forced_search:
  • true: Forces a web search.
  • false (default): The model decides whether to perform a web search.
  • OpenAI compatible
  • DashScope
  • Python
  • Node.js
  • Curl
For the Python SDK, pass enable_search in extra_body. For the Node.js SDK, pass it as a top-level parameter.
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following configuration is for the China (Beijing) region. Replace {WorkspaceId} with your workspace ID. Configuration varies by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-plus",
    messages=[
        {"role": "user", "content": "What's the weather in Hangzhou tomorrow?"},
    ],
    extra_body={
        "enable_search": True,
        "search_options": {
            "forced_search": True  # Force web search
        }
    }
)
print(completion.choices[0].message.content)
Sample response
According to the available data, the weather forecast for Hangzhou on September 17, 2025 (tomorrow) is as follows:

- **Weather conditions**: Partly cloudy to clear, with a chance of light rain in some areas.
- **Temperature**: Daytime high of about 30°C to 34°C, nighttime low of about 24°C to 26°C.
- **Wind**: Light winds, generally from the east, southeast, or west, with speeds less than level 3.
- **Humidity**: Relative humidity of about 77%.
- **Air quality**: Good, with an air quality index of about 34 to 38.
- **Clothing suggestion**: We recommend wearing cool and breathable clothing, such as cotton or linen shirts, light long skirts, or thin T-shirts.

In addition, a cold front will arrive in Zhejiang tomorrow afternoon and evening, gradually bringing cooler temperatures, but the high temperatures will persist until the afternoon. Starting from the 18th, the high temperatures across the province will completely subside.

Please pay attention to the weather changes and adjust your travel and clothing plans accordingly.

Source citations

You can configure web search to include source links and citation markers in responses to make information easier to trace.
  1. Return sources: Set enable_source: true. The search_info field in the response will then contain a list of search results.
  2. Enable citation markers: When enable_source is set to true, set enable_citation: true to include citation markers, such as [1], in the response.
  3. Set the citation style: Use the citation_format parameter. Available options include:
    • "[<number>]" (default): The style is [1].
    • "[ref_<number>]": The style is [ref_1].
The enable_source, enable_citation, and citation_format parameters above are available for DashScope API calls only.
Models such as glm-5.2 and kimi-k3 support only the web search feature of the Responses API. With the Responses API, search sources are returned automatically in the response (see Get search sources), but the enable_citation citation markers are not supported (no [1] markers are inserted into the response content).
  • Python
  • Java
  • curl
import os
import dashscope

# The following configuration is for the China (Beijing) region. Replace {WorkspaceId} with your Workspace ID. Configurations vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
response = dashscope.Generation.call(
    api_key=os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY"),
    model="qwen-plus",
    messages=[{"role": "user", "content": "What is the weather in Hangzhou tomorrow?"}],
    enable_search=True,
    search_options={
        "enable_source": True,       # Required to use citation markers.
        "enable_citation": True,     # Enables citation markers.
        "citation_format": "[ref_<number>]", # Sets the citation style.
    },
    result_format="message"
)

print("="*20 + "Search Results" + "="*20)
for web in response.output.search_info["search_results"]:
    print(f"[{web['index']}]: [{web['title']}]({web['url']})")
print("="*20 + "Response Content" + "="*20)
print(response.output.choices[0].message.content)
Sample response
====================Search Results====================
[1]: [Dropping nearly 10°C! Confirmed: cold air is about to arrive, and it's strong](https://cj.sina.com.cn/articles/view/1665450974/6344c3de01901avjw)
[2]: [Dropping nearly 10°C! Confirmed: cold air is about to arrive, and it's strong](https://hznews.hangzhou.com.cn/chengshi/content/2025-09/15/content_9083259.htm)
[3]: [Hangzhou Weather Query for September 2025](https://www.ip.cn/tianqi/zhejiang/hangzhou/202509.html)
[4]: [40-Day Weather Forecast](http://uc.src.weather.com.cn/mweather40d/index.shtml?10121010103A)
[5]: [Hangzhou Weather Forecast for September 18, 2025](https://tianqi.eastday.com/tianqi/hangzhou/20250918.html)
[6]: [Hangzhou Weather Query for September 2024](https://www.ip.cn/tianqi/zhejiang/hangzhou/202409.html)
[7]: [The scent of autumn is in the air; the long-awaited first fragrance of osmanthus has finally arrived in Hangzhou](https://baijiahao.baidu.com/s?id=1843471369098538519&wfr=spider&for=pc)
[8]: [Yuhang District Historical Weather Records for September 2024](https://www.ip.cn/tianqi/zhejiang/hangzhou/yuhang/202409.html)
====================Response Content====================
According to the latest weather information, the weather in Hangzhou tomorrow (September 18, 2025) is expected to be overcast to partly cloudy, with a high of 28°C and a low of 24°C. The wind will be light, coming from the northeast at about level 2. Additionally, air humidity will be relatively moderate, UV intensity will be low, and the air quality will be good, making it suitable for outdoor activities. However, it is advisable to check the latest weather forecast for the most accurate information[ref_5].
Queries in vertical domains such as weather and stocks require high data accuracy, and general web search results may not be precise enough. When domain-specific search is enabled, the model prioritizes vertical data sources to return more accurate results. Set enable_search_extension to true to enable this feature. Valid values:
  • true: Enable.
  • false (default): Disable.
Supported domains:

Domain

Description

Sample query

Exchange rate

Provides the latest exchange rates between multiple currencies and supports standard currency codes.

What is the exchange rate between CNY and USD?

Weather

Provides real-time, future, and historical weather data.

Hangzhou weather

Stocks

Supports A-shares, Hong Kong stocks, and US stocks. You can retrieve real-time stock prices, previous trading day closing prices, historical trends, 30-day closing prices, and prices for stock tickers or indices.

What was the closing price of the Shanghai Composite Index yesterday?

Gas price

Provides daily updates on gasoline and diesel prices in various regions.

What is the gas price in Hangzhou?

Perpetual calendar

For a specified date, provides information including the lunar calendar, solar terms, holidays, and traditional almanac guidance on auspicious and inauspicious activities.

What is today's lunar date?

Gold price

Provides real-time quotes, including the latest price, opening price, high, and low.

What is the price of gold now?

Silver price

Provides real-time quotes, including the latest price, opening price, high, and low.

What is the price of silver now?

Lottery

Supports mainstream lottery types such as Double Color Ball, Super Lotto, Permutation 3, Permutation 5, 7-Star Lottery, Happy 8, and 3D.

What are the latest Double Color Ball results?

TV series

Provides information on TV series from mainstream platforms.

What TV series are trending?

Movies

Provides the latest information from mainstream movie platforms.

What movies have been released recently?

License plate restrictions

Checks the driving restrictions for the current day based on a license plate number.

ZheAxxxxxx, are there driving restrictions in Hangzhou today?

Soccer matches

Provides schedules and standings for leagues such as the Premier League, La Liga, Bundesliga, Serie A, Ligue 1, Chinese Super League, and Scottish Premiership.

Which team is currently ranked first in the Premier League?

  • OpenAI
  • DashScope
  • Python
  • Node.js
  • curl
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following configuration is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. Configurations vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-plus",
    messages=[
        {"role": "user", "content": "What is the stock price of Alibaba?"},
    ],
    extra_body={
        "enable_search": True,
        "search_options": {"enable_search_extension": True},
    }
)
print(completion.choices[0].message.content)
Sample response
As of September 15, 2025, the closing price of Alibaba's US stock was 155.060 USD. According to real-time information on September 16, the price was 158.040 USD, an increase of about 1.92% from the previous day. The stock price has risen by 17.07% compared to last month.

We recommend checking professional stock market platforms or financial websites for more specific real-time stock price information.

Search freshness

For time-sensitive queries, such as recent news or updates, use the freshness parameter to restrict the search time range and filter out outdated results. Valid values:
  • 7: Retrieves content from the last 7 days.
  • 30: Retrieves content from the last 30 days.
  • 180: Retrieves content from the last 180 days.
  • 365: Retrieves content from the last 365 days.
  • Not set (default): The search is not restricted by time.
Requirements:
  • Effective only for search_strategy: turbo.
  • Supported models: qwen-plus, qwen-flash, qwen-plus-character, qwen-flash-character, qwen-flash-character-2026-02-26
  • OpenAI compatible
  • DashScope
Python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following configuration is for the China (Beijing) region. Replace {WorkspaceId} with your actual Workspace ID. Configurations vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-plus",
    messages=[
        {"role": "user", "content": "What is the major news in the AI field recently?"},
    ],
    extra_body={
        "enable_search": True,
        "search_options": {
            "search_strategy": "turbo",
            "freshness": 7  # Search within the last 7 days.
        }
    }
)
print(completion.choices[0].message.content)

Restrict search sites

To restrict a search to specific websites, such as official sites or trusted media sources, use the assigned_site_list parameter. When enabled, the search is limited to the sites you specify. Limitations:
  • This setting applies only when search_strategy is set to turbo.
  • Supported models:
    • Qwen Plus Series: qwen-plus
    • Qwen Flash Series: qwen-flash
    • Character model: qwen-plus-character, qwen-flash-character, qwen-flash-character-2026-02-26
  • You can specify up to 25 sites.
The assigned_site_list parameter defaults to [], which means the search is unrestricted.
If no relevant content is found on the specified sites, the search may return empty results. In this case, the model will answer using its own knowledge.
  • OpenAI compatible
  • DashScope
Python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # This example is for the China (Beijing) region. Replace {WorkspaceId} with your Workspace ID. Configurations vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-plus",
    messages=[
        {"role": "user", "content": "What is the trending news in Beijing?"},
    ],
    extra_body={
        "enable_search": True,
        "search_options": {
            "search_strategy": "turbo",
            "assigned_site_list": ["baidu.com", "sina.cn"]  # Search only the specified sites
        }
    }
)
print(completion.choices[0].message.content)

Control search scope with natural language

Use the prompt_intervene parameter to define the search scope with natural language. This lets you target content about a specific topic or from a particular region. Supported models: qwen-plus, qwen-flash, qwen-plus-character, qwen-flash-character, qwen-flash-character-2026-02-26
  • OpenAI compatible
  • DashScope
Python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # This configuration is for the China (Beijing) region. Replace {WorkspaceId} with your Workspace ID. Configuration is region-specific.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-plus",
    messages=[
        {"role": "user", "content": "Current state of intelligent technology development"},
    ],
    extra_body={
        "enable_search": True,
        "search_options": {
            "search_strategy": "turbo",
            "intention_options": {
                "prompt_intervene": "Retrieve only AI technology-related content"
            }
        }
    }
)
print(completion.choices[0].message.content)

Early return of search sources

In streaming mode, a delay of 0.5 seconds or more can occur between when search results are ready and when the first data packet is sent. You can reduce the time to first token (TTFT) by returning search sources immediately after the search completes. To enable this feature, set prepend_search_result to true. Valid values:
  • true: The first data packet contains only the search sources. Subsequent data packets contain the model response.
  • false (default): The first data packet contains both the search sources and the initial part of the model response.
This feature is not supported for OpenAI compatibility or the DashScope Java SDK.
  • Python
  • curl
import os
import dashscope

# The following configuration is for the China (Beijing) region. Replace {WorkspaceId} with your actual Workspace ID. Configurations vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
responses = dashscope.Generation.call(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen-plus",
    messages=[{"role": "user", "content": "What is the weather in Hangzhou tomorrow?"}],
    enable_search=True,
    search_options={
        "enable_source": True,
        "prepend_search_result": True,  # The first packet returns only search sources
    },
    result_format="message",
    stream=True,
    incremental_output=True
)

first_chunk = True
for resp in responses:
    if first_chunk:
        search_info = resp.output.get("search_info", {})
        if search_info:
            print("=" * 20 + f"Found {len(search_info['search_results'])} pages" + "=" * 20)
            for web in search_info["search_results"]:
                print(f"[{web['index']}]: [{web['title']}]({web['url']})")
            first_chunk = False
            print("=" * 20 + "Response content" + "=" * 20)

    content = resp.output.choices[0].message.content
    print(content, end='')
Sample response
====================Found 8 pages====================
[1]: [Dropping nearly 10℃! Just confirmed: cold air is about to arrive, and it's strong](https://cj.sina.com.cn/articles/view/1665450974/6344c3de01901avjw)
[2]: [Dropping nearly 10℃! Just confirmed: cold air is about to arrive, and it's strong](https://hznews.hangzhou.com.cn/chengshi/content/2025-09/15/content_9083259.htm)
[3]: [Hangzhou Weather Query for September 2025](https://www.ip.cn/tianqi/zhejiang/hangzhou/202509.html)
[4]: [40-Day Weather Forecast](http://uc.src.weather.com.cn/mweather40d/index.shtml?10121010103A)
[5]: [Hangzhou Weather Forecast for September 18, 2025](https://tianqi.eastday.com/tianqi/hangzhou/20250918.html)
[6]: [Hangzhou Weather Query for September 2024](https://www.ip.cn/tianqi/zhejiang/hangzhou/202409.html)
[7]: [The scent of autumn is in the air, the long-awaited first fragrance of osmanthus has finally arrived in Hangzhou](https://baijiahao.baidu.com/s?id=1843471369098538519&wfr=spider&for=pc)
[8]: [Yuhang District Historical Weather Records for September 2024](https://www.ip.cn/tianqi/zhejiang/hangzhou/yuhang/202409.html)
====================Response content====================
According to the weather information for September 17, 2025, the weather in Hangzhou tomorrow (September 18) is as follows:

Light rain turning to overcast, with lower temperatures.
*   Weather conditions: Light rain during the day, then turning overcast.
*   Temperature: High of about 26°C, low of about 22°C.
*   Wind: Northeast wind during the day.

Weather characteristics:
Affected by cold air, Hangzhou will experience a significant cooling period. Compared to the recent high temperatures of over 35°C, the high temperature tomorrow will drop by nearly 10°C, feeling much cooler. After this temperature drop, high temperatures are not expected to return until the 25th.

Mixed text and image output

Set enable_text_image_mixed: true to enable mixed text and image output. With this feature enabled, the model embeds relevant images in its responses. Example:
image.png
Supported models: qwen-max, qwen-plus-latest, qwen-flash This parameter is independent of enable_search and does not need to be enabled with it. Image format: The model returns images embedded in the response as HTML <img> tags. To display them on the front end, you can render the HTML directly or convert it to Markdown.
<!-- Example of the image format returned by the model -->
<p align="center">
<img src="https://example.com/image.jpg" alt="Image description" width="400" height="auto">
</p>
The following examples show how to enable mixed text and image output.
  • OpenAI compatible
  • DashScope
Python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Configuration for the China (Beijing) region. Replace {WorkspaceId} with your workspace ID. Endpoints vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-plus-latest",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Tell me about West Lake in Hangzhou"},
    ],
    # Enable mixed text and image output
    extra_body={"enable_text_image_mixed": True}
)
print(completion.choices[0].message.content)

Web search with thinking models

In the previous examples, the model provides a direct response after retrieving search results. This approach is suitable for simple, time-sensitive, and fact-based queries, such as "What is the weather in Hangzhou tomorrow?". However, for complex tasks like industry trend analysis, multi-source information synthesis, or report generation, this approach often falls short. For these scenarios, you can use a thinking model. After retrieving content, a thinking model first reasons over the information before generating a response, significantly improving the answer quality for complex tasks. The thinking process is visible, so you can understand how the response is derived from the retrieved information. The following models support both web search and deep thinking capabilities:
  • Qwen
    • Qwen-Plus: qwen-plus, qwen-plus-latest, and snapshot versions from qwen-plus-2025-07-14 or later
    • Qwen-Flash: qwen-flash, and snapshot versions from qwen-flash-2025-07-28 or later
  • DeepSeek: deepseek-v4-pro
For more details on thinking models, see Deep Thinking.
  • OpenAI compatible
  • DashScope
  • Python
  • Node.js
  • HTTP

Sample code

from openai import OpenAI
import os

# Initialize the OpenAI client
client = OpenAI(
    # Reads the API key from the DASHSCOPE_API_KEY environment variable. Alternatively, you can set it directly: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following configuration is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. Configurations vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

reasoning_content = ""  # Stores the complete thinking process
answer_content = ""  # Stores the complete response
is_answering = False  # Flag to check if the thinking process has ended and the response has begun

# Create a chat completion request
completion = client.chat.completions.create(
    # This example uses qwen-plus. You can replace it with any other supported thinking model.
    model="qwen-plus",
    messages=[{"role": "user", "content": "Based on recent AI news, predict the development trends of AI."}],
    extra_body={
        "enable_thinking": True,
        "enable_search": True,  # Parameter to enable web search
        "search_options": {
            "forced_search": True,  # Parameter to force web search
            "search_strategy": "max"
        },
    },
    stream=True,
    stream_options={"include_usage": True}
)

print("\n" + "=" * 20 + "Thinking Process" + "=" * 20 + "\n")

for chunk in completion:
    # If chunk.choices is empty, print the usage
    if not chunk.choices:
        print("\n" + "=" * 20 + "Usage" + "=" * 20)
        print(chunk.usage)
    else:
        delta = chunk.choices[0].delta
        # Print the thinking process
        if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
            print(delta.reasoning_content, end="", flush=True)
            reasoning_content += delta.reasoning_content
        else:
            # Start printing the response
            if delta.content != "" and not is_answering:
                print("\n" + "=" * 20 + "Complete Response" + "=" * 20 + "\n")
                is_answering = True
            # Print the response stream
            if delta.content:
                print(delta.content, end="", flush=True)
                answer_content += delta.content

# To print the complete thinking process and response, uncomment the following lines
# print("=" * 20 + "Complete Thinking Process" + "=" * 20 + "\n")
# print(reasoning_content)
# print("=" * 20 + "Complete Response" + "=" * 20 + "\n")
# print(answer_content)

Response

====================Thinking Process====================

To predict AI development trends, I need to analyze recent AI news from the knowledge base. First, I will identify key news items and related trends.

From the knowledge base, I can see several news items related to AI:
...
Based on this information, I will provide a predictive answer about AI development trends.
====================Complete Response====================

# AI Development Trend Prediction: A Look at the Future from Recent News
Based on an analysis of recent AI news, I believe AI development will show the following important trends:
...
AI development is shifting from being "technology-driven" to "demand-driven," with a greater focus on solving practical problems and improving user experience. As technology matures and application scenarios expand, AI will become more deeply integrated into daily life. However, humanized and emotional design will become a key differentiating factor. As emphasized in the "Silver Hair + AI" report, technology will ultimately serve people, not replace the emotional connections between them.
The core of future AI development will be to maintain and enhance the emotional bonds between people while improving efficiency, achieving a harmonious coexistence of technology and humanity.
====================Usage====================
CompletionUsage(completion_tokens=1683, prompt_tokens=2688, total_tokens=4371, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=None, audio_tokens=None, reasoning_tokens=1022, rejected_prediction_tokens=None), prompt_tokens_details=PromptTokensDetails(audio_tokens=None, cached_tokens=0))

Web search with Responses API

You can enable web search by adding the web_search tool to the tools array of the tools parameter.
This feature is supported only for the following models: the Qwen3.8 Max, Flash, and open-source series, and qwen3.8-omni-flash; the Qwen3.7 and Qwen3.5 series models (including open-source models, but not Omni models), the Qwen3.6-Plus and Qwen3.6-Flash series, and qwen3.6-35b-a3b; deepseek-v4-flash-0731, deepseek-v4-pro, deepseek-v4-pro-0813; glm-5.2; and kimi-k3.
qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, and qwen3.8-27b do not support the agent value of search_strategy on the Chat Completions API. To use agent-style multi-turn retrieval with Qwen3.8, use the Responses API web_search tool documented in this section — the model can autonomously call web_search multiple times within a single response.
The Responses API does not use the search_strategy parameter. Whether web search is triggered — and whether the model performs multiple search rounds — is determined solely by attaching the web_search tool and by the model's own decisions. A search_options.search_strategy value passed to the Responses API is silently ignored and does not trigger a search.
For models that support these tools, enable web_search, web_extractor, and code_interpreter together. For qwen3.8-omni-flash, the only supported built-in tool is web_search.
For usage instructions, code examples, and migration guides for the Responses API, see OpenAI-compatible - Responses.
from openai import OpenAI
import os

client = OpenAI(
    # If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # This configuration is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. Configurations vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
)

response = client.responses.create(
    model="qwen3.8-max",
    input="What is the weather in Hangzhou tomorrow?",
    tools=[
        {"type": "web_search"},
        {"type": "web_extractor"},
        {"type": "code_interpreter"}
    ],
    extra_body={"enable_thinking": True}
)

print("="*20 + "Response content" + "="*20)
print(response.output_text)

print("="*20 + "Tool call trace" + "="*20)
# Agent-style multi-turn retrieval: the model may call web_search multiple times
for item in response.output:
    t = getattr(item, "type", None)
    if t == "web_search_call":
        q = getattr(getattr(item, "action", None), "query", "")
        print(f"[web_search_call] query={q}")
    elif t == "web_extractor_call":
        print(f"[web_extractor_call]")

print("="*20 + "Source citations" + "="*20)
for item in response.output:
    if getattr(item, "type", None) == "message":
        for part in item.content:
            for ann in getattr(part, "annotations", []) or []:
                if getattr(ann, "type", None) == "url_citation":
                    print(f"- {ann.title}: {ann.url}")

print("="*20 + "Tool call count" + "="*20)
usage = response.usage
if hasattr(usage, "x_tools") and usage.x_tools:
    print(f"Web search count: {usage.x_tools.get('web_search', {}).get('count', 0)}")
For a query such as "What is the weather in Hangzhou tomorrow?", the model performs multiple retrieval rounds within a single response. The output array contains multiple web_search_call (and optionally web_extractor_call) items interleaved with reasoning and the final message:
{
    "output": [
        { "type": "reasoning", "..." : "..." },
        { "type": "web_search_call", "action": { "query": "Hangzhou weather tomorrow" } },
        { "type": "reasoning", "..." : "..." },
        { "type": "web_extractor_call", "..." : "..." },
        { "type": "web_search_call", "action": { "query": "Hangzhou 15-day forecast" } },
        { "type": "reasoning", "..." : "..." },
        { "type": "message", "content": [ /* final answer with url_citation annotations */ ] }
    ],
    "usage": {
        "x_tools": { "web_search": { "count": 2 } }
    }
}
The presence of multiple web_search_call items and x_tools.web_search.count > 1 confirms agent-style multi-turn retrieval — the model decided on its own to refine the query and search again.

Get search sources

After a web search runs, the search sources are returned in the response. They appear in the element whose type is web_search_call within the output array, and its action.sources field is the list of source links. You can extract them from the response in the example above as follows:
The Responses API does not support the enable_source, enable_citation, or citation_format parameters, and does not insert [1] citation markers into the response content. To use citation markers, use the DashScope API.
# Extract search sources from the response above
print("=" * 20 + "Search sources" + "=" * 20)
for item in response.output:
    if item.type == "web_search_call":
        for i, source in enumerate(item.action.sources, start=1):
            print(f"[{i}] {source.url}")

Billing

The web search described in this topic refers to the model's built-in web search feature, which is billed as described below and does not include a free call quota. It is separate from the Web Search MCP service offered in the Model Studio MCP marketplace, and the two are billed independently: the Web Search MCP service provides a free quota of 2,000 calls for all users, after which it is billed at CNY 29 per 1,000 calls. For more information, see Connect Harness tools.
Charges for web search consist of two components:
  • model call fees: The web search feature appends retrieved web content to the prompt, increasing the number of input tokens. These tokens are billed at the model's standard rate. For pricing details, see the Model Studio console. When you use the Responses API or the Anthropic-compatible method, the web search tool is billed at the same rate as the agent policy.
  • search policy fees:
    • turbo and max policies: Standard billing applies starting from 00:00 on February 27, 2026. The fee is CNY 3 per 1,000 calls for the turbo policy and CNY 4 per 1,000 calls for the max policy. This pricing applies only to the China (Beijing) region.
    • agent policy:
      • The fee per 1,000 calls is as follows:
        • For the China (Beijing), US (Virginia), China (Hong Kong), Japan (Tokyo), and Germany (Frankfurt) regions: CNY 4.
        • For the Singapore region: CNY 73.392381.
    • agent_max policy (Limited-time offer): This policy covers both the web search and the web extractor tool.
      • Fee per 1,000 calls for the web search tool:
        • For the China (Beijing), US (Virginia), China (Hong Kong), Japan (Tokyo), and Germany (Frankfurt) regions: CNY 4.
        • For the Singapore region: CNY 73.392381.
      • The web extractor tool is free for a limited time.

Rate limit

The rate limit for web search is 15 requests per second (RPS) per Alibaba Cloud account. This limit applies to the total requests from all API keys under the account, regardless of the model. If the limit is exceeded, the API call will not trigger the search step and will not return an error.

FAQ

Q: Why doesn't the model perform a web search after I enable it?

A: This can happen for the following reasons:
  • The model determines a search is unnecessary: The model may decide that the query can be answered using its internal knowledge and does not require real-time information. To force a web search, set forced_search: true in the search_options parameter.
  • The rate limit is exceeded: Your account's request frequency has surpassed 15 RPS. The API does not return an error but silently skips the web search step. To resolve this, reduce your request frequency.
  • Unsupported model: The model you are using does not support web search. See Supported models.

Q: How can I determine if a search was performed?

A: The method depends on the API you are using:
  • DashScope
    • If a search was performed, the response includes a search_info field, and the usage object contains a plugins field.
    • If a search is not performed, the response does not contain the search_info field, and the usage object does not contain the plugins field.
  • OpenAI-compatible The response provides no explicit indicator. You can infer that a search occurred by comparing the input token count in the usage object. A count significantly higher than your original prompt's token count suggests a web search was performed. For example, a query like "What's the weather in Hangzhou?" might use 10 input tokens without a search, but 1,953 input tokens with a search.

Q: Why does web search fail for English queries?

A: We are continuously optimizing the search-triggering logic for English queries. For now, we recommend either asking questions in Chinese or forcing a web search when using English input.

Q: Is my original prompt sent to external search engines?

A: No. Your original prompt is not sent directly to a search engine. Instead, the system analyzes your query's intent, applies multiple layers of data masking, and extracts only key, non-sensitive information fragments for retrieval. The system rewrites the query multiple times before sending it to the search engine to ensure no sensitive data is exposed in plaintext. Alibaba Cloud uses data encryption and privacy protection measures to ensure security. For details, see the Service Agreement.

Q: Can my original text be reconstructed from the search vectors?

A: No. A vector is a high-dimensional mathematical representation of data and is not human-readable. It is computationally infeasible for an external system to reverse-engineer the original text from its vector. Furthermore, the vector matching process occurs within a secure, trusted environment and is never exposed to public search engines. A: The system first determines whether a search is necessary. It typically triggers a search for time-sensitive or encyclopedic queries, as these are less likely to contain confidential information. Conversely, it generally does not perform a search for queries unrelated to current events. The system rewrites the query multiple times before performing any search.

Q: Why does the model reply "I cannot answer this question" or fail to respond when web search is enabled?

A: Web search results may contain regulated content that triggers the content moderation rules, causing the API to return a DataInspectionFailed error (HTTP 400) and the model to reply "Sorry, I cannot answer this question." To troubleshoot, disable web search and resend the same query. If the model responds normally, the search results triggered the interception. This interception is non-deterministic: it depends on the specific content returned by the search, and not all queries on sensitive topics trigger it.

Q: Web search returns a stock price on a non-trading day. How do I handle this?

A: Use qwen3.7-max or a later model. qwen3.7-max can reason about dates: it recognizes a non-trading day and reports that no closing price is available. qwen-max lacks date reasoning and returns the stock price retrieved from search results. Neither enable_search_extension nor prompt_intervene resolves this issue. A: Kimi models (kimi-k3) support web search only through the web_search tool of the Responses API; the enable_search parameter is not supported. For more flexible retrieval, you can also create an agent application in the Model Studio console and add a web search MCP tool, such as bailian_web_search, under Tools > MCP services. The Web Search MCP service and the built-in web search are two independent features that are billed separately. For more information, see Connect Harness tools.

Error messages

To troubleshoot errors, see Error codes.
Token Plan
Model Playground
Fine-tuning
Model Compression
Statistics and Monitoring
Support