SDKs

Microsoft Web IQ SDK는 Auto, 웹, 뉴스, 비디오, 이미지 및 장소 검색, 상거래 및 찾아보기를 위한 타입이 지정된 클라이언트를 제공합니다. 이 페이지의 맨 위에 있는 언어를 선택하여 모든 설치 명령과 예제를 함께 전환합니다.

이러한 예제에서는 입력된 증거 및 결과 범위 인용과 함께 Auto search용 공용 1.2.1 SDK 릴리스를 사용합니다. 이전 SDK 버전을 실행하기 전에 업그레이드합니다.

Property Python TypeScript 러스트 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 ID가 필요합니다. 인증을 참조하세요.

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

Quickstart

예제를 실행하기 전에 WEBIQ_API_KEY 환경 변수를 API 키로 설정합니다. 소스 코드에 API 키를 넣지 마세요.

이 예제에서는 시도 시간 제한이 60초인 자동 advanced 모드를 호출하고, 지원 인용을 사용하여 각 증거 결과를 인쇄한 다음, 웹, 뉴스, 비디오, 이미지 및 위치 검색을 호출하고 찾아보기를 사용하여 페이지를 검색합니다. Auto는 생성된 최종 답변이 아니라 증거를 반환합니다. 증명 정보 유형 및 요청 옵션은 Auto reference를 참조하세요.

웹, 뉴스 및 찾아보기 요청 구절은 그라운딩에 권장되는 형식입니다. 찾아보기에서는 비어 있지 않은 선택 항목 query 이 최대 1,000자까지 필요합니다. 전체 문서 형식은 콘텐츠 형식을 참조하세요.

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 인증

API 키 대신 Azure Identity 자격 증명을 전달합니다. 로컬 개발의 경우 지원되는 개발자 도구(예: Azure CLI)로 로그인합니다. Azure 호스팅된 애플리케이션의 경우 관리 ID 또는 워크로드 ID를 사용합니다. 사용자 ID에 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();
}

Azure Identity 지원은 SDK에 포함됩니다. 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을 선택하세요.

프로젝트의 Azure SDK 종속성과 호환되는 버전을 사용하여 com.azure:azure-identity를 Maven 또는 Gradle 종속성에 추가합니다.

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
Auto client.auto.search(query, ...) 자동
Web client.web.search(query, ...) 웹 검색
뉴스 client.news.search(query, ...) 뉴스 검색
Videos client.videos.search(query, ...) 비디오 검색
Images client.images.search(query, ...) 이미지 검색
장소 client.places.search(query, ...) 장소
찾아보기 client.browse.fetch(url, ...) 찾아보기
상거래 검색 client.commerce.search(query, ...) 상거래
커머스 제안 client.commerce.fetch_offers(...) 상거래
상거래 제품 세부 정보 client.commerce.fetch_details(...) 상거래

요청 옵션은 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
Auto client.auto.search(query, options) 자동
Web client.web.search(query, options) 웹 검색
뉴스 client.news.search(query, options) 뉴스 검색
Videos client.videos.search(query, options) 비디오 검색
Images client.images.search(query, options) 이미지 검색
장소 client.places.search(query, options) 장소
찾아보기 client.browse.fetch(url, options) 찾아보기
상거래 검색 client.commerce.search(query, options) 상거래
Commerce 제안 client.commerce.fetchOffers(options) 상거래
상거래 제품 세부 정보 client.commerce.fetchDetails(options) 상거래

요청 옵션 및 응답 속성은 maxResults, contentFormat, liveCrawl, aspectRatio와 같은 camelCase를 사용합니다. 옵션을 두 번째 인수로 전달합니다. 빠른 시작과 같이 지원되는 값에 SDK 열거형을 사용합니다.

나머지 코드 조각은 클라이언트를 명시적으로 생성하지 않는 한 client가 열린 상태라고 가정하며 비동기 함수 내에서 실행됩니다. 최상위에서 await는 ES 모듈이 필요합니다.

Resource 메서드 Reference
Auto client.auto().search(query, options) 자동
Web client.web().search(query, options) 웹 검색
뉴스 client.news().search(query, options) 뉴스 검색
Videos client.videos().search(query, options) 비디오 검색
Images client.images().search(query, options) 이미지 검색
장소 client.places().search(query, options) 장소
찾아보기 client.browse().fetch(url, options) 찾아보기
상거래 검색 client.commerce().search(query, options) 상거래
커머스 오퍼 client.commerce().fetch_offers(options) 상거래
상거래 제품 세부 정보 client.commerce().fetch_details(options) 상거래

WebSearchOptions, PlacesSearchOptions, BrowseOptions, CommerceOffersOptions, NewsSearchOptions, VideoSearchOptions, ImageSearchOptions, CommerceSearchOptions, CommerceDetailsOptions 또는 AutoSearchOptions를 사용하여 옵션을 빌드합니다. 응답 필드는 snake_case를 사용하고, 선택적 값에는 Option를 사용합니다.

