SDKs

Zestawy SDK Microsoft Web IQ udostępniają silnie typowane klienty dla wyszukiwania Auto, w sieci Web, wiadomości, wideo, obrazów i miejsc, Commerce oraz Browse. Wybierz język w górnej części tej strony, aby przełączyć wszystkie polecenia instalacji i przykłady razem.

W tych przykładach użyto publicznych wersji zestawu SDK 1.2.1 dla Auto search z typowanymi dowodami i cytatami ograniczonymi do wyników. Uaktualnij wcześniejsze wersje zestawu SDK przed ich uruchomieniem.

Property Python TypeScript Rust Java .NET
Package webiq @microsoft/webiq webiq com.microsoft.webiq:webiq Microsoft.WebIQ
Użyta wersja 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) lub 24+ Rust 1.88+ Java 11+ .NET 8+
License MIT MIT MIT MIT MIT

Potrzebujesz klucza API Web IQ lub tożsamości Microsoft Entra z dostępem do Web IQ. Zobacz Uwierzytelnianie.

Installation

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

Dodaj zestaw SDK i środowisko uruchomieniowe Tokio do projektu:

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

Dodaj zależność z Maven Central do pliku pom.xml projektu. Skonfiguruj projekt do kompilacji dla Java 11 lub nowszego.

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

Dla Gradle:

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

Te przykłady używają publicznego Microsoft.WebIQ pakietu 1.2.1 i wymagają .NET 8 lub nowszej. Uruchom to polecenie w projekcie konsoli .NET:

dotnet add package Microsoft.WebIQ --version 1.2.1

Szybki start

Przed uruchomieniem przykładu ustaw zmienną środowiskową WEBIQ_API_KEY na swój klucz API. Nie umieszczaj kluczy interfejsu API w kodzie źródłowym.

W przykładzie wywoływana jest funkcja Auto w trybie advanced z limitem czasu 60 sekund na próbę, wyświetlany jest każdy wynik evidence z przypisanymi cytowaniami źródłowymi, a następnie wywoływane są funkcje Web, News, Video, Image i Places Search oraz pobierana jest strona za pomocą Browse. Auto zwraca dowody, a nie wygenerowaną ostateczną odpowiedź. Zobacz dokumentację Auto, aby uzyskać informacje o typach dowodów i opcjach żądania.

Fragmenty z żądań Web, News i Browse, zalecany format na potrzeby podstawiania źródeł. Przeglądanie wymaga również niepustego zaznaczenia query o długości maksymalnie 1000 znaków. Aby uzyskać informacje o formatach całego dokumentu, zobacz Formaty zawartości.

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(())
}

Zapisz ten przykład jako src/main/java/WebIqSample.java w projekcie Maven i uruchom polecenie 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);

Uwierzytelnianie za pomocą Microsoft Entra ID

Zamiast klucza interfejsu API przekaż poświadczenie Azure Identity. W przypadku programowania lokalnego zaloguj się przy użyciu obsługiwanego narzędzia dewelopera, takiego jak Azure CLI. W przypadku aplikacji hostowanych na platformie Azure użyj tożsamości zarządzanej lub tożsamości obciążenia roboczego. Tożsamość musi mieć dostęp do Web IQ.

Domyślnym zakresem protokołu OAuth jest https://api.microsoft.ai/.default.

Zainstaluj opcjonalną zależność uwierzytelniania:

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();
}

Obsługa tożsamości Azure jest zawarta w pakiecie SDK. Zestaw SDK ponownie eksportuje azure_identity, więc nie jest wymagana dodatkowa zależność. W tym przykładzie użyto poświadczeń dewelopera po az login lub 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);

W przypadku aplikacji hostowanych wybierz pozycję ManagedIdentityCredential lub WorkloadIdentityCredential z webiq::azure_identity.

Dodaj com.azure:azure-identity do zależności narzędzia Maven lub Gradle, używając wersji zgodnej z zależnościami Azure SDK projektu.

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

