SDKs

Microsoft Web IQ SDK 为 Auto、Web、新闻、视频、图像和位置搜索以及浏览提供强类型客户端库。 选择此页面顶部的语言,同时切换所有安装命令和示例。

这些示例使用公开发布的 1.2.1 SDK 版本进行自动搜索,其中包含类型化的证据和结果范围的引文。 在运行之前升级较早版本的 SDK。

Property Python TypeScript Rust Java .NET
Package webiq @microsoft/webiq webiq com.microsoft.webiq:webiq Microsoft.WebIQ
使用的版本 1.2.1 1.2.1 1.2.1 1.2.1 1.2.1
Runtime Python 3.11+ Node.js 22.13+ (22.x) 或 24+ Rust 1.88+ Java 11+ .NET 8+
License MIT MIT MIT MIT MIT

需要 Web IQ API 密钥或有权访问 Web IQ 的Microsoft Entra标识。 请参阅身份验证。

Installation

python -m pip install webiq==1.2.1
npm install @microsoft/webiq@1.2.1

将 SDK 和 Tokio 运行时添加到项目:

cargo add webiq@1.2.1
cargo add tokio --features macros,rt-multi-thread

将 Maven Central 依赖项添加到项目的 pom.xml 中。 将项目配置为针对 Java 11 或更高版本进行编译。

<dependency>
    <groupId>com.microsoft.webiq</groupId>
    <artifactId>webiq</artifactId>
    <version>1.2.1</version>
</dependency>

对于 Gradle:

implementation "com.microsoft.webiq:webiq:1.2.1"

这些示例使用公共 Microsoft.WebIQ 1.2.1 包,需要.NET 8 或更高版本。 在.NET控制台项目中运行以下命令:

dotnet add package Microsoft.WebIQ --version 1.2.1

快速入门

在运行示例之前,将 WEBIQ_API_KEY 环境变量设置为 API 密钥。 不要在源代码中放置 API 密钥。

该示例以 advanced 模式调用 Auto,每次尝试超时时间为 60 秒,使用支持引文打印每个证据结果,然后调用 Web、新闻、视频、图像和 Places Search,并使用 Browse 检索页面。 Auto 返回证据,而不是生成的最终答案。 请参阅 Auto reference,了解证据类型和请求选项。

Web、新闻和浏览请求段落,这是用于 grounding 的推荐格式。 浏览还需要选择最多 1000 个字符的非空选择内容。query 有关完整文档格式,请参阅 内容格式。

import os
from webiq import WebIQClient
from webiq.types import BrowseContentFormat, ContentFormat, AutoMode

with WebIQClient(api_key=os.environ["WEBIQ_API_KEY"]) as client:
    evidence = client.auto.search(
        "What are the latest developments in retrieval-augmented generation?",
        mode=AutoMode.advanced,
        max_response_length=30000,
        max_citations=5,
        timeout=60.0,
    )
    for result in evidence.results or []:
        print(result.evidence)
        for citation in result.citations or []:
            print(citation.title, citation.url)

    web = client.web.search(
        "Microsoft Web IQ",
        max_results=5,
        content_format=ContentFormat.passage,
    )
    for result in web.webResults or []:
        print(result.title, result.url)

    news = client.news.search(
        "technology",
        max_results=5,
        content_format=ContentFormat.passage,
    )
    for item in news.newsResults or []:
        print(item.title, item.source)

    videos = client.videos.search("machine learning tutorial", max_results=5)
    for video in videos.videoResults or []:
        print(video.title, video.length)

    images = client.images.search("golden gate bridge", max_results=5)
    for image in images.imageResults or []:
        print(image.title, image.url)

    places = client.places.search(
        "coffee in Seattle",
        max_results=5,
        language="en",
        region="US",
        location="lat:47.6062;long:-122.3321",
    )
    for place in places.placeResults or []:
        print(place.name, place.businessUrl)

    page = client.browse.fetch(
        "https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
        query="How fast is Web IQ",
        content_format=BrowseContentFormat.passage,
        max_length=3000,
        live_crawl="fallback",
    )
    print(page.content)
import { WebIQClient, BrowseContentFormat, ContentFormat, LiveCrawlMode, AutoMode } from '@microsoft/webiq';