나머지 코드 조각은 명시적으로 구성하지 않는 한 client가 열린 상태에서, Result를 반환하는 비동기 함수 내부에서 실행됩니다. 빠른 시작에서 Tokio 런타임 설정을 사용합니다.

Resource 메서드 Reference
Auto client.auto.search(query, AutoSearchOptions) 자동
Web client.web.search(query, WebSearchOptions) 웹 검색
뉴스 client.news.search(query, NewsSearchOptions) 뉴스 검색
Videos client.videos.search(query, VideosSearchOptions) 비디오 검색
Images client.images.search(query, ImagesSearchOptions) 이미지 검색
장소 client.places.search(query, PlacesSearchOptions) 장소
찾아보기 client.browse.fetch(url, BrowseFetchOptions) 찾아보기
상거래 검색 client.commerce.search(query, CommerceSearchOptions) 상거래
커머스 오퍼 client.commerce.fetchOffers(CommerceOffersOptions) 상거래
상거래 제품 세부 정보 client.commerce.fetchDetails(CommerceDetailsOptions) 상거래

contentFormat, maxLength, maxResults와 같은 camelCase 작성기 메서드로 요청 옵션을 빌드합니다. getter인 getWebResults() 및 getTraceId()를 통해 응답 속성을 읽습니다. 선택적 응답 필드는 null일 수 있습니다.

나머지 코드 조각은 명시적으로 구성하지 않는 한 client이 열린 상태에서 메서드 내에서 실행됩니다. 가져오기를 Java 파일의 맨 위에 놓습니다.

Resource 비동기 메서드 Reference
Auto client.Auto.SearchAsync(query, configure) 자동
Web client.Web.SearchAsync(query, configure) 웹 검색
뉴스 client.News.SearchAsync(query, configure) 뉴스 검색
Videos client.Videos.SearchAsync(query, configure) 비디오 검색
Images client.Images.SearchAsync(query, configure) 이미지 검색
장소 client.Places.SearchAsync(query, configure) 장소
찾아보기 client.Browse.FetchAsync(url, configure) 찾아보기
상거래 검색 client.Commerce.SearchAsync(query, configure) 상거래
커머스 제안 client.Commerce.FetchOffersAsync(...) 상거래
상거래 제품 세부 정보 client.Commerce.FetchDetailsAsync(...) 상거래

요청 및 응답 속성은 PascalCase를 사용합니다. 구성 콜백에서 요청 옵션을 설정하거나 요청 모델을 직접 전달합니다. 동기 Search 및 Fetch 메서드도 사용할 수 있습니다.

나머지 코드 조각은 명시적으로 구성하지 않는 한 client가 열려 있는 것으로 가정합니다.

Auto 사용 가능 여부

Auto는 버전 1.2.1의 5개 SDK에서 모두 사용할 수 있습니다. Python 및 Java는 동기 및 비동기 클라이언트를 통해 Auto를 노출합니다. .NET은 Search 및 SearchAsync를 제공합니다. TypeScript 및 Rust는 비동기 호출을 사용합니다.

완전한 자연어 질문을 작성하고 애플리케이션에 중요한 제약 조건을 유지합니다. 각 결과의 evidence와 citations를 함께 읽습니다. 인용은 자신을 포함하는 해당 결과만 뒷받침합니다. 매개 변수, 증명 정보 유형 및 서비스 제한은 Auto API reference를 참조하세요.

상거래

Note

상거래 API는 프라이빗 미리 보기로 제공되며 전체 문서 액세스 권한이 있는 AppID에 포함됩니다. 검색, 오퍼 및 제품 세부 정보에 대해 별도로 액세스가 사용하도록 설정됩니다. Commerce API를 사용하여 쇼핑 환경 구축하기를 확인하세요.