Zasoby i opcje żądania

Użyj dokumentacji REST dla opisów parametrów, obsługiwanych wartości, pól odpowiedzi i limitów usługi.

Resource Metoda Reference
Auto client.auto.search(query, ...) Auto
sieć Web client.web.search(query, ...) Wyszukiwanie w Sieci Web
wiadomości client.news.search(query, ...) Wyszukiwanie wiadomości
Videos client.videos.search(query, ...) Wyszukiwanie wideo
Obrazy client.images.search(query, ...) Wyszukiwanie obrazów
Miejsca client.places.search(query, ...) Miejsca
Przeglądaj client.browse.fetch(url, ...) Przeglądaj
Wyszukiwanie Commerce client.commerce.search(query, ...) Handel
Oferty handlowe client.commerce.fetch_offers(...) Handel
Szczegóły produktu Commerce client.commerce.fetch_details(...) Handel

Opcje żądania używają snake_case; właściwości odpowiedzi używają camelCase. Użyj enumów SDK dla obsługiwanych wartości. Na przykład:

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,
)

Pozostałe fragmenty kodu zakładają, że client jest otwarty, chyba że skonstruują go jawnie.

Resource Metoda Reference
Auto client.auto.search(query, options) Auto
sieć Web client.web.search(query, options) Wyszukiwanie w Sieci Web
wiadomości client.news.search(query, options) Wyszukiwanie wiadomości
Videos client.videos.search(query, options) Wyszukiwanie wideo
Obrazy client.images.search(query, options) Wyszukiwanie obrazów
Miejsca client.places.search(query, options) Miejsca
Przeglądaj client.browse.fetch(url, options) Przeglądaj
Wyszukiwanie w handlu client.commerce.search(query, options) Handel
Oferty handlowe client.commerce.fetchOffers(options) Handel
Szczegóły produktu Commerce client.commerce.fetchDetails(options) Handel

Opcje żądania i właściwości odpowiedzi używają camelCase, takich jak maxResults, contentFormat, liveCrawli aspectRatio. Przekaż opcje jako drugi argument. Użyj wyliczenia zestawu SDK dla obsługiwanych wartości, jak pokazano w przewodniku Szybki start.

Pozostałe fragmenty kodu zakładają, że client jest otwarty, i są uruchamiane wewnątrz funkcji asynchronicznej, chyba że jawnie skonstruują klienta. Instrukcja await najwyższego poziomu wymaga modułu ES.

Resource Metoda Reference
Auto client.auto().search(query, options) Auto
sieć Web client.web().search(query, options) Wyszukiwanie w Sieci Web
wiadomości client.news().search(query, options) Wyszukiwanie wiadomości
Videos client.videos().search(query, options) Wyszukiwanie wideo
Obrazy client.images().search(query, options) Wyszukiwanie obrazów
Miejsca client.places().search(query, options) Miejsca
Przeglądaj client.browse().fetch(url, options) Przeglądaj
Wyszukiwanie Commerce client.commerce().search(query, options) Handel
Oferty handlowe client.commerce().fetch_offers(options) Handel
Szczegóły produktu Commerce client.commerce().fetch_details(options) Handel

Twórz opcje za pomocą AutoSearchOptions, PlacesSearchOptions, ImageSearchOptions, NewsSearchOptions, WebSearchOptions, BrowseOptions, CommerceSearchOptions, VideoSearchOptions, CommerceOffersOptions lub CommerceDetailsOptions. Pola odpowiedzi używają formatu snake_case, a opcjonalne wartości używają Option.

Pozostałe fragmenty kodu są uruchamiane wewnątrz funkcji asynchronicznej zwracającej Resultelement, z otwartym client, chyba że jawnie skonstruują taki obiekt. Użyj konfiguracji środowiska uruchomieniowego Tokio z przewodnika Szybki start.