async function main() {
  const apiKey = process.env.WEBIQ_API_KEY;
  if (!apiKey) throw new Error('Set WEBIQ_API_KEY before running this example.');

  const client = new WebIQClient({ apiKey });
  try {
    const evidence = await client.auto.search(
      'What are the latest developments in retrieval-augmented generation?',
      { mode: AutoMode.ADVANCED, maxResponseLength: 30000, maxCitations: 5, timeout: 60_000 },
    );
    for (const result of evidence.results ?? []) {
      console.log(result.evidence);
      for (const citation of result.citations ?? []) console.log(citation.title, citation.url);
    }

    const web = await client.web.search('Microsoft Web IQ', {
      maxResults: 5,
      contentFormat: ContentFormat.PASSAGE,
    });
    for (const result of web.webResults ?? []) console.log(result.title, result.url);

    const news = await client.news.search('technology', {
      maxResults: 5,
      contentFormat: ContentFormat.PASSAGE,
    });
    for (const item of news.newsResults ?? []) console.log(item.title, item.source);

    const videos = await client.videos.search('machine learning tutorial', { maxResults: 5 });
    for (const video of videos.videoResults ?? []) console.log(video.title, video.length);

    const images = await client.images.search('golden gate bridge', { maxResults: 5 });
    for (const image of images.imageResults ?? []) console.log(image.title, image.url);

    const places = await client.places.search('coffee in Seattle', {
      maxResults: 5,
      language: 'en',
      region: 'US',
      location: 'lat:47.6062;long:-122.3321',
    });
    for (const place of places.placeResults ?? []) console.log(place.name, place.businessUrl);

    const page = await client.browse.fetch('https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283', {
      query: 'How fast is Web IQ',
      contentFormat: BrowseContentFormat.PASSAGE,
      maxLength: 3000,
      liveCrawl: LiveCrawlMode.FALLBACK,
    });
    console.log(page.content);
  } finally {
    await client.close();
  }
}

main().catch(console.error);
use webiq::{
    AutoSearchOptions, BrowseContentFormat, BrowseOptions, ContentFormat, ImageSearchOptions,
    LiveCrawlMode, NewsSearchOptions, PlacesSearchOptions, VideoSearchOptions,
    AutoMode, WebIqClient, WebSearchOptions,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = WebIqClient::new(std::env::var("WEBIQ_API_KEY")?)?;

    let evidence = client.auto().search(
        "What are the latest developments in retrieval-augmented generation?",
        AutoSearchOptions::new()
            .mode(AutoMode::Advanced)
            .max_response_length(30000)
            .max_citations(5)
            .timeout(std::time::Duration::from_secs(60)),
    ).await?;
    for result in evidence.results.unwrap_or_default() {
        println!("{:?}", result.evidence);
        for citation in result.citations.unwrap_or_default() {
            println!("{:?} {:?}", citation.title, citation.url);
        }
    }

    let web = client.web().search(
        "Microsoft Web IQ",
        WebSearchOptions::new()
            .max_results(5)
            .content_format(ContentFormat::Passage),
    ).await?;
    for result in web.web_results.unwrap_or_default() {
        println!("{:?} {:?}", result.title, result.url);
    }

    let news = client.news().search(
        "technology",
        NewsSearchOptions::new()
            .max_results(5)
            .content_format(ContentFormat::Passage),
    ).await?;
    for item in news.news_results.unwrap_or_default() {
        println!("{:?} {:?}", item.title, item.source);
    }

    let videos = client.videos().search(
        "machine learning tutorial",
        VideoSearchOptions::new().max_results(5),
    ).await?;
    for video in videos.video_results.unwrap_or_default() {
        println!("{:?} {:?}", video.title, video.length);
    }

    let images = client.images().search(
        "golden gate bridge",
        ImageSearchOptions::new().max_results(5),
    ).await?;
    for image in images.image_results.unwrap_or_default() {
        println!("{:?} {:?}", image.title, image.url);
    }

    let places = client.places().search(
        "coffee in Seattle",
        PlacesSearchOptions::new()
            .max_results(5)
            .language("en")
            .region("US")
            .location("lat:47.6062;long:-122.3321"),
    ).await?;
    for place in places.place_results.unwrap_or_default() {
        println!("{:?} {:?}", place.name, place.business_url);
    }

    let page = client.browse().fetch(
        "https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
        BrowseOptions::new()
            .query("How fast is Web IQ")
            .content_format(BrowseContentFormat::Passage)
            .max_length(3000)
            .live_crawl(LiveCrawlMode::Fallback),
    ).await?;
    println!("{}", page.content.unwrap_or_default());

    Ok(())
}

在 Maven 项目中将此示例另存为 src/main/java/WebIqSample.java,并运行 mvn compile exec:java -Dexec.mainClass=WebIqSample。

import com.microsoft.webiq.WebIQClient;
import com.microsoft.webiq.models.*;
import com.microsoft.webiq.resources.*;