제품을 검색한 다음, 찾은 제품에 대한 오퍼 및 제품 세부 정보를 가져옵니다. 오퍼를 표시할 때 반환된 대로 정확하게 clickUrl에 연결합니다. 오퍼 링크를 참조하세요.

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 에는 하나 이상의 product_id, sku_id또는 offer_id.가 필요합니다. fetch_details에는 공백이 아닌 product_id 또는 sku_id가 필요하며, 일괄이 아니라 0개 또는 1개의 제품을 반환합니다. 둘 다 language, region, timeout를 수락하며, 제안도 location를 수락합니다. WebIQAsyncClient에서 await와 함께 동일한 메서드를 사용할 수 있습니다.

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에는 productId, skuId, 또는 offerId 중 적어도 하나가 필요합니다. fetchDetails에는 공백이 아닌 productId 또는 skuId가 필요하며, 일괄이 아니라 0개 또는 1개의 제품을 반환합니다. 둘 다 language, region, timeout 및 signal를 허용하며, offer도 location를 허용합니다. 검색 식별자 및 컬렉션은 선택 사항입니다.

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에는 하나 이상의 product_id, sku_id 또는 offer_id가 필요합니다. fetch_details에는 공백이 아닌 product_id 또는 sku_id가 필요하며, 일괄이 아니라 0개 또는 1개의 제품을 반환합니다. 두 옵션 작성기 모두 language, region, 및 timeout를 허용하며, 제안도 location를 허용합니다. 검색 식별자 및 컬렉션은 선택 사항입니다.

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 에는 하나 이상의 productId, skuId또는 offerId.가 필요합니다. fetchDetails에는 productId 또는 skuId 중 공백이 아닌 값이 필요하며, 배치가 아니라 0개 또는 1개의 제품을 반환합니다. 두 옵션 작성기 모두 language, region, 및 timeout를 허용하며, 제안도 location를 허용합니다. 검색 식별자 및 컬렉션은 선택 사항입니다.

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 및 FetchOffersAsync에는 productId, skuId 또는 offerId 중 하나 이상이 필요합니다. FetchDetails 및 FetchDetailsAsync에는 공백이 아닌 skuId 또는 productId가 필요하며, 배치가 아니라 0개 또는 1개의 제품을 반환합니다. 둘 다 Language 및 configure에 대한 Region 콜백과 시간 제한 및 취소 매개 변수를 허용하며, offer도 Location를 지원합니다. 검색 식별자 및 컬렉션은 선택 사항입니다.

범위

웹 검색 및 뉴스는 해당 범위의 포함 및 제외 규칙을 사용하여 결과를 필터링하기 위해 만든 범위의 이름을 허용합니다. your-scope-name를 범위 이름으로 바꿉니다. 설정 및 동작은 범위를 사용하여 결과 필터링을 참조하세요.

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

비동기 지원

애플리케이션에 여러 결과 형식이 필요한 경우 동시에 독립적인 요청을 실행합니다.

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 클라이언트

프록시, TLS 또는 연결 풀링 구성에 사용자 지정 HTTP 클라이언트를 사용합니다. 인증서 확인을 비활성화하지 마세요.

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를 전달합니다. AbortSignal를 유지하여 SDK의 헤더, 본문 및 내부 init가 전달되도록 합니다.

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

WebIqClient::builder().http_client(...)에 구성된 reqwest::Client을 전달합니다. 애플리케이션이 이 클라이언트를 직접 생성하는 경우 reqwest를 SDK와 호환되는 버전의 직접 종속성으로 추가합니다.

WebIQClientOptions.builder().httpClient(...)를 통해 구성된 java.net.http.HttpClient를 전달합니다. SDK는 호출자 소유 클라이언트를 닫지 않습니다. 애플리케이션에서 해당 클라이언트의 수명 주기를 관리합니다.

HttpClient을 WebIQClientOptions.HttpClient을 통해 전달합니다. SDK는 호출자 소유 HTTP 클라이언트를 삭제하거나 해제하지 않습니다. 애플리케이션에서 해당 수명을 관리합니다.

취소

비동기 요청의 경우 asyncio 작업 취소를 사용하거나, 재시도 대기를 포함하는 경과 시간 예산을 적용하려면 asyncio.timeout를 사용합니다. 요청당 SDK 시간 제한은 각 HTTP 시도를 제한합니다.

모든 리소스 메서드는 options.signal부터 AbortSignal까지 허용합니다. 중단하면 진행 중인 요청이 취소되고 다시 시도 대기가 취소됩니다. 신호의 이유는 변경되지 않은 상태로 다시 throw됩니다.

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

원격 분석 필드는 error, elapsed_ms, request_id, retry_after, trace_id, error_body, status_code, attempt를 포함해 snake_case를 사용합니다.

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

원격 분석 필드는 retryAfter, elapsedMs, requestId, error, traceId, attempt, errorBody, 및 statusCode를 포함해 camelCase를 사용합니다.

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

전체 서버 오류 응답(errorCategory, APIStatusError.body, traceId, retryAfter, technicalDetails 포함)을 보려면 errorCode를 검사합니다.

모든 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;
  }
}

전체 서버 오류 응답(errorCategory, APIStatusError.body, traceId, retryAfter, technicalDetails 포함)을 보려면 errorCode를 검사합니다.

호출은 반환합니다 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(), user_message(), error_code(), technical_details(), 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(), getErrorCode(), getUserMessage(), 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를 사용합니다.
  • 원격 분석을 사용하여 시도, 응답 코드 및 경과 시간을 연관시킵니다.
  • 오류를 다시 시도할 수 있는 것으로 처리하기 전에 구조적 오류 본문을 검사합니다. 오류 처리를 참조하세요.
  • 검색 결과를 표시하거나 인용할 때 클릭 및 인용 계측 을 추가합니다.