Microsoft Web IQ SDK は、自動車、Web、ニュース、ビデオ、画像、場所の検索、コマース、および Browse 用の型指定されたクライアントを提供します。 このページの上部にある言語を選択すると、すべてのインストール コマンドと例が一緒に切り替わります。
これらの例では、typed evidence と result-scoped citations を備えた Auto search 向けの公開 1.2.1 SDK リリースを使用します。 以前のバージョンの SDK を実行する前にアップグレードしてください。
| Property | Python | TypeScript | Rust | Java | .NET |
|---|---|---|---|---|---|
| 梱包 | 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 |
| ランタイム | 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
クイック スタート
例を実行する前に、WEBIQ_API_KEY 環境変数をご自身の API キーの値に設定します。 ソース コードに API キーを配置しないでください。
この例では、試行ごとに 60 秒のタイムアウトで advanced モードで Auto を呼び出し、各証拠の結果をサポートする引用文献と共に出力した後、Web、ニュース、ビデオ、画像、および場所検索を呼び出し、Browse でページを取得します。 Auto では、生成された最終的な回答ではなく、証拠が返されます。 証拠の種類と要求オプションについては、Auto referenceを参照してください。
Web、News、Browse のリクエスト パッセージは、グラウンディングに推奨される形式です。 また、Browse には、最大 1,000 文字の空でない選択 query も必要です。 ドキュメント全体の形式については、「コンテンツ形式」を参照してください。
import os
from webiq import WebIQClient
from webiq.types import BrowseContentFormat, ContentFormat, AutoMode
with WebIQClient(api_key=os.environ["WEBIQ_API_KEY"]) as client:
evidence = client.auto.search(
"What are the latest developments in retrieval-augmented generation?",
mode=AutoMode.advanced,
max_response_length=30000,
max_citations=5,
timeout=60.0,
)
for result in evidence.results or []:
print(result.evidence)
for citation in result.citations or []:
print(citation.title, citation.url)
web = client.web.search(
"Microsoft Web IQ",
max_results=5,
content_format=ContentFormat.passage,
)
for result in web.webResults or []:
print(result.title, result.url)
news = client.news.search(
"technology",
max_results=5,
content_format=ContentFormat.passage,
)
for item in news.newsResults or []:
print(item.title, item.source)
videos = client.videos.search("machine learning tutorial", max_results=5)
for video in videos.videoResults or []:
print(video.title, video.length)
images = client.images.search("golden gate bridge", max_results=5)
for image in images.imageResults or []:
print(image.title, image.url)
places = client.places.search(
"coffee in Seattle",
max_results=5,
language="en",
region="US",
location="lat:47.6062;long:-122.3321",
)
for place in places.placeResults or []:
print(place.name, place.businessUrl)
page = client.browse.fetch(
"https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
query="How fast is Web IQ",
content_format=BrowseContentFormat.passage,
max_length=3000,
live_crawl="fallback",
)
print(page.content)
import { WebIQClient, BrowseContentFormat, ContentFormat, LiveCrawlMode, AutoMode } from '@microsoft/webiq';
async function main() {
const apiKey = process.env.WEBIQ_API_KEY;
if (!apiKey) throw new Error('Set WEBIQ_API_KEY before running this example.');
const client = new WebIQClient({ apiKey });
try {
const evidence = await client.auto.search(
'What are the latest developments in retrieval-augmented generation?',
{ mode: AutoMode.ADVANCED, maxResponseLength: 30000, maxCitations: 5, timeout: 60_000 },
);
for (const result of evidence.results ?? []) {
console.log(result.evidence);
for (const citation of result.citations ?? []) console.log(citation.title, citation.url);
}
const web = await client.web.search('Microsoft Web IQ', {
maxResults: 5,
contentFormat: ContentFormat.PASSAGE,
});
for (const result of web.webResults ?? []) console.log(result.title, result.url);
const news = await client.news.search('technology', {
maxResults: 5,
contentFormat: ContentFormat.PASSAGE,
});
for (const item of news.newsResults ?? []) console.log(item.title, item.source);
const videos = await client.videos.search('machine learning tutorial', { maxResults: 5 });
for (const video of videos.videoResults ?? []) console.log(video.title, video.length);
const images = await client.images.search('golden gate bridge', { maxResults: 5 });
for (const image of images.imageResults ?? []) console.log(image.title, image.url);
const places = await client.places.search('coffee in Seattle', {
maxResults: 5,
language: 'en',
region: 'US',
location: 'lat:47.6062;long:-122.3321',
});
for (const place of places.placeResults ?? []) console.log(place.name, place.businessUrl);
const page = await client.browse.fetch('https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283', {
query: 'How fast is Web IQ',
contentFormat: BrowseContentFormat.PASSAGE,
maxLength: 3000,
liveCrawl: LiveCrawlMode.FALLBACK,
});
console.log(page.content);
} finally {
await client.close();
}
}
main().catch(console.error);
use webiq::{
AutoSearchOptions, BrowseContentFormat, BrowseOptions, ContentFormat, ImageSearchOptions,
LiveCrawlMode, NewsSearchOptions, PlacesSearchOptions, VideoSearchOptions,
AutoMode, WebIqClient, WebSearchOptions,
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = WebIqClient::new(std::env::var("WEBIQ_API_KEY")?)?;
let evidence = client.auto().search(
"What are the latest developments in retrieval-augmented generation?",
AutoSearchOptions::new()
.mode(AutoMode::Advanced)
.max_response_length(30000)
.max_citations(5)
.timeout(std::time::Duration::from_secs(60)),
).await?;
for result in evidence.results.unwrap_or_default() {
println!("{:?}", result.evidence);
for citation in result.citations.unwrap_or_default() {
println!("{:?} {:?}", citation.title, citation.url);
}
}
let web = client.web().search(
"Microsoft Web IQ",
WebSearchOptions::new()
.max_results(5)
.content_format(ContentFormat::Passage),
).await?;
for result in web.web_results.unwrap_or_default() {
println!("{:?} {:?}", result.title, result.url);
}
let news = client.news().search(
"technology",
NewsSearchOptions::new()
.max_results(5)
.content_format(ContentFormat::Passage),
).await?;
for item in news.news_results.unwrap_or_default() {
println!("{:?} {:?}", item.title, item.source);
}
let videos = client.videos().search(
"machine learning tutorial",
VideoSearchOptions::new().max_results(5),
).await?;
for video in videos.video_results.unwrap_or_default() {
println!("{:?} {:?}", video.title, video.length);
}
let images = client.images().search(
"golden gate bridge",
ImageSearchOptions::new().max_results(5),
).await?;
for image in images.image_results.unwrap_or_default() {
println!("{:?} {:?}", image.title, image.url);
}
let places = client.places().search(
"coffee in Seattle",
PlacesSearchOptions::new()
.max_results(5)
.language("en")
.region("US")
.location("lat:47.6062;long:-122.3321"),
).await?;
for place in places.place_results.unwrap_or_default() {
println!("{:?} {:?}", place.name, place.business_url);
}
let page = client.browse().fetch(
"https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
BrowseOptions::new()
.query("How fast is Web IQ")
.content_format(BrowseContentFormat::Passage)
.max_length(3000)
.live_crawl(LiveCrawlMode::Fallback),
).await?;
println!("{}", page.content.unwrap_or_default());
Ok(())
}
この例を Maven プロジェクトに src/main/java/WebIqSample.java として保存し、mvn compile exec:java -Dexec.mainClass=WebIqSample を実行します。
import com.microsoft.webiq.WebIQClient;
import com.microsoft.webiq.models.*;
import com.microsoft.webiq.resources.*;
public class WebIqSample {
public static void main(String[] args) {
try (WebIQClient client = WebIQClient.withApiKey(System.getenv("WEBIQ_API_KEY"))) {
SearchAutoEvidenceResponse evidence = client.auto.search(
"What are the latest developments in retrieval-augmented generation?",
AutoSearchOptions.builder().mode(AutoMode.ADVANCED)
.maxResponseLength(30000).maxCitations(5)
.timeout(java.time.Duration.ofSeconds(60)).build());
if (evidence.getResults() != null) {
for (AutoEvidenceResult result : evidence.getResults()) {
System.out.println(result.getEvidence());
if (result.getCitations() != null) {
for (AutoEvidenceCitation citation : result.getCitations()) {
System.out.println(citation.getTitle() + " " + citation.getUrl());
}
}
}
}
WebResponse web = client.web.search("Microsoft Web IQ",
WebSearchOptions.builder().maxResults(5)
.contentFormat(ContentFormat.PASSAGE).build());
if (web.getWebResults() != null) {
for (WebResult result : web.getWebResults()) {
System.out.println(result.getTitle() + " " + result.getUrl());
}
}
NewsResponse news = client.news.search("technology",
NewsSearchOptions.builder().maxResults(5)
.contentFormat(ContentFormat.PASSAGE).build());
if (news.getNewsResults() != null) {
for (NewsItem item : news.getNewsResults()) {
System.out.println(item.getTitle() + " " + item.getSource());
}
}
VideosResponse videos = client.videos.search("machine learning tutorial",
VideosSearchOptions.builder().maxResults(5).build());
if (videos.getVideoResults() != null) {
for (VideoItem video : videos.getVideoResults()) {
System.out.println(video.getTitle() + " " + video.getLength());
}
}
ImagesResponse images = client.images.search("golden gate bridge",
ImagesSearchOptions.builder().maxResults(5).build());
if (images.getImageResults() != null) {
for (ImageItem image : images.getImageResults()) {
System.out.println(image.getTitle() + " " + image.getUrl());
}
}
PlacesResponse places = client.places.search("coffee in Seattle",
PlacesSearchOptions.builder().maxResults(5)
.language("en").region("US")
.location("lat:47.6062;long:-122.3321").build());
if (places.getPlaceResults() != null) {
for (PlaceItem place : places.getPlaceResults()) {
System.out.println(place.getName() + " " + place.getBusinessUrl());
}
}
BrowseResponse page = client.browse.fetch("https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
BrowseFetchOptions.builder()
.query("How fast is Web IQ")
.contentFormat(BrowseContentFormat.PASSAGE)
.maxLength(3000).liveCrawl(LiveCrawlMode.FALLBACK).build());
System.out.println(page.getContent());
}
}
}
using Microsoft.WebIQ;
using Microsoft.WebIQ.Models;
using System.Text.Json;
string apiKey = Environment.GetEnvironmentVariable("WEBIQ_API_KEY")
?? throw new InvalidOperationException("Set WEBIQ_API_KEY before running this example.");
using var client = new WebIQClient(apiKey);
var evidence = await client.Auto.SearchAsync(
"What are the latest developments in retrieval-augmented generation?",
request =>
{
request.Mode = AutoMode.Advanced;
request.MaxResponseLength = 30000;
request.MaxCitations = 5;
}, timeout: TimeSpan.FromSeconds(60));
foreach (var result in evidence.Results ?? [])
{
Console.WriteLine(JsonSerializer.Serialize(result.Evidence));
foreach (var citation in result.Citations ?? [])
Console.WriteLine($"{citation.Title} {citation.Url}");
}
var web = await client.Web.SearchAsync("Microsoft Web IQ", request =>
{
request.MaxResults = 5;
request.ContentFormat = ContentFormat.Passage;
});
foreach (var result in web.WebResults ?? [])
Console.WriteLine($"{result.Title} {result.Url}");
var news = await client.News.SearchAsync("technology", request =>
{
request.MaxResults = 5;
request.ContentFormat = ContentFormat.Passage;
});
foreach (var item in news.NewsResults ?? [])
Console.WriteLine($"{item.Title} {item.Source}");
var videos = await client.Videos.SearchAsync("machine learning tutorial",
request => request.MaxResults = 5);
foreach (var video in videos.VideoResults ?? [])
Console.WriteLine($"{video.Title} {video.Length}");
var images = await client.Images.SearchAsync("golden gate bridge",
request => request.MaxResults = 5);
foreach (var image in images.ImageResults ?? [])
Console.WriteLine($"{image.Title} {image.Url}");
var places = await client.Places.SearchAsync("coffee in Seattle", request =>
{
request.MaxResults = 5;
request.Language = "en";
request.Region = "US";
request.Location = "lat:47.6062;long:-122.3321";
});
foreach (var place in places.PlaceResults ?? [])
Console.WriteLine($"{place.Name} {place.BusinessUrl}");
var page = await client.Browse.FetchAsync("https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
request =>
{
request.ContentFormat = BrowseContentFormat.Passage;
request.Query = "How fast is Web IQ";
request.MaxLength = 3000;
request.LiveCrawl = LiveCrawlMode.Fallback;
});
Console.WriteLine(page.Content);
Microsoft Entra ID 認証
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);
ホストされているアプリケーションの場合は、WorkloadIdentityCredentialからwebiq::azure_identityまたはManagedIdentityCredentialを選択します。
プロジェクトのAzure SDK依存関係と互換性のあるバージョンを使用して、Maven または Gradle の依存関係にcom.azure:azure-identityを追加します。
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 | メソッド | リファレンス |
|---|---|---|
| Auto | client.auto.search(query, ...) |
自動 |
| Web | client.web.search(query, ...) |
Web 検索 |
| News | client.news.search(query, ...) |
ニュース検索 |
| Videos | client.videos.search(query, ...) |
ビデオ検索 |
| 画像 | client.images.search(query, ...) |
画像検索 |
| 場所 | client.places.search(query, ...) |
プレイス |
| ブラウズ | client.browse.fetch(url, ...) |
ブラウズ |
| コマース検索 | client.commerce.search(query, ...) |
コマース |
| Commerce オファー | 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 | メソッド | リファレンス |
|---|---|---|
| Auto | client.auto.search(query, options) |
自動 |
| Web | client.web.search(query, options) |
Web 検索 |
| News | client.news.search(query, options) |
ニュース検索 |
| Videos | client.videos.search(query, options) |
ビデオ検索 |
| 画像 | 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 が使用されます。 2 番目の引数としてオプションを渡します。 クイック スタートに示すように、サポートされている値には SDK 列挙型を使用します。
残りのスニペットは、クライアントを明示的に構築しない限り、開いている client を想定し、非同期関数内で実行します。 最上位レベルの await には ES モジュールが必要です。
| Resource | メソッド | リファレンス |
|---|---|---|
| Auto | client.auto().search(query, options) |
自動 |
| Web | client.web().search(query, options) |
Web 検索 |
| News | client.news().search(query, options) |
ニュース検索 |
| Videos | client.videos().search(query, options) |
ビデオ検索 |
| 画像 | client.images().search(query, options) |
画像検索 |
| 場所 | client.places().search(query, options) |
プレイス |
| ブラウズ | client.browse().fetch(url, options) |
ブラウズ |
| コマース検索 | client.commerce().search(query, options) |
コマース |
| Commerce オファー | client.commerce().fetch_offers(options) |
コマース |
| コマース製品の詳細 | client.commerce().fetch_details(options) |
コマース |
AutoSearchOptions、WebSearchOptions、NewsSearchOptions、VideoSearchOptions、ImageSearchOptions、PlacesSearchOptions、BrowseOptions、CommerceSearchOptions、CommerceOffersOptions、またはCommerceDetailsOptionsを使用したビルド オプション。 応答フィールドはsnake_caseを使用し、省略可能な値は Optionを使用します。
残りのスニペットは、 Resultを返す非同期関数内で実行され、明示的に構築されない限り、開いている client が返されます。 クイックスタートのTokioランタイムセットアップを使用します。
| Resource | メソッド | リファレンス |
|---|---|---|
| Auto | client.auto.search(query, AutoSearchOptions) |
自動 |
| Web | client.web.search(query, WebSearchOptions) |
Web 検索 |
| News | client.news.search(query, NewsSearchOptions) |
ニュース検索 |
| Videos | client.videos.search(query, VideosSearchOptions) |
ビデオ検索 |
| 画像 | client.images.search(query, ImagesSearchOptions) |
画像検索 |
| 場所 | client.places.search(query, PlacesSearchOptions) |
プレイス |
| ブラウズ | client.browse.fetch(url, BrowseFetchOptions) |
ブラウズ |
| コマース検索 | client.commerce.search(query, CommerceSearchOptions) |
コマース |
| コマース特典 | client.commerce.fetchOffers(CommerceOffersOptions) |
コマース |
| Commerce 製品の詳細 | client.commerce.fetchDetails(CommerceDetailsOptions) |
コマース |
maxResults、contentFormat、maxLengthなどの camelCase ビルダー メソッドを使用して要求オプションをビルドします。
getWebResults()やgetTraceId()などの getter を使用して応答プロパティを読み取ります。 オプションの応答フィールドはnullできます。
残りのスニペットは、明示的に構築する場合を除き、開かれた状態の client 内でメソッドの中で実行されます。 Java ファイルの先頭にインポートを配置します。
| Resource | 非同期メソッド | リファレンス |
|---|---|---|
| Auto | client.Auto.SearchAsync(query, configure) |
自動 |
| Web | client.Web.SearchAsync(query, configure) |
Web 検索 |
| News | client.News.SearchAsync(query, configure) |
ニュース検索 |
| Videos | client.Videos.SearchAsync(query, configure) |
ビデオ検索 |
| 画像 | 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 リファレンスを参照してください。
コマース
Note
Commerce API はプライベート プレビュー段階であり、完全なドキュメント アクセス権を持つ AppID に含まれています。 Access は、検索、オファー、および製品の詳細に対して個別に有効になります。 Commerce APIs を使用してショッピング体験を構築するを参照してください。
製品を検索し、見つかった製品のオファーと製品の詳細を取得します。 オファーを表示する場合は、その 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 には、少なくとも 1 つの 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 には、少なくとも 1 つの productId、 skuId、または offerIdが必要です。
fetchDetails には、空白以外の productId または skuId が必要であり、バッチではなく 0 個または 1 つの積が返されます。 どちらも language、region、timeout、signal を受け入れ、オファーは 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 には、少なくとも 1 つの 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 には、少なくとも 1 つの 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には、少なくとも 1 つのproductId、skuId、またはofferIdが必要です。
FetchDetails
FetchDetailsAsyncは空白以外のproductIdまたはskuIdを必要とし、バッチではなくゼロまたは 1 つの製品を返します。 どちらも、LanguageとRegionのconfigureコールバックに加えて、タイムアウトパラメーターとキャンセル パラメーターを受け入れます。また、Locationもサポートしています。 検索識別子とコレクションは省略可能です。
Scopes
Web 検索とニュースでは、作成したスコープ名を指定でき、そのスコープの包含ルールと除外ルールを使用して結果をフィルター処理できます。
スコープ名で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 を最大 2 回再試行し、指数バックオフとジッターを使用します。 応答本文の有効な 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 クライアントを自分で閉じます。 非同期要求にはWebIQAsyncClientとともにhttpx.AsyncClientを使用します。
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を渡します。 SDK のヘッダー、本文、および内部initが転送されるように、AbortSignalを保持します。
import { ProxyAgent } from 'undici';
import { WebIQClient } from '@microsoft/webiq';
const proxyAgent = new ProxyAgent('http://proxy:8080');
const client = new WebIQClient({
apiKey: process.env.WEBIQ_API_KEY,
fetchFn: (url, init) => {
const options = { ...init, dispatcher: proxyAgent };
return fetch(url, options);
},
});
try {
const response = await client.web.search('Microsoft Web IQ');
console.log(response.webResults);
} finally {
await client.close();
await proxyAgent.close();
}
構成された reqwest::Client を WebIqClient::builder().http_client(...)に渡します。 アプリケーションがこのクライアントを直接構築する場合は、SDK と互換性のあるバージョンとの直接の依存関係として reqwest を追加します。
構成された java.net.http.HttpClient を WebIQClientOptions.builder().httpClient(...)経由で渡します。 SDK は、呼び出し元が所有するクライアントを閉じません。そのライフタイムはアプリケーション側で管理してください。
WebIQClientOptions.HttpClient を HttpClient を通して渡します。 SDK では、呼び出し元が所有する HTTP クライアントは破棄されません。アプリケーションでその有効期間を管理してください。
キャンセル
非同期要求の場合は、asyncio タスクの取り消しまたは asyncio.timeout を使用して、再試行待機を含む経過時間の上限を適用します。 要求ごとの SDK タイムアウトでは、各 HTTP 試行が制限されます。
すべてのリソースメソッドは、options.signal から AbortSignal までを受け付けます。 中止すると、実行中の要求が取り消され、再試行までの待機も取り消されます。信号の理由は変更されずに再スローされます。
const response = await client.web.search('Microsoft Web IQ', {
signal: AbortSignal.timeout(5_000),
});
受信要求の信号とウォール クロック制限を組み合わせるには、 AbortSignal.any([request.signal, AbortSignal.timeout(5_000)])を使用します。
再試行待機を含め、操作を中断するために、リクエスト future を取り消すか破棄します。 アプリケーションのデッドラインには、Tokio time utilities を使用し、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 とトレース 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")
テレメトリ フィールドでは、 attempt、 status_code、 request_id、 trace_id、 retry_after、 elapsed_ms、 error、 error_bodyなどの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();
}
テレメトリ フィールドでは、 attempt、 statusCode、 requestId、 traceId、 retryAfter、 elapsedMs、 error、 errorBodyなど、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");
エラー処理
一時的なエラーとは別に、認証、アクセス許可、レート制限のエラーを処理します。 SDK の再試行なしで、HTTP 429 と 430 がすぐに発生します。 返された再試行ガイダンスを使用して、再試行するタイミングを決定します。
すべての SDK 例外は、 WebIQErrorから継承されます。 HTTP エラーは AuthenticationError を継承し、これには PermissionDeniedError、RateLimitError、APIStatusError が含まれます。 ネットワークの障害とタイムアウトにより、 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}")
errorCode、technicalDetails、retryAfter、traceId、APIStatusError.body などを含む完全なサーバー エラー応答については、errorCategory を調べます。
すべての SDK エラーは、 WebIQErrorから継承されます。 HTTP エラーは AuthenticationError を継承し、これには PermissionDeniedError、RateLimitError、APIStatusError が含まれます。 ネットワークの障害とタイムアウトにより、 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;
}
}
errorCode、technicalDetails、retryAfter、traceId、APIStatusError.body などを含む完全なサーバー エラー応答については、errorCategory を調べます。
呼び出しは Result<T, WebIqError>を返します。 API エラーで照合するか、エラー アクセサーで構造化された診断を調べます。
use webiq::WebIqError;
match client.web().search("Microsoft Web IQ", Default::default()).await {
Ok(response) => println!("{:?}", response.web_results),
Err(WebIqError::Authentication(details)) => eprintln!("401: {}", details.message),
Err(WebIqError::PermissionDenied(details)) => eprintln!("403: {}", details.message),
Err(WebIqError::RateLimit(details)) => {
eprintln!("Rate limited; retry after: {:?}", details.retry_after());
}
Err(error) => {
eprintln!("{error}");
eprintln!("Code: {:?}, trace: {:?}", error.error_code(), error.trace_id());
}
}
API エラーは、 status_code()、 error_category()、 error_code()、 user_message()、 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応答には、"encumbrance"(例: truncationReason)を含めることができます。
デバッグと次の手順
- サポートに問い合わせるときに
traceIdを含めてください。 Rust はtrace_idを使用し、JavaはgetTraceId()を使用し、.NETはTraceIdを使用します。 - テレメトリを使用して、試行、応答コード、経過時間を関連付けます。
- エラーを再試行可能として扱う前に、構造化エラー本文を検査します。 エラー 処理を参照してください。
- 検索結果を表示または引用するときに 、クリックと引用のインストルメンテーション を追加します。