public class WebIqSample {
    public static void main(String[] args) {
        try (WebIQClient client = WebIQClient.withApiKey(System.getenv("WEBIQ_API_KEY"))) {
            SearchAutoEvidenceResponse evidence = client.auto.search(
                    "What are the latest developments in retrieval-augmented generation?",
                    AutoSearchOptions.builder().mode(AutoMode.ADVANCED)
                            .maxResponseLength(30000).maxCitations(5)
                            .timeout(java.time.Duration.ofSeconds(60)).build());
            if (evidence.getResults() != null) {
                for (AutoEvidenceResult result : evidence.getResults()) {
                    System.out.println(result.getEvidence());
                    if (result.getCitations() != null) {
                        for (AutoEvidenceCitation citation : result.getCitations()) {
                            System.out.println(citation.getTitle() + " " + citation.getUrl());
                        }
                    }
                }
            }

            WebResponse web = client.web.search("Microsoft Web IQ",
                    WebSearchOptions.builder().maxResults(5)
                            .contentFormat(ContentFormat.PASSAGE).build());
            if (web.getWebResults() != null) {
                for (WebResult result : web.getWebResults()) {
                    System.out.println(result.getTitle() + " " + result.getUrl());
                }
            }

            NewsResponse news = client.news.search("technology",
                    NewsSearchOptions.builder().maxResults(5)
                            .contentFormat(ContentFormat.PASSAGE).build());
            if (news.getNewsResults() != null) {
                for (NewsItem item : news.getNewsResults()) {
                    System.out.println(item.getTitle() + " " + item.getSource());
                }
            }

            VideosResponse videos = client.videos.search("machine learning tutorial",
                    VideosSearchOptions.builder().maxResults(5).build());
            if (videos.getVideoResults() != null) {
                for (VideoItem video : videos.getVideoResults()) {
                    System.out.println(video.getTitle() + " " + video.getLength());
                }
            }

            ImagesResponse images = client.images.search("golden gate bridge",
                    ImagesSearchOptions.builder().maxResults(5).build());
            if (images.getImageResults() != null) {
                for (ImageItem image : images.getImageResults()) {
                    System.out.println(image.getTitle() + " " + image.getUrl());
                }
            }

            PlacesResponse places = client.places.search("coffee in Seattle",
                    PlacesSearchOptions.builder().maxResults(5)
                            .language("en").region("US")
                            .location("lat:47.6062;long:-122.3321").build());
            if (places.getPlaceResults() != null) {
                for (PlaceItem place : places.getPlaceResults()) {
                    System.out.println(place.getName() + " " + place.getBusinessUrl());
                }
            }

            BrowseResponse page = client.browse.fetch("https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
                    BrowseFetchOptions.builder()
                            .query("How fast is Web IQ")
                            .contentFormat(BrowseContentFormat.PASSAGE)
                            .maxLength(3000).liveCrawl(LiveCrawlMode.FALLBACK).build());
            System.out.println(page.getContent());
        }
    }
}
using Microsoft.WebIQ;
using Microsoft.WebIQ.Models;
using System.Text.Json;

string apiKey = Environment.GetEnvironmentVariable("WEBIQ_API_KEY")
    ?? throw new InvalidOperationException("Set WEBIQ_API_KEY before running this example.");
using var client = new WebIQClient(apiKey);

var evidence = await client.Auto.SearchAsync(
    "What are the latest developments in retrieval-augmented generation?",
    request =>
    {
        request.Mode = AutoMode.Advanced;
        request.MaxResponseLength = 30000;
        request.MaxCitations = 5;
    }, timeout: TimeSpan.FromSeconds(60));
foreach (var result in evidence.Results ?? [])
{
    Console.WriteLine(JsonSerializer.Serialize(result.Evidence));
    foreach (var citation in result.Citations ?? [])
        Console.WriteLine($"{citation.Title} {citation.Url}");
}

var web = await client.Web.SearchAsync("Microsoft Web IQ", request =>
{
    request.MaxResults = 5;
    request.ContentFormat = ContentFormat.Passage;
});
foreach (var result in web.WebResults ?? [])
    Console.WriteLine($"{result.Title} {result.Url}");

var news = await client.News.SearchAsync("technology", request =>
{
    request.MaxResults = 5;
    request.ContentFormat = ContentFormat.Passage;
});
foreach (var item in news.NewsResults ?? [])
    Console.WriteLine($"{item.Title} {item.Source}");

var videos = await client.Videos.SearchAsync("machine learning tutorial",
    request => request.MaxResults = 5);
foreach (var video in videos.VideoResults ?? [])
    Console.WriteLine($"{video.Title} {video.Length}");

var images = await client.Images.SearchAsync("golden gate bridge",
    request => request.MaxResults = 5);
foreach (var image in images.ImageResults ?? [])
    Console.WriteLine($"{image.Title} {image.Url}");

var places = await client.Places.SearchAsync("coffee in Seattle", request =>
{
    request.MaxResults = 5;
    request.Language = "en";
    request.Region = "US";
    request.Location = "lat:47.6062;long:-122.3321";
});
foreach (var place in places.PlaceResults ?? [])
    Console.WriteLine($"{place.Name} {place.BusinessUrl}");

var page = await client.Browse.FetchAsync("https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
    request =>
    {
        request.ContentFormat = BrowseContentFormat.Passage;
        request.Query = "How fast is Web IQ";
        request.MaxLength = 3000;
        request.LiveCrawl = LiveCrawlMode.Fallback;
    });
Console.WriteLine(page.Content);

Microsoft Entra ID 身份验证

传递Azure标识凭据,而不是 API 密钥。 对于本地开发,请使用受支持的开发人员工具(例如Azure CLI)登录。 对于Azure托管的应用程序,请使用托管标识或工作负荷标识。 你的标识必须有权访问 Web IQ。