Resource Metoda Reference
Auto client.auto.search(query, AutoSearchOptions) Auto
sieć Web client.web.search(query, WebSearchOptions) Wyszukiwanie w Sieci Web
wiadomości client.news.search(query, NewsSearchOptions) Wyszukiwanie wiadomości
Videos client.videos.search(query, VideosSearchOptions) Wyszukiwanie wideo
Obrazy client.images.search(query, ImagesSearchOptions) Wyszukiwanie obrazów
Miejsca client.places.search(query, PlacesSearchOptions) Miejsca
Przeglądaj client.browse.fetch(url, BrowseFetchOptions) Przeglądaj
Wyszukiwanie Commerce client.commerce.search(query, CommerceSearchOptions) Handel
Oferty handlowe client.commerce.fetchOffers(CommerceOffersOptions) Handel
Szczegóły produktu Commerce client.commerce.fetchDetails(CommerceDetailsOptions) Handel

Twórz opcje żądania za pomocą metod konstruktora camelCase, takich jak maxResults, contentFormat i maxLength. Odczytywanie właściwości odpowiedzi za pośrednictwem getterów, takich jak getWebResults() i getTraceId(). Opcjonalne pola odpowiedzi mogą być null.

Pozostałe fragmenty kodu są uruchamiane wewnątrz metody, przy otwartym client, chyba że jawnie je tworzą. Umieść import w górnej części pliku Java.

Resource Metoda asynchroniczna Reference
Auto client.Auto.SearchAsync(query, configure) Auto
sieć Web client.Web.SearchAsync(query, configure) Wyszukiwanie w Sieci Web
wiadomości client.News.SearchAsync(query, configure) Wyszukiwanie wiadomości
Videos client.Videos.SearchAsync(query, configure) Wyszukiwanie wideo
Obrazy client.Images.SearchAsync(query, configure) Wyszukiwanie obrazów
Miejsca client.Places.SearchAsync(query, configure) Miejsca
Przeglądaj client.Browse.FetchAsync(url, configure) Przeglądaj
Wyszukiwanie Commerce client.Commerce.SearchAsync(query, configure) Handel
Oferty handlowe client.Commerce.FetchOffersAsync(...) Handel
Szczegóły produktu Commerce client.Commerce.FetchDetailsAsync(...) Handel

Właściwości żądań i odpowiedzi używają zapisu PascalCase. Ustaw opcje żądania w wywołaniu zwrotnym konfiguracji lub przekaż model żądania bezpośrednio. Dostępne są również metody synchroniczne Search i Fetch .

Pozostałe fragmenty kodu zakładają, że client jest otwarty, chyba że skonstruują go jawnie.

Dostępność Auto

Auto jest dostępne we wszystkich pięciu zestawach SDK w wersji 1.2.1. Python i Java uwidaczniają funkcję Auto zarówno za pośrednictwem klientów synchronicznych, jak i asynchronicznych; .NET zapewnia Search i SearchAsync; TypeScript i Rust używają wywołań asynchronicznych.

Napisz pełne pytanie w języku naturalnym i zachowaj ograniczenia, które mają znaczenie dla aplikacji. Odczytaj każdy wynik — jego evidence razem z jego citations; cytaty dotyczą tylko wyniku, w którym się znajdują. Aby uzyskać informacje o parametrach, typach danych dowodowych i limitach usługi, zobacz Auto API reference.

Handel

Note

Interfejsy API handlu są dostępne w prywatnej wersji zapoznawczej i są dołączone do identyfikatorów AppID, które mają pełny dostęp do dokumentacji. Dostęp jest włączony oddzielnie dla wyszukiwania, ofert i szczegółów produktu. Zobacz Tworzenie środowiska zakupów za pomocą interfejsów API Commerce.

Wyszukaj produkty, a następnie pobierz oferty i szczegóły produktu dla znalezionego produktu. Gdy wyświetlasz ofertę, umieść link do jej clickUrl dokładnie tak, jak został zwrócony; zobacz Link do ofert.

