SDKs

Microsoft Web IQ SDKs 提供網頁、新聞、影片、圖片、地點搜尋及瀏覽的具型別用戶端。 請在本頁頂端選擇一種語言,將所有安裝指令與範例一同切換。

這些範例使用公開的 1.1.0 SDK 版本,支援 Places 與以查詢為導向的 Browse passages。 在執行之前,先升級較早的 SDK 版本。

Property Python TypeScript Rust JAVA .NET
套件 webiq @microsoft/webiq webiq com.microsoft.webiq:webiq Microsoft.WebIQ
使用的版本 1.1.0 1.1.0 1.1.0 1.1.0 1.1.0
Runtime Python 3.11+ Node.js 22.13+(22.x)或24+ Rust 1.88+ JAVA 11+ .NET 8+
License 麻省理工學院 麻省理工學院 麻省理工學院 麻省理工學院 麻省理工學院

你需要 Web IQ API 金鑰或 Microsoft Entra 身份,並能存取 Web IQ。 請參閱驗證。

Installation

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

將 SDK 和 Tokio 執行環境加入你的專案:

cargo add webiq@1.1.0
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.1.0</version>
</dependency>

Gradle:

implementation "com.microsoft.webiq:webiq:1.1.0"

這些範例使用公開Microsoft.WebIQ的 1.1.0 套件,並要求使用 .NET 8 或更新版本。 在 .NET 控制台專案中執行此指令:

dotnet add package Microsoft.WebIQ --version 1.1.0

快速入門

在執行範例前,先把 WEBIQ_API_KEY 環境變數設成你的 API 金鑰。 不要把 API 金鑰放進原始碼裡。

範例呼叫 Web、News、Video、Image 和 Places Search,並用 Browse 取得頁面。 網路、新聞與瀏覽請求段落,這是建議的依據格式。 瀏覽時也需要選取內容不得為空白,且長度最多為 query 1000 個字元。 關於完整文件格式,請參見 內容格式。

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

with WebIQClient(api_key=os.environ["WEBIQ_API_KEY"]) as client:
    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 } 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 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::{
    BrowseContentFormat, BrowseOptions, ContentFormat, ImageSearchOptions,
    LiveCrawlMode, NewsSearchOptions, PlacesSearchOptions, VideoSearchOptions,
    WebIqClient, WebSearchOptions,
};

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

    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"))) {
            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;

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 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 認證

與其使用 API 金鑰,不如傳遞 Azure Identity 憑證。 本地開發時,請使用支援的開發者工具登入,例如 Azure CLI。 對於 Azure 託管的應用程式,請使用管理身份或工作負載身份。 你的身份必須能存取 Web IQ。

預設的 OAuth 範圍為 https://api.microsoft.ai/.default。

安裝可選的認證依賴:

python -m pip install "webiq[entra]==1.1.0"
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重新匯出 ,因此不需要額外的依賴。 此範例在 az login 或 azd auth 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.web.search(query, ...) 網路搜尋
新聞 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.web.search(query, options) 網路搜尋
新聞 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.web().search(query, options) 網路搜尋
新聞 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) 瀏覽

使用 WebSearchOptions、NewsSearchOptions、VideoSearchOptions、ImageSearchOptions、PlacesSearchOptions 或 BrowseOptions 建立選項。 回應欄位使用 snake_case,選擇性值使用 Option。

其餘的片段則在一個非同步函式中執行,回傳 Result,並帶有一個開啟的 client,除非他們明確建構一個。 用快速入門的 Tokio 執行環境設定。

Resource 方法 Reference
網路 client.web.search(query, WebSearchOptions) 網路搜尋
新聞 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 等,建置請求選項。 透過 getTraceId() 和 getWebResults() 等 getter 讀取回應屬性。 可選的回應欄位可能為 null。

其餘的片段則在一個方法中執行,且具有一個開啟的 client,除非它們明確建構了一個。 將匯入放在 Java 檔案的最上方。

Resource 非同步方法 Reference
網路 client.Web.SearchAsync(query, configure) 網路搜尋
新聞 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 可用性

Python、TypeScript、Rust、Java 和 .NET SDK 的公開 1.1.0 版本未提供 Auto 用戶端。 這裡還沒有包含 Auto SDK 範例。 請參閱 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 不會關閉呼叫端擁有的用戶端;請在您的應用程式中管理其生命週期。

將一個 HttpClient 傳入 WebIQClientOptions.HttpClient。 SDK 不會釋放由呼叫者擁有的 HTTP 用戶端;請在你的應用程式中管理其生命週期。

取消

對於非同步請求,可以使用 asyncio 任務取消或 asyncio.timeout 設定包含重試等待的實際經過時間預算。 每請求的 SDK 逾時時限限制了每次 HTTP 嘗試。

每個資源方法都接受從 AbortSignal 到 options.signal。 中止會取消進行中的請求與重試等待;signal 的 reason 會原樣再次拋出。

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.1.0 未提供請求取消權杖。 取消回傳的 CompletableFuture 並不保證底層 HTTP 請求或重試等待會被取消。

傳遞 CancellationToken 以取消操作,包括重試等待:

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

Telemetry

附加遙測回呼,記錄每次請求嘗試、狀態及經過時間。 遙測還包括請求與追蹤識別碼、重試指引及錯誤資訊。 避免記錄憑證或敏感查詢內容。

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,包括 attempt、status_code、request_id、error_body、trace_id、retry_after、elapsed_ms 和 error。

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、 error、 retryAfter、 elapsedMs,以及 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 錯誤繼承自 APIStatusError,包括 AuthenticationError、PermissionDeniedError 及 RateLimitError。 網路故障與逾時會引發 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、technicalDetails、retryAfter 和 traceId。

所有 SDK 錯誤皆繼承自 WebIQError。 HTTP 錯誤繼承自 APIStatusError,包括 AuthenticationError、PermissionDeniedError 及 RateLimitError。 網路故障與逾時會引發 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、technicalDetails、retryAfter 和 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()、 body()request_id()technical_details()trace_id()error_code()user_message()retry_after()。 缺少選填欄位時,會返回 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()、 getBody()、getRequestId()、getTechnicalDetails()、getTraceId()、getErrorCode()、getUserMessage(),以及 getRetryAfter()。 缺少選填欄位時,會返回 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、Body、TechnicalDetails、RetryAfter、RequestId 和 TraceId。 缺少的可選欄位為 null。

瀏覽可以在爬取待處理時回傳 HTTP 202 Accepted 。 這是正常的回應,並非例外,SDK 也不會自動輪詢。 請使用回應網址和UTC retryAfter 時間戳記稍後再試。 部分 HTTP 200 回應可以包含一個 truncationReason,例如 "encumbrance"。

除錯與後續步驟

  • 聯絡客服時請附上 traceId。 Rust 使用 trace_id, Java 使用 getTraceId(), .NET 使用 TraceId。
  • 利用遙測來關聯各次嘗試、回應代碼和經過時間。
  • 在將錯誤視為可重試之前,先檢查結構化錯誤體。 請參見 錯誤處理。
  • 在顯示或引用搜尋結果時,加入 點擊與引用追蹤機制。