默认的 OAuth 作用域为 https://api.microsoft.ai/.default。

安装可选的身份验证依赖项:

python -m pip install "webiq[entra]==1.2.1"
from azure.identity import DefaultAzureCredential
from webiq import WebIQClient

with DefaultAzureCredential() as credential:
    with WebIQClient(credential=credential) as client:
        response = client.web.search("Microsoft Web IQ")
        print(response.webResults)
npm install "@azure/identity@>=4.13.1"
import { DefaultAzureCredential } from '@azure/identity';
import { WebIQClient } from '@microsoft/webiq';

const client = new WebIQClient({ credential: new DefaultAzureCredential() });
try {
  const response = await client.web.search('Microsoft Web IQ');
  console.log(response.webResults);
} finally {
  await client.close();
}

SDK 中包括 Azure Identity 支持。 SDK 重新导出 azure_identity,因此不需要额外的依赖项。 此示例在 azd auth login 或 az login 之后使用开发人员凭据:

use webiq::{azure_identity::DeveloperToolsCredential, WebIqClient};

let credential = DeveloperToolsCredential::new(None)?;
let client = WebIqClient::builder()
    .credential(credential)
    .build()?;
let response = client.web().search("Microsoft Web IQ", Default::default()).await?;
println!("{:?}", response.web_results);

对于托管应用程序,请从 webiq::azure_identity 中选择 ManagedIdentityCredential 或 WorkloadIdentityCredential。

将com.azure:azure-identity 添加到 Maven 或 Gradle 依赖项中,并使用与项目的 Azure SDK 依赖项兼容的版本。

import com.azure.identity.DefaultAzureCredentialBuilder;
import com.microsoft.webiq.WebIQClient;
import com.microsoft.webiq.WebIQClientOptions;

WebIQClientOptions options = WebIQClientOptions.builder()
        .credential(new DefaultAzureCredentialBuilder().build())
        .build();
try (WebIQClient client = new WebIQClient(options)) {
    System.out.println(client.web.search("Microsoft Web IQ").getWebResults());
}
dotnet add package Azure.Identity
using Azure.Identity;
using Microsoft.WebIQ;

using var client = new WebIQClient(new WebIQClientOptions
{
    Credential = new DefaultAzureCredential()
});
var response = await client.Web.SearchAsync("Microsoft Web IQ");
Console.WriteLine(response.WebResults?.Count);

资源和请求选项

将 REST 参考用于参数说明、支持的值、响应字段和服务限制。

Resource 方法 Reference
自动 client.auto.search(query, ...) 自动
Web client.web.search(query, ...) Web 搜索
新闻 client.news.search(query, ...) 新闻搜索
Videos client.videos.search(query, ...) 视频搜索
图像 client.images.search(query, ...) 图像搜索
Places client.places.search(query, ...) 地点
浏览 client.browse.fetch(url, ...) 浏览

请求选项使用 snake_case;响应属性使用 camelCase。 对支持的值使用 SDK 枚举。 例如:

from webiq.types import ContentFormat, ImageAspectRatio, ImageSize, SafeSearch

web = client.web.search(
    "search terms",
    max_results=10,
    language="en",
    region="US",
    location="lat:40.7;long:-74.0",
    content_format=ContentFormat.passage,
    max_length=3000,
)
news = client.news.search(
    "search terms",
    max_results=10,
    content_format=ContentFormat.passage,
    max_length=3000,
)
videos = client.videos.search(
    "search terms", max_results=5, enable_playlist=True, freshness="month",
)
images = client.images.search(
    "search terms",
    max_results=5,
    aspect_ratio=ImageAspectRatio.wide,
    image_size=ImageSize.large,
    safe_search=SafeSearch.strict,
    watermark_free=True,
)

其余代码片段假定打开 client ,除非它们显式构造一个。

Resource 方法 Reference
自动 client.auto.search(query, options) 自动
Web client.web.search(query, options) Web 搜索
新闻 client.news.search(query, options) 新闻搜索
Videos client.videos.search(query, options) 视频搜索
图像 client.images.search(query, options) 图像搜索
Places client.places.search(query, options) 地点
浏览 client.browse.fetch(url, options) 浏览

请求选项和响应属性使用 camelCase,例如 maxResults、contentFormat、liveCrawl 和 aspectRatio。 将选项作为第二个参数传递。 对受支持的值使用 SDK 枚举,如快速入门中所示。

其余代码片段假定已打开 client,并在异步函数中运行,除非它们显式构造客户端。 顶级 await 需要 ES 模块。

Resource 方法 Reference
自动 client.auto().search(query, options) 自动
Web client.web().search(query, options) Web 搜索
新闻 client.news().search(query, options) 新闻搜索
Videos client.videos().search(query, options) 视频搜索
图像 client.images().search(query, options) 图像搜索
Places client.places().search(query, options) 地点
浏览 client.browse().fetch(url, options) 浏览