response = client.commerce.search(
    "wireless headphones",
    max_results=5,  # 1-50, default 10
    language="en",
    region="US",
)
for product in response.products or []:
    if product.id:
        offer_id = product.offers[0].id if product.offers else None
        offers = client.commerce.fetch_offers(
            product_id=product.id, sku_id=product.skuId, offer_id=offer_id)
        details = client.commerce.fetch_details(
            product_id=product.id, sku_id=product.skuId)
        for offer in offers.offers or []:
            print(offer.name, offer.price, offer.clickUrl)
        for detail in details.products or []:
            print(detail.name, detail.description, detail.rating)

fetch_offers wymaga co najmniej jednego z: product_id, sku_id lub offer_id. fetch_details wymaga znaku niebędącego białym znakiem product_id lub sku_id i zwraca zero lub jeden produkt, a nie partię. Oba akceptują language, region i timeout; oferty akceptują również location. Te same metody są dostępne z await na WebIQAsyncClient.

const response = await client.commerce.search('wireless headphones', {
  maxResults: 5, // 1-50, default 10
  language: 'en',
  region: 'US',
});
for (const product of response.products ?? []) {
  if (product.id?.trim()) {
    const offers = await client.commerce.fetchOffers({
      productId: product.id,
      skuId: product.skuId,
      offerId: product.offers?.[0]?.id,
    });
    const details = await client.commerce.fetchDetails({
      productId: product.id,
      skuId: product.skuId,
    });
    console.log(offers.offers, details.products);
  }
}

fetchOffers wymaga co najmniej jednego z productId, skuId lub offerId. fetchDetails wymaga znaku niebędącego białym znakiem productId lub skuId i zwraca zero lub jeden produkt, a nie partię. Oba akceptują language, region, timeout i signal; oferty również akceptują location. Identyfikatory wyszukiwania i kolekcje są opcjonalne.

use webiq::{CommerceDetailsOptions, CommerceOffersOptions, CommerceSearchOptions};

let response = client.commerce().search("wireless headphones",
    CommerceSearchOptions::new().max_results(5).language("en").region("US")).await?;
for product in response.products.unwrap_or_default() {
    if let Some(id) = product.id.filter(|id| !id.trim().is_empty()) {
        let mut offers_options = CommerceOffersOptions::new().product_id(id.clone());
        let mut details_options = CommerceDetailsOptions::new().product_id(id);
        if let Some(sku_id) = product.sku_id {
            offers_options = offers_options.sku_id(sku_id.clone());
            details_options = details_options.sku_id(sku_id);
        }
        if let Some(offer_id) = product.offers.unwrap_or_default().into_iter().next().and_then(|o| o.id) {
            offers_options = offers_options.offer_id(offer_id);
        }
        let offers = client.commerce().fetch_offers(offers_options).await?;
        let details = client.commerce().fetch_details(details_options).await?;
        println!("{:?} {:?}", offers.offers, details.products);
    }
}

fetch_offers wymaga co najmniej jednego z product_id, sku_id lub offer_id. fetch_details wymaga niebędącego białym znaku product_id lub sku_id i zwraca zero lub jeden produkt, a nie partię. Oba konstruktory parametrów akceptują language, region i timeout; oferty akceptują także location. Identyfikatory wyszukiwania i kolekcje są opcjonalne.

CommerceResponse response = client.commerce.search("wireless headphones",
        CommerceSearchOptions.builder().maxResults(5).language("en").region("US").build());