使用 AutoSearchOptions、WebSearchOptions、NewsSearchOptions、VideoSearchOptions、ImageSearchOptions、PlacesSearchOptions 或 BrowseOptions 构建选项。 响应字段使用 snake_case,可选值使用 Option。

其余代码片段在一个返回 Result 的异步函数内运行,并且已有一个打开的 client,除非它们显式构造了一个。 使用快速入门中的 Tokio 运行时设置。

Resource 方法 Reference
自动 client.auto.search(query, AutoSearchOptions) 自动
Web client.web.search(query, WebSearchOptions) Web 搜索
新闻 client.news.search(query, NewsSearchOptions) 新闻搜索
Videos client.videos.search(query, VideosSearchOptions) 视频搜索
图像 client.images.search(query, ImagesSearchOptions) 图像搜索
Places client.places.search(query, PlacesSearchOptions) 地点
浏览 client.browse.fetch(url, BrowseFetchOptions) 浏览

使用 camelCase 生成器方法(例如 maxResults, contentFormat和 maxLength)生成请求选项。 通过 getter(如 getWebResults() 和 getTraceId())读取响应属性。 可选的响应字段可以是 null。

其余代码片段在方法内运行,且是在已有一个打开的 client 的情况下,除非它们显式构造一个 client。 将导入放在Java文件的顶部。

Resource 异步方法 Reference
自动 client.Auto.SearchAsync(query, configure) 自动
Web client.Web.SearchAsync(query, configure) Web 搜索
新闻 client.News.SearchAsync(query, configure) 新闻搜索
Videos client.Videos.SearchAsync(query, configure) 视频搜索
图像 client.Images.SearchAsync(query, configure) 图像搜索
Places client.Places.SearchAsync(query, configure) 地点
浏览 client.Browse.FetchAsync(url, configure) 浏览

请求和响应属性使用 PascalCase。 在配置回调中设置请求选项,或直接传递请求模型。 同步 Search 和 Fetch 方法也可用。

其余代码片段假定打开 client ,除非它们显式构造一个。

Auto 的可用性

所有五个 SDK 在 1.2.1 版中都提供 Auto。 Python 和 Java 通过其同步客户端和异步客户端公开 Auto;.NET 提供 Search 和 SearchAsync;TypeScript 和 Rust 使用异步调用。

编写完整的自然语言问题,并保留对应用程序至关重要的约束。 将每个结果的 evidence 与其 citations 一起阅读;引文仅支持各自所属的结果。 有关参数、证据类型和服务限制,请参阅 Auto API 参考。

异步支持

当应用程序需要多个结果类型时,并发发出独立请求。

使用 WebIQAsyncClient 和 asyncio:

import asyncio
import os
from webiq import WebIQAsyncClient

async def main():
    async with WebIQAsyncClient(api_key=os.environ["WEBIQ_API_KEY"]) as client:
        web, news = await asyncio.gather(
            client.web.search("Microsoft Web IQ"),
            client.news.search("technology"),
        )
        print(web.webResults, news.newsResults)

asyncio.run(main())
const [web, news] = await Promise.all([
  client.web.search('Microsoft Web IQ'),
  client.news.search('technology'),
]);
console.log(web.webResults, news.newsResults);
let web_resource = client.web();
let news_resource = client.news();
let (web, news) = tokio::try_join!(
    web_resource.search("Microsoft Web IQ", Default::default()),
    news_resource.search("technology", Default::default()),
)?;
println!("{:?} {:?}", web.web_results, news.news_results);

使用 WebIQAsyncClient;其资源方法返回 CompletableFuture:

import com.microsoft.webiq.WebIQAsyncClient;
import com.microsoft.webiq.models.NewsResponse;
import com.microsoft.webiq.models.WebResponse;
import java.util.concurrent.CompletableFuture;

try (WebIQAsyncClient client = WebIQAsyncClient.withApiKey(System.getenv("WEBIQ_API_KEY"))) {
    CompletableFuture<WebResponse> web = client.web.search("Microsoft Web IQ");
    CompletableFuture<NewsResponse> news = client.news.search("technology");
    CompletableFuture.allOf(web, news).join();
    System.out.println(web.join().getWebResults());
    System.out.println(news.join().getNewsResults());
}
var webTask = client.Web.SearchAsync("Microsoft Web IQ");
var newsTask = client.News.SearchAsync("technology");
await Task.WhenAll(webTask, newsTask);
Console.WriteLine((await webTask).WebResults?.Count);
Console.WriteLine((await newsTask).NewsResults?.Count);

Configuration

超时和重试

设置客户端级超时,然后在必要时按请求单独覆盖该设置。 超时按每次尝试计算,而不是适用于重试花费的总时间。

默认情况下,SDK 会重试暂时性网络故障以及 HTTP 408、 500、、 502、 520, 523以及 524 最多两次,并出现指数退避和抖动。 响应正文中的有效 retryAfter 值优先于生成的退避。 HTTP 429 且 430 永远不会自动重试:检查错误的重试指南并应用自己的退避。 客户端超时不会被重试。

import os
from webiq import WebIQClient, RetryPolicy

with WebIQClient(
    api_key=os.environ["WEBIQ_API_KEY"],
    timeout=10.0,
    retry=RetryPolicy(max_retries=2, base_delay_s=0.25, max_delay_s=4.0),
) as client:
    response = client.web.search("Microsoft Web IQ", timeout=30.0)

超时以秒为单位。 客户端默认值为 10 秒。

import { WebIQClient, RetryPolicy } from '@microsoft/webiq';

const client = new WebIQClient({
  apiKey: process.env.WEBIQ_API_KEY,
  timeout: 10_000,
  retry: new RetryPolicy({
    maxRetries: 2,
    baseDelaySeconds: 0.25,
    maxDelaySeconds: 4.0,
  }),
});
try {
  const response = await client.web.search('Microsoft Web IQ', { timeout: 30_000 });
  console.log(response.webResults);
} finally {
  await client.close();
}

超时以毫秒为单位。 客户端默认值为 10,000 毫秒。

use std::time::Duration;
use webiq::{RetryPolicy, WebIqClient, WebSearchOptions};

let client = WebIqClient::builder()
    .api_key(std::env::var("WEBIQ_API_KEY")?)
    .timeout(Duration::from_secs(10))
    .retry(RetryPolicy::new().max_retries(2))
    .build()?;
let response = client.web().search(
    "Microsoft Web IQ",
    WebSearchOptions::new().timeout(Duration::from_secs(30)),
).await?;

客户端默认值为 10 秒。

import com.microsoft.webiq.WebIQClient;
import com.microsoft.webiq.WebIQClientOptions;
import com.microsoft.webiq.resources.WebSearchOptions;
import com.microsoft.webiq.retry.RetryPolicy;
import java.time.Duration;

WebIQClientOptions options = WebIQClientOptions.builder()
        .apiKey(System.getenv("WEBIQ_API_KEY"))
        .timeout(Duration.ofSeconds(10))
        .retry(RetryPolicy.builder().maxRetries(2).build())
        .build();
try (WebIQClient client = new WebIQClient(options)) {
    client.web.search("Microsoft Web IQ",
            WebSearchOptions.builder().timeout(Duration.ofSeconds(30)).build());
}

客户端默认值为 10 秒。

using Microsoft.WebIQ;

using var client = new WebIQClient(new WebIQClientOptions
{
    ApiKey = Environment.GetEnvironmentVariable("WEBIQ_API_KEY"),
    Timeout = TimeSpan.FromSeconds(30),
    Retry = new RetryPolicy { MaxRetries = 2 }
});
var response = await client.Web.SearchAsync("Microsoft Web IQ",
    timeout: TimeSpan.FromSeconds(10));

客户端默认值为 30 秒。

自定义 HTTP 客户端

使用自定义 HTTP 客户端进行代理、TLS 或连接池配置。 不要禁用证书验证。

自行传递 http_client 并关闭调用方拥有的 HTTP 客户端。 使用 httpx.AsyncClient 配合 WebIQAsyncClient 发起异步请求。

import os
import httpx
from webiq import WebIQClient

with httpx.Client(
    base_url="https://api.microsoft.ai/v3",
    proxy="http://proxy:8080",
) as http_client:
    with WebIQClient(
        api_key=os.environ["WEBIQ_API_KEY"],
        http_client=http_client,
    ) as client:
        response = client.web.search("Microsoft Web IQ")

undici安装代理支持:

npm install undici

传递自定义 fetchFn。 保留 init ,以便转发 SDK 的标头、正文和内部 AbortSignal 。

import { ProxyAgent } from 'undici';
import { WebIQClient } from '@microsoft/webiq';

const proxyAgent = new ProxyAgent('http://proxy:8080');
const client = new WebIQClient({
  apiKey: process.env.WEBIQ_API_KEY,
  fetchFn: (url, init) => {
    const options = { ...init, dispatcher: proxyAgent };
    return fetch(url, options);
  },
});
try {
  const response = await client.web.search('Microsoft Web IQ');
  console.log(response.webResults);
} finally {
  await client.close();
  await proxyAgent.close();
}

将已配置的 reqwest::Client 传递给 WebIqClient::builder().http_client(...)。 如果应用程序直接构造此客户端,请将 reqwest 添加为与 SDK 兼容版本的直接依赖项。

通过 WebIQClientOptions.builder().httpClient(...) 传递已配置的 java.net.http.HttpClient。 SDK 不会关闭调用方拥有的客户端;在应用程序中管理其生存期。

通过 WebIQClientOptions.HttpClient 传递一个 HttpClient。 SDK 不会释放调用方拥有的 HTTP 客户端;在应用程序中管理其生存期。

取消

对于异步请求,请使用 asyncio 任务取消或 asyncio.timeout 设置包含重试等待时间的总时间预算。 每个请求的 SDK 超时会限制每次 HTTP 尝试的时长。

每个资源方法都接受一个 AbortSignal 到 options.signal。 中止会取消正在进行的请求并重试等待;会原样再次抛出该信号的原因。