if (response.getProducts() != null) {
    for (var product : response.getProducts()) {
        if (product.getId() != null && !product.getId().isBlank()) {
            String offerId = product.getOffers() != null && !product.getOffers().isEmpty()
                    ? product.getOffers().get(0).getId() : null;
            CommerceOffersResponse offers = client.commerce.fetchOffers(
                    CommerceOffersOptions.builder().productId(product.getId())
                            .skuId(product.getSkuId()).offerId(offerId).build());
            CommerceProductDetailsResponse details = client.commerce.fetchDetails(
                    CommerceDetailsOptions.builder().productId(product.getId())
                            .skuId(product.getSkuId()).build());
            System.out.println(offers.getOffers());
            System.out.println(details.getProducts());
        }
    }
}

fetchOffers wymaga co najmniej jednego z elementów productId, skuId lub offerId. fetchDetails wymaga elementu productId lub skuId, który nie jest białym znakiem, i zwraca zero lub jeden produkt, a nie partię. Oba konstruktory opcji akceptują language, region i timeout; oferty akceptują także location. Identyfikatory wyszukiwania i kolekcje są opcjonalne.

CommerceResponse response = await client.Commerce.SearchAsync("wireless headphones",
    request => request.MaxResults = 5);
foreach (var product in response.Products ?? [])
{
    if (!string.IsNullOrWhiteSpace(product.Id))
    {
        var offers = await client.Commerce.FetchOffersAsync(productId: product.Id,
            skuId: product.SkuId, offerId: product.Offers?.FirstOrDefault()?.Id);
        var details = await client.Commerce.FetchDetailsAsync(productId: product.Id,
            skuId: product.SkuId);
        Console.WriteLine($"{offers.Offers?.Count} offers, {details.Products?.Count} products");
    }
}

FetchOffers i FetchOffersAsync wymagają co najmniej jednego z productId, skuId lub offerId. FetchDetails i FetchDetailsAsync wymagają nieoznakowego znaku productId lub skuId i zwracają zero lub jeden produkt, a nie partię. Oba akceptują funkcję zwrotną configure dla Language i Region, a także parametry limitu czasu i anulowania; oferty również obsługują Location. Identyfikatory wyszukiwania i kolekcje są opcjonalne.

Scopes

Wyszukiwanie w sieci Web i wiadomości akceptują nazwę zakresu utworzonego w celu filtrowania wyników przy użyciu reguł dołączania i wykluczania tego zakresu. Zastąp your-scope-name nazwą swojego zakresu. Aby uzyskać informacje o konfiguracji i zachowaniu, zobacz Filtrowanie wyników za pomocą zakresów.

response = client.web.search(
    "Microsoft cloud services",
    scope_name="your-scope-name",
)
const response = await client.web.search('Microsoft cloud services', {
  scopeName: 'your-scope-name',
});
use webiq::WebSearchOptions;

let response = client.web().search("Microsoft cloud services",
    WebSearchOptions::new().scope_name("your-scope-name")).await?;
WebResponse response = client.web.search("Microsoft cloud services",
        WebSearchOptions.builder().scopeName("your-scope-name").build());
WebResponse response = await client.Web.SearchAsync("Microsoft cloud services",
    request => request.ScopeName = "your-scope-name");

Obsługa asynchroniczna

Wysyłaj żądania niezależne współbieżnie, gdy aplikacja potrzebuje wielu typów wyników.

Użyj WebIQAsyncClient z 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);

Użyj WebIQAsyncClient; jego metody zasobów zwracają 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

Limity czasu i ponowne próby

Ustaw limit czasu na poziomie klienta, a następnie nadpisz go dla poszczególnych żądań w razie potrzeby. Limity czasu są stosowane dla każdej próby, a nie do całkowitego czasu spędzonego na ponawianiu prób.

Domyślnie biblioteki SDK ponawiają przejściowe błędy sieci i HTTP 408, 500, 502, 520, 523 i 524 maksymalnie dwa razy, ze wykładniczym opóźnieniem i losowym rozrzutem. Prawidłowa wartość retryAfter w treści odpowiedzi ma pierwszeństwo przed wygenerowanym opóźnieniem ponowienia. HTTP 429 i 430 nigdy nie są ponawiane automatycznie: sprawdź wskazówki dotyczące ponawiania w komunikacie o błędzie i zastosuj własny mechanizm ponawiania. Limity czasu po stronie klienta nie są ponawiane.

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)