const response = await client.web.search('Microsoft Web IQ', {
  signal: AbortSignal.timeout(5_000),
});

若要将入站请求的信号与实际时间限制相结合,请使用 AbortSignal.any([request.signal, AbortSignal.timeout(5_000)])。

取消或丢弃请求 future 对象,以中断该操作,包括重试等待。 对于应用程序中的截止时间,请使用 Tokio 时间实用工具并启用 Tokio 的 time 功能。

使用每次调用的 timeout 来限制每次 HTTP 尝试。 SDK 1.2.1 不提供请求取消令牌。 取消返回的 CompletableFuture 并不能保证取消底层 HTTP 请求或重试等待。

传递一个 CancellationToken 取消操作,包括重试等待:

using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var response = await client.Web.SearchAsync("Microsoft Web IQ",
    cancellationToken: cancellation.Token);

Telemetry

附加遥测回调以记录每个请求尝试、状态和已用时间。 遥测还包括请求和跟踪 ID、重试指南和错误信息。 避免记录凭据或敏感查询内容。

import os
from webiq import WebIQClient, TelemetryEvent

def on_request(event: TelemetryEvent):
    print(f"{event.method} {event.path}: {event.status_code} ({event.elapsed_ms}ms)")

with WebIQClient(
    api_key=os.environ["WEBIQ_API_KEY"],
    telemetry_hook=on_request,
) as client:
    response = client.web.search("Microsoft Web IQ")

遥测字段使用 snake_case,包括 error、error_body、retry_after、elapsed_ms、trace_id、request_id、status_code 和 attempt。

import { WebIQClient } from '@microsoft/webiq';

const client = new WebIQClient({
  apiKey: process.env.WEBIQ_API_KEY,
  telemetryHook: event => {
    console.log(`${event.method} ${event.path}: ${event.statusCode} (${event.elapsedMs}ms)`);
  },
});
try {
  await client.web.search('Microsoft Web IQ');
} finally {
  await client.close();
}

遥测字段使用 camelCase,包括 attempt、statusCode、requestId、traceId、retryAfter、elapsedMs、以及 error 和 errorBody。

use std::sync::Arc;
use webiq::{TelemetryEvent, WebIqClient};

let client = WebIqClient::builder()
    .api_key(std::env::var("WEBIQ_API_KEY")?)
    .telemetry_hook(Arc::new(|event: &TelemetryEvent| {
        println!("{} {}: {:?} ({:?}ms)",
            event.method, event.path, event.status_code, event.elapsed_ms);
    }))
    .build()?;
client.web().search("Microsoft Web IQ", Default::default()).await?;
import com.microsoft.webiq.WebIQClient;
import com.microsoft.webiq.WebIQClientOptions;

WebIQClientOptions options = WebIQClientOptions.builder()
        .apiKey(System.getenv("WEBIQ_API_KEY"))
        .telemetryHook(event -> System.out.printf("%s %s: %s (%sms)%n",
                event.getMethod(), event.getPath(),
                event.getStatusCode(), event.getElapsedMs()))
        .build();
try (WebIQClient client = new WebIQClient(options)) {
    client.web.search("Microsoft Web IQ");
}
using Microsoft.WebIQ;

using var client = new WebIQClient(new WebIQClientOptions
{
    ApiKey = Environment.GetEnvironmentVariable("WEBIQ_API_KEY"),
    TelemetryHook = telemetry => Console.WriteLine(
        $"{telemetry.Method} {telemetry.Path}: " +
        $"{telemetry.StatusCode} ({telemetry.ElapsedMilliseconds}ms)")
});
await client.Web.SearchAsync("Microsoft Web IQ");

错误处理

分别处理身份验证、权限和速率限制错误与暂时性故障。 HTTP 429 和 430 会立即出现,无需 SDK 重试。 使用返回的重试指南来决定何时重试。

所有 SDK 异常都继承自 WebIQError. HTTP 错误继承自 ,包括 、 和 。 网络故障和超时会引发 APIConnectionError。 Python 请求验证在发送请求前可能引发 pydantic.ValidationError。

from webiq import (
    APIConnectionError, APIStatusError, AuthenticationError,
    PermissionDeniedError, RateLimitError, WebIQError,
)

try:
    response = client.web.search("Microsoft Web IQ")
except AuthenticationError as error:
    print(f"Authentication failed: {error}")
except PermissionDeniedError as error:
    print(f"Forbidden: {error}")
except RateLimitError as error:
    print(f"Rate limited; retry after: {error.retry_after}")
except APIStatusError as error:
    print(f"HTTP {error.status_code}: {error}")
    if isinstance(error.body, dict):
        print(error.body.get("errorCode"), error.body.get("traceId"))
except APIConnectionError as error:
    print(f"Connection failed: {error}")
except WebIQError as error:
    print(f"SDK error: {error}")

检查APIStatusError.body完整的服务器错误响应,包括errorCategory、errorCode、technicalDetailsretryAfter和traceId。