Limity czasu są w sekundach. Wartość domyślna klienta to 10 sekund.

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();
}

Limity czasu są w milisekundach. Wartość domyślna klienta to 10 000 milisekund.

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?;

Wartość domyślna klienta to 10 sekund.

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());
}

Wartość domyślna klienta to 10 sekund.

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

Wartość domyślna klienta to 30 sekund.

Niestandardowe klienty HTTP

Użyj niestandardowego klienta HTTP do konfiguracji serwera proxy, protokołu TLS lub puli połączeń. Nie wyłączaj weryfikacji certyfikatu.

Przekaż http_client i samodzielnie zamknij klienta HTTP należącego do wywołującego. Użyj polecenia httpx.AsyncClient z WebIQAsyncClient do żądań asynchronicznych.

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

Zainstaluj undici na potrzeby obsługi serwera proxy:

npm install undici

Przekaż niestandardowy element fetchFn. Zachowaj init, aby nagłówki, treść i wewnętrzne elementy AbortSignal w pakiecie SDK były przekazywane dalej.

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();
}

Przekaż skonfigurowany reqwest::Client do WebIqClient::builder().http_client(...). Jeśli aplikacja tworzy tego klienta bezpośrednio, dodaj reqwest jako bezpośrednią zależność z wersją zgodną z zestawem SDK.

Przekaż skonfigurowany java.net.http.HttpClient przez WebIQClientOptions.builder().httpClient(...). Zestaw SDK nie zamyka klientów należących do wywołującego; zarządzaj ich cyklem życia w aplikacji.

Przekaż HttpClient przez WebIQClientOptions.HttpClient. SDK nie zwalnia klienta HTTP należącego do kodu wywołującego; zarządzaj jego cyklem życia w swojej aplikacji.

Anulowanie

W przypadku żądań asynchronicznych należy użyć anulowania zadania asyncio lub asyncio.timeout, aby narzucić limit czasu rzeczywistego, który obejmuje czas oczekiwania między ponownymi próbami. Limit czasu SDK dla pojedynczego żądania ogranicza każdą próbę HTTP.

Każda metoda zasobu akceptuje AbortSignal poprzez options.signal. Przerwanie anuluje żądanie w toku i oczekiwanie na ponowienie prób; przyczyna sygnału jest ponownie zgłaszana bez zmian.

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

Aby połączyć sygnał żądania przychodzącego z limitem zegara ściennego, użyj polecenia AbortSignal.any([request.signal, AbortSignal.timeout(5_000)]).

Anuluj lub porzuć obiekt future żądania, aby przerwać operację, w tym oczekiwanie na ponowienie próby. W przypadku terminu dla aplikacji użyj narzędzi czasowych Tokio i włącz funkcję Tokio time.

Użyj timeout dla każdego wywołania, aby ograniczyć czas trwania każdej próby HTTP. Zestaw SDK 1.2.1 nie udostępnia tokenu anulowania żądania. Anulowanie zwróconego CompletableFuture nie gwarantuje anulowania bazowego żądania HTTP ani oczekiwania na ponowienie próby.

Przekaż CancellationToken, aby anulować operację, w tym oczekiwania na ponowienie próby:

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

Telemetry

Dołącz wywołanie zwrotne telemetrii, aby zarejestrować każdą próbę żądania, stan i czas, który upłynął. Dane telemetryczne obejmują również identyfikatory żądań i śledzenia, wskazówki dotyczące ponawiania prób i informacje o błędach. Unikaj rejestrowania poświadczeń lub poufnej zawartości zapytania.

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

Pola telemetrii używają formatu snake_case, w tym attempt, status_code, trace_id, elapsed_ms, error, request_id, retry_after i error_body.

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();
}

Pola telemetrii używają camelCase, w tym attempt, statusCode, traceId, requestId, retryAfter, elapsedMs, error i 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");

Obsługa błędów

Obsługuj błędy uwierzytelniania, uprawnień i limitu szybkości oddzielnie od błędów przejściowych. Błędy HTTP 429 i 430 są zwracane natychmiast, bez ponownych prób przez SDK. Skorzystaj z zwróconych wskazówek dotyczących ponawiania prób, aby zdecydować, kiedy ponowić próbę.

Wszystkie wyjątki zestawu SDK dziedziczą po WebIQError. Błędy HTTP dziedziczą po APIStatusError, w tym AuthenticationError, PermissionDeniedError i RateLimitError. Awarie sieci i przekroczenia limitu czasu zgłaszają błąd APIConnectionError. Walidacja żądania w Python może zgłosić pydantic.ValidationError przed wysłaniem żądania.

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}")

Sprawdź w APIStatusError.body pełną odpowiedź błędu serwera, w tym errorCategory, errorCode, technicalDetails, retryAfter i traceId.

Wszystkie błędy zestawu SDK dziedziczą po WebIQError. Błędy HTTP dziedziczą po APIStatusError, w tym AuthenticationError, PermissionDeniedError i RateLimitError. Awarie sieci i przekroczenia limitu czasu zgłaszają błąd 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;
  }
}

Sprawdź w APIStatusError.body pełną odpowiedź błędu serwera, w tym errorCategory, errorCode, technicalDetails, retryAfter i traceId.

Wywołania zwracają wartość Result<T, WebIqError>. Dopasowuj według błędów interfejsu API lub sprawdź metody dostępu błędów do diagnostyki ustrukturyzowanej:

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());
    }
}

Błędy interfejsu API uwidaczniają status_code(), technical_details(), error_code(), error_category(), retry_after(), request_id(), user_message(), trace_id() i body(). Brak opcjonalnych pól powoduje zwrócenie None.

Wszystkie wyjątki zestawu SDK dziedziczą po WebIQException. Wyjątki stanu HTTP dziedziczą po APIStatusException. Awarie sieci i przekroczenia limitu czasu zgłaszają błąd 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());
}

Wyjątki stanu zawierają getStatusCode(), getUserMessage(), getTechnicalDetails(), getErrorCategory(), getErrorCode(), getRetryAfter(), getRequestId(), getTraceId() i getBody(). Brak opcjonalnych pól powoduje zwrócenie null.

Wyjątki stanu HTTP dziedziczą po ApiStatusException. Awarie sieci i przekroczenia limitu czasu zgłaszają błąd 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}");
}

Wyjątki stanu uwidaczniają ErrorCategory, RetryAfter, ErrorCode, TechnicalDetails, RequestId, UserMessage, TraceId i Body. Brakuje opcjonalnych pól null.

Polecenie Browse może zwracać HTTP 202 Accepted, gdy przeszukiwanie oczekuje na wykonanie. Jest to normalna odpowiedź, a nie wyjątek, a zestaw SDK nie sonduje automatycznie. Użyj adresu URL odpowiedzi i znacznika czasu UTC retryAfter , aby ponowić próbę później. Częściowe odpowiedzi HTTP 200 mogą zawierać element truncationReason, taki jak "encumbrance".

Debugowanie i następne kroki

  • Dołącz traceId podczas kontaktowania się z pomocą techniczną. Rust używa metody trace_id, Java używa getTraceId()metody , a .NET używa metody TraceId.
  • Użyj telemetrii, aby skorelować próby, kody odpowiedzi i czas, który upłynął.
  • Sprawdź treść ustrukturyzowanego błędu przed traktowaniem błędu jako kwalifikującego się do ponowienia próby. Zobacz Obsługa błędów.
  • Dodaj instrumentację kliknięć i cytatów podczas wyświetlania lub przywołowywania wyników wyszukiwania.