所有 SDK 错误都继承自 WebIQError. HTTP 错误继承自 ,包括 、 和 。 网络故障和超时会引发 APIConnectionError。

import {
  APIConnectionError, APIStatusError, AuthenticationError,
  PermissionDeniedError, RateLimitError,
} from '@microsoft/webiq';

try {
  await client.web.search('Microsoft Web IQ');
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Authentication failed:', error.message);
  } else if (error instanceof PermissionDeniedError) {
    console.error('Forbidden:', error.message);
  } else if (error instanceof RateLimitError) {
    console.error('Rate limited; retry after:', error.retryAfter);
  } else if (error instanceof APIStatusError) {
    console.error(`HTTP ${error.statusCode}:`, error.message);
    if (error.body && typeof error.body === 'object') {
      const body = error.body as Record<string, unknown>;
      console.error(body.errorCode, body.traceId);
    }
  } else if (error instanceof APIConnectionError) {
    console.error('Connection failed:', error.message);
  } else {
    throw error;
  }
}

检查APIStatusError.body完整的服务器错误响应,包括errorCategory、errorCode、technicalDetailsretryAfter和traceId。

调用返回 Result<T, WebIqError>。 匹配 API 错误,或检查用于结构化诊断的错误访问器方法:

use webiq::WebIqError;

match client.web().search("Microsoft Web IQ", Default::default()).await {
    Ok(response) => println!("{:?}", response.web_results),
    Err(WebIqError::Authentication(details)) => eprintln!("401: {}", details.message),
    Err(WebIqError::PermissionDenied(details)) => eprintln!("403: {}", details.message),
    Err(WebIqError::RateLimit(details)) => {
        eprintln!("Rate limited; retry after: {:?}", details.retry_after());
    }
    Err(error) => {
        eprintln!("{error}");
        eprintln!("Code: {:?}, trace: {:?}", error.error_code(), error.trace_id());
    }
}

API 错误公开 status_code()、error_category()、error_code()、technical_details()、user_message()、retry_after()、request_id()、trace_id() 和 body()。 缺少可选字段时,返回 None。

所有 SDK 异常都继承自 WebIQException. HTTP 状态异常继承自 APIStatusException. 网络故障和超时会引发 APIConnectionException。

import com.microsoft.webiq.errors.*;

try {
    client.web.search("Microsoft Web IQ");
} catch (AuthenticationException error) {
    System.err.println("Authentication failed: " + error.getMessage());
} catch (PermissionDeniedException error) {
    System.err.println("Forbidden: " + error.getMessage());
} catch (RateLimitException error) {
    System.err.println("Rate limited; retry after: " + error.getRetryAfter());
} catch (APIStatusException error) {
    System.err.println("HTTP " + error.getStatusCode() + ": " + error.getMessage());
    System.err.println("Code: " + error.getErrorCode() + ", trace: " + error.getTraceId());
} catch (APIConnectionException error) {
    System.err.println("Connection failed: " + error.getMessage());
}

状态异常公开 getStatusCode()、getErrorCategory()、getUserMessage()、getErrorCode()、getTechnicalDetails()、getRetryAfter()、getRequestId()、getTraceId() 和 getBody()。 缺少可选字段时,返回 null。

HTTP 状态异常继承自 ApiStatusException. 网络故障和超时会引发 ApiConnectionException。

using Microsoft.WebIQ;

try
{
    await client.Web.SearchAsync("Microsoft Web IQ");
}
catch (AuthenticationException error)
{
    Console.Error.WriteLine($"Authentication failed: {error.Message}");
}
catch (PermissionDeniedException error)
{
    Console.Error.WriteLine($"Forbidden: {error.Message}");
}
catch (RateLimitException error)
{
    Console.Error.WriteLine($"Rate limited; retry after: {error.RetryAfter}");
}
catch (ApiStatusException error)
{
    Console.Error.WriteLine($"HTTP {error.StatusCode}: {error.Message}");
    Console.Error.WriteLine($"Code: {error.ErrorCode}, trace: {error.TraceId}");
}
catch (ApiConnectionException error)
{
    Console.Error.WriteLine($"Connection failed: {error.Message}");
}

状态异常提供 ErrorCategory、ErrorCode、UserMessage、TechnicalDetails、RetryAfter、RequestId、TraceId 和 Body。 可选字段缺失。null

当爬网挂起时,Browse 可能会返回 HTTP 202 Accepted。 这是正常的响应,而不是异常,SDK 不会自动轮询。 使用响应 URL 和 UTC retryAfter 时间戳稍后重试。 部分 HTTP 200 响应可以包括一个 truncationReason,例如 "encumbrance"。

调试和后续步骤

  • 联系支持人员时包括 traceId 。 Rust 使用trace_id、Java使用getTraceId()和.NET使用TraceId。
  • 使用遥测来关联尝试、响应代码和已用时间。
  • 在将错误视为可重试之前,请检查结构化错误正文。 参见错误处理。
  • 显示或引用搜索结果时添加 单击和引文埋点。