クイック スタート: 初めての Web IQ API 呼び出しを行う

数分で初めてのMicrosoft Web IQ API 呼び出しを行います。 Web を検索し、応答を検査し、既知の URL からクエリに重点を置いた抜粋を抽出します。 その他の例では、Places Search と Auto エビデンス取得を示します。

Web IQ リソースがまだない場合は、続行する前にAzure ポータルまたはAzure CLIを使用して作成してください。

このページの上部にある SDK または REST の例を選択して、すべての例をまとめて切り替えます。 SDKは、認証、再試行、レスポンス形式に自動的に対応します。

API キーは、Web IQ を評価する最速の方法です。 運用ワークロードの場合は、Microsoft Entra IDを使用します。

Prerequisites

Note

アプリケーションが中国で実行されている場合、検索エンドポイントにはhttps://api.microsoftol.com/v3ではなくhttps://api.microsoft.ai/v3を呼び出します。 REST の例では、URL を置き換えます。 SDK クライアントを構築する場合は、Pythonのbase_url引数、TypeScript のbaseUrl オプション、Rust のWebIqClient::builder().base_url(...)、JavaのWebIQClientOptions.builder().baseUrl(...)、または.NETのWebIQClientOptions.BaseUrlプロパティを使用して、同じベース URL を設定します。 Base URLを参照してください。

ヒント

コードなしでガイド付きスタートを希望しますか? Web IQ 開発者ポータルで 作業を開始 する: アプリ プロファイルの選択、API キーの作成、 Playground からの要求の送信、生成されたコードのコピー、使用状況の確認を行います。

1. API キーを格納する

要求の例で繰り返されたり、ソース コードに配置されたりしないように、キーを環境変数に配置してください。

macOS または Linux

export WEBIQ_API_KEY="your-api-key"

Windows PowerShell

$env:WEBIQ_API_KEY="your-api-key"

Warning

ソース管理にキーをコミットしたり、ブラウザーまたはクライアント側のコードで公開したりしないでください。 本番環境の認証情報をシークレット マネージャーに格納します。

2. Web を検索する

質問やクエリがあり、Web IQ に関連するページを検出してランク付けさせたい場合は、Web Search を使用します。

最適化された動作点として、すべての要求に maxResults = 10、contentFormat = passage、および maxLength = 3000 を設定することをお勧めします。 そこから、ユース ケースに基づいてこれらの設定を微調整できます。

エンドポイント:POST https://api.microsoft.ai/v3/search/web

curl --request POST "https://api.microsoft.ai/v3/search/web" \
  --header "x-apikey: $WEBIQ_API_KEY" \
  --header "content-type: application/json" \
  --data '{
    "query": "latest developments in retrieval augmented generation",
    "maxResults": 10,
    "contentFormat": "passage",
    "maxLength": 3000
  }'

python -m pip install webiq==1.2.1 (Python 3.11 以降) で SDK をインストールし、次を実行します。

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

with WebIQClient(api_key=os.environ["WEBIQ_API_KEY"]) as client:
    results = client.web.search(
        "latest developments in retrieval augmented generation",
        max_results=10,
        content_format=ContentFormat.passage,
        max_length=3000,
    )
    for result in results.webResults or []:
        print(result.title, result.url)

npm install @microsoft/webiq@1.2.1 (Node.js 22.x では 22.18 以降、または 24 以降) で SDK をインストールします。 この例を search.mts として保存し、 node search.mtsで実行します。

import { WebIQClient, ContentFormat } from "@microsoft/webiq";

async function main() {
  const client = new WebIQClient({ apiKey: process.env.WEBIQ_API_KEY });

  try {
    const results = await client.web.search(
      "latest developments in retrieval augmented generation",
      {
        maxResults: 10,
        contentFormat: ContentFormat.PASSAGE,
        maxLength: 3000,
      },
    );
    for (const result of results.webResults ?? []) {
      console.log(result.title, result.url);
    }
  } finally {
    await client.close();
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Rust 1.88 以降のプロジェクトで、 cargo add webiq@1.2.1 と cargo add tokio --features macros,rt-multi-threadを実行します。 この例を src/main.rs として保存して cargo run実行してください。

use webiq::{ContentFormat, WebIqClient, WebSearchOptions};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = WebIqClient::new(std::env::var("WEBIQ_API_KEY")?)?;
    let results = client.web().search(
        "latest developments in retrieval augmented generation",
        WebSearchOptions::new()
            .max_results(10)
            .content_format(ContentFormat::Passage)
            .max_length(3000),
    ).await?;
    for result in results.web_results.unwrap_or_default() {
        println!("{:?} {:?}", result.title, result.url);
    }
    Ok(())
}

Java 11 以降用に構成された Maven プロジェクトで、この依存関係をpom.xmlに追加します。

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

この例を src/main/java/Search.java として保存して mvn compile exec:java -Dexec.mainClass=Search実行してください。

import com.microsoft.webiq.WebIQClient;
import com.microsoft.webiq.models.ContentFormat;
import com.microsoft.webiq.models.WebResponse;
import com.microsoft.webiq.models.WebResult;
import com.microsoft.webiq.resources.WebSearchOptions;

public class Search {
    public static void main(String[] args) {
        try (WebIQClient client = WebIQClient.withApiKey(System.getenv("WEBIQ_API_KEY"))) {
            WebResponse results = client.web.search(
                    "latest developments in retrieval augmented generation",
                    WebSearchOptions.builder()
                            .maxResults(10)
                            .contentFormat(ContentFormat.PASSAGE)
                            .maxLength(3000)
                            .build());
            if (results.getWebResults() != null) {
                for (WebResult result : results.getWebResults()) {
                    System.out.println(result.getTitle() + " " + result.getUrl());
                }
            }
        }
    }
}

.NET 8 以降のコンソール プロジェクトで、dotnet add package Microsoft.WebIQ --version 1.2.1を実行します。 この例を Program.cs として保存して dotnet run実行してください。

using Microsoft.WebIQ;
using Microsoft.WebIQ.Models;

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

var results = await client.Web.SearchAsync(
    "latest developments in retrieval augmented generation",
    request =>
    {
        request.MaxResults = 10;
        request.ContentFormat = ContentFormat.Passage;
        request.MaxLength = 3000;
    });
foreach (var result in results.WebResults ?? [])
    Console.WriteLine($"{result.Title} {result.Url}");
import os
import json
import requests

response = requests.post(
    "https://api.microsoft.ai/v3/search/web",
    headers={
        "x-apikey": os.environ["WEBIQ_API_KEY"],
        "content-type": "application/json",
    },
    json={
        "query": "latest developments in retrieval augmented generation",
        "maxResults": 10,
        "contentFormat": "passage",
        "maxLength": 3000,
    },
    timeout=30,
)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))

この例を search.mjs として保存し、 node search.mjsで実行します。

const response = await fetch("https://api.microsoft.ai/v3/search/web", {
  method: "POST",
  headers: {
    "x-apikey": process.env.WEBIQ_API_KEY,
    "content-type": "application/json",
  },
  body: JSON.stringify({
    query: "latest developments in retrieval augmented generation",
    maxResults: 10,
    contentFormat: "passage",
    maxLength: 3000,
  }),
});

if (!response.ok) {
  throw new Error(`Web Search failed: ${response.status} ${await response.text()}`);
}

console.log(JSON.stringify(await response.json(), null, 2));

3. 応答を理解する

Web Search が成功すると、 webResults 配列が返されます。 この簡略化した例は、最も頻繁に使用するフィールドを示しています。

{
  "webResults": [
    {
      "title": "Example result",
      "url": "https://example.com/article",
      "content": "The query-relevant passage extracted from the page...",
      "crawledAt": "2026-07-18T12:00:00Z"
    }
  ],
  "traceId": "00000000000000000000000000000000"
}
  • title と url はソースを識別します。
  • content には、要求で contentFormat: "passage" が使用されているため、クエリ関連の一節が含まれています。
  • traceId は、Web IQ サポートがリクエストを調査するのに役立ちます。

REST 応答と MCP ツールの結果では、入れ子になった結果オブジェクトのフィールドを含む、 null または空の文字列 ("") 値を持つモデル フィールドは省略されます。空のリスト/配列 ([]) フィールドは保持されます。ただし、リスト フィールドも存在しない場合があります。 存在しないフィールドは使用不可として扱い、空または存在しないリストはアイテムを持たないものとして扱います。 空白のみの文字列、 false、 0、空のディクショナリ、個々の配列/ディクショナリ エントリ、埋め込み生 JSON は保持されます。 ルート配列と MCP content のようなプロトコル エンベロープ コレクションは変更されません。

すべてのパラメーターと応答フィールドについては、 Web Search API リファレンスを参照 してください。

4. エンドポイントを選択する

次から開始 Use 受け取るもの
質問または検索クエリ Web 検索 クエリに関連するコンテンツを含むランク付けされたページ
特定の URL ブラウズ そのページから抽出されたコンテンツ
場所またはローカル ビジネス のクエリ 場所 住所や営業時間などの構造化された場所の詳細
自動的に選択された回答タイプが必要なクエリ REST または SDK 1.2.1 以降でのAuto 結果範囲の引用を含む型付きのエビデンス
ショッピングまたは製品のクエリ コマース(プライベート プレビュー) через REST 販売者のオファー、価格、および製品の詳細を含むランク付けされた製品

一般的な基礎ワークフローでは、両方のエンドポイントを使用します。関連するソースを検索し、結果の URL を選択してから、その URL を参照して、フォローアップの質問に関連する箇所を抽出します。

5. URL からコンテンツを抽出する

読みたいページがすでにわかっている場合は、[Browse] を使用します。 contentFormatをpassageに設定し、質問に最も関連するページの部分を取得する非空白のqueryを指定します。

liveCrawl: "fallback" は、ページがインデックスにまだ登録されていない場合に、ページをクロールするように Web IQ に要求します。 ライブ クロールは、発行元のクロール制限と可用性の対象となります。fallbackでは、実際のクロールは保証されません。

すべての例では、グラウンディングに推奨される形式であるクエリに重点を置いた一節を要求します。 選択 query は空白ではなく、1000 文字以下にする必要があります。 maxLength は、返されるコンテンツの量を個別に制御します。 完全ドキュメント形式 (text、 html、および markdown) には、 完全なドキュメント アクセスが必要です。

エンドポイント:POST https://api.microsoft.ai/v3/browse

curl --request POST "https://api.microsoft.ai/v3/browse" \
  --header "x-apikey: $WEBIQ_API_KEY" \
  --header "content-type: application/json" \
  --data '{
    "url": "https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
    "query": "How fast is Web IQ",
    "contentFormat": "passage",
    "maxLength": 3000,
    "liveCrawl": "fallback"
  }'

python -m pip install webiq==1.2.1 (Python 3.11 以降) で SDK をインストールし、次を実行します。

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

with WebIQClient(api_key=os.environ["WEBIQ_API_KEY"]) as client:
    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)

npm install @microsoft/webiq@1.2.1 (Node.js 22.x では 22.18 以降、または 24 以降) で SDK をインストールします。 この例を browse.mts として保存し、 node browse.mtsで実行します。

import { WebIQClient, BrowseContentFormat, LiveCrawlMode } from "@microsoft/webiq";

async function main() {
  const client = new WebIQClient({ apiKey: process.env.WEBIQ_API_KEY });

  try {
    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(JSON.stringify(page, null, 2));
  } finally {
    await client.close();
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Rust 1.88 以降のプロジェクトで、 cargo add webiq@1.2.1 と cargo add tokio --features macros,rt-multi-threadを実行します。 この例を src/main.rs として保存して cargo run実行してください。

use webiq::{BrowseContentFormat, BrowseOptions, LiveCrawlMode, WebIqClient};

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

Java 11 以降用に構成された Maven プロジェクトで、この依存関係をpom.xmlに追加します。

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

この例を src/main/java/Browse.java として保存して mvn compile exec:java -Dexec.mainClass=Browse実行してください。

import com.microsoft.webiq.WebIQClient;
import com.microsoft.webiq.models.BrowseContentFormat;
import com.microsoft.webiq.models.BrowseResponse;
import com.microsoft.webiq.models.LiveCrawlMode;
import com.microsoft.webiq.resources.BrowseFetchOptions;

public class Browse {
    public static void main(String[] args) {
        try (WebIQClient client = WebIQClient.withApiKey(System.getenv("WEBIQ_API_KEY"))) {
            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());
        }
    }
}

.NET 8 以降のコンソール プロジェクトで、dotnet add package Microsoft.WebIQ --version 1.2.1を実行します。 この例を Program.cs として保存して dotnet run実行してください。

using Microsoft.WebIQ;
using Microsoft.WebIQ.Models;

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

var 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);
import os
import json
import requests

response = requests.post(
    "https://api.microsoft.ai/v3/browse",
    headers={
        "x-apikey": os.environ["WEBIQ_API_KEY"],
        "content-type": "application/json",
    },
    json={
        "url": "https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
        "query": "How fast is Web IQ",
        "contentFormat": "passage",
        "maxLength": 3000,
        "liveCrawl": "fallback",
    },
    timeout=30,
)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))

この例を browse.mjs として保存し、 node browse.mjsで実行します。

const response = await fetch("https://api.microsoft.ai/v3/browse", {
  method: "POST",
  headers: {
    "x-apikey": process.env.WEBIQ_API_KEY,
    "content-type": "application/json",
  },
  body: JSON.stringify({
    url: "https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
    query: "How fast is Web IQ",
    contentFormat: "passage",
    maxLength: 3000,
    liveCrawl: "fallback",
  }),
});

if (!response.ok) {
  throw new Error(`Browse failed: ${response.status} ${await response.text()}`);
}

console.log(JSON.stringify(await response.json(), null, 2));

成功した 200 応答には、ページ url、 title、抽出された content、および traceIdが含まれます。 ライブ クロールは、retryAfter(ISO 8601 UTC タイムスタンプ) を持つ202を返すことができます。その時刻まで待ってから、同じ要求を再度送信します。 完全な応答コントラクトについては、Browse API リファレンスを参照してください。

6. 場所を検索する (省略可能)

場所検索を使用して、地元の企業やその他の場所に関する構造化された情報を検索します。 SDK の例では、手順 2 でインストールした 1.2.1 パッケージを使用します。

エンドポイント:POST https://api.microsoft.ai/v3/search/places

curl --request POST "https://api.microsoft.ai/v3/search/places" \
  --header "x-apikey: $WEBIQ_API_KEY" \
  --header "content-type: application/json" \
  --data '{
    "query": "coffee in Seattle",
    "maxResults": 5,
    "language": "en",
    "region": "US",
    "location": "lat:47.6062;long:-122.3321"
  }'
import os
from webiq import WebIQClient

with WebIQClient(api_key=os.environ["WEBIQ_API_KEY"]) as client:
    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)

この例を places.mts として保存し、 node places.mtsで実行します。

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

async function main() {
  const client = new WebIQClient({ apiKey: process.env.WEBIQ_API_KEY });

  try {
    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);
    }
  } finally {
    await client.close();
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

手順2のTokioセットアップを使用します。 この例を src/main.rs として保存して cargo run実行してください。

use webiq::{PlacesSearchOptions, WebIqClient};

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

この例を手順 2 の Maven プロジェクトに src/main/java/Places.java として保存し、mvn compile exec:java -Dexec.mainClass=Placesを実行します。

import com.microsoft.webiq.WebIQClient;
import com.microsoft.webiq.models.PlaceItem;
import com.microsoft.webiq.models.PlacesResponse;
import com.microsoft.webiq.resources.PlacesSearchOptions;

public class Places {
    public static void main(String[] args) {
        try (WebIQClient client = WebIQClient.withApiKey(System.getenv("WEBIQ_API_KEY"))) {
            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());
                }
            }
        }
    }
}

手順 2 の .NET コンソール プロジェクトで、この例をProgram.csとして保存し、dotnet run実行します。

using Microsoft.WebIQ;

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 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}");
import os
import json
import requests

response = requests.post(
    "https://api.microsoft.ai/v3/search/places",
    headers={
        "x-apikey": os.environ["WEBIQ_API_KEY"],
        "content-type": "application/json",
    },
    json={
        "query": "coffee in Seattle",
        "maxResults": 5,
        "language": "en",
        "region": "US",
        "location": "lat:47.6062;long:-122.3321",
    },
    timeout=30,
)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))

この例を places.mjs として保存し、 node places.mjsで実行します。

const response = await fetch("https://api.microsoft.ai/v3/search/places", {
  method: "POST",
  headers: {
    "x-apikey": process.env.WEBIQ_API_KEY,
    "content-type": "application/json",
  },
  body: JSON.stringify({
    query: "coffee in Seattle",
    maxResults: 5,
    language: "en",
    region: "US",
    location: "lat:47.6062;long:-122.3321",
  }),
});

if (!response.ok) {
  throw new Error(`Places failed: ${response.status} ${await response.text()}`);
}

console.log(JSON.stringify(await response.json(), null, 2));

placeResultsから結果を読み取る。 リストと個々のフィールドは存在しない可能性があるため、住所、営業時間、その他の詳細を使用する前に欠損値を確認してください。 Places API リファレンスを参照してください。

7. Auto で証拠を取得する

Web IQ に検索ソースを選択させ、裏付けとなる引用と共に型指定された証拠を返したい場合は、[自動] を使用します。 日付、場所、単位などの関連する制約を維持しながら、完全な自然言語の質問をします。 これらの例では、mode を省略して既定値を使用し、リクエスト試行ごとに 60 秒を許可します。 複雑な質問に対してより包括的な検索が必要な場合は、mode を Auto Advanced の advanced に設定します。

自動では、生成された最終的な回答ではなく、アプリケーションで使用する根拠情報が返されます。 各エビデンス結果をそれぞれに固有の引用付きで読む;ある結果の引用文献を別の結果のサポートとして扱わない。 SDK の例では、手順 2 でインストールした 5 つの SDK すべてでバージョン 1.2.1 を使用します。

エンドポイント:POST https://api.microsoft.ai/v3/auto

curl --request POST "https://api.microsoft.ai/v3/auto" \
  --max-time 60 \
  --header "x-apikey: $WEBIQ_API_KEY" \
  --header "content-type: application/json" \
  --data '{
    "query": "What are the latest developments in retrieval-augmented generation?",
    "maxResponseLength": 30000,
    "maxCitations": 5
  }'
import os
from webiq import WebIQClient

with WebIQClient(api_key=os.environ["WEBIQ_API_KEY"]) as client:
    evidence = client.auto.search(
        "What are the latest developments in retrieval-augmented generation?",
        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)

この例を auto.mts として保存し、 node auto.mtsで実行します。

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

async function main() {
  const client = new WebIQClient({ apiKey: process.env.WEBIQ_API_KEY });

  try {
    const evidence = await client.auto.search(
      "What are the latest developments in retrieval-augmented generation?",
      { 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);
      }
    }
  } finally {
    await client.close();
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

手順2のTokioセットアップを使用します。 この例を src/main.rs として保存して cargo run実行してください。

use webiq::{AutoSearchOptions, WebIqClient};

#[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()
            .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);
        }
    }
    Ok(())
}

この例を手順 2 の Maven プロジェクトに src/main/java/Auto.java として保存し、mvn compile exec:java -Dexec.mainClass=Autoを実行します。

import com.microsoft.webiq.WebIQClient;
import com.microsoft.webiq.models.AutoEvidenceCitation;
import com.microsoft.webiq.models.AutoEvidenceResult;
import com.microsoft.webiq.models.SearchAutoEvidenceResponse;
import com.microsoft.webiq.resources.AutoSearchOptions;

public class Auto {
    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()
                            .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());
                        }
                    }
                }
            }
        }
    }
}

手順 2 の .NET コンソール プロジェクトで、この例をProgram.csとして保存し、dotnet run実行します。

using Microsoft.WebIQ;
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.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}");
}
import os
import json
import requests

response = requests.post(
    "https://api.microsoft.ai/v3/auto",
    headers={
        "x-apikey": os.environ["WEBIQ_API_KEY"],
        "content-type": "application/json",
    },
    json={
        "query": "What are the latest developments in retrieval-augmented generation?",
        "maxResponseLength": 30000,
        "maxCitations": 5,
    },
    timeout=60,
)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))

この例を auto.mjs として保存し、 node auto.mjsで実行します。

const response = await fetch("https://api.microsoft.ai/v3/auto", {
  method: "POST",
  signal: AbortSignal.timeout(60_000),
  headers: {
    "x-apikey": process.env.WEBIQ_API_KEY,
    "content-type": "application/json",
  },
  body: JSON.stringify({
    query: "What are the latest developments in retrieval-augmented generation?",
    maxResponseLength: 30000,
    maxCitations: 5,
  }),
});

if (!response.ok) {
  throw new Error(`Auto failed: ${response.status} ${await response.text()}`);
}

console.log(JSON.stringify(await response.json(), null, 2));

成功した応答には、 results 配列が含まれています。 各結果は、型指定された evidence オブジェクトとそれを裏付ける citations をペアにします。 空または存在しない results 配列には、処理する証拠がありません。 証拠の種類、応答の例、要求の制限については、 自動 API リファレンスを参照 してください。

8. Commerce を使用して製品を検索する (オプション)

コマース API を使用して、ショッピング クエリの製品と販売者のオファーを検索します。検索では、主要な販売者プランでランク付けされた製品が返され、オファーは 1 つの製品に対してより多くのオファーを返し、製品の詳細は製品のタイトル、説明、評価を返します。

Note

Commerce API はプライベート プレビュー段階であり、完全なドキュメント アクセス権を持つ AppID に含まれています。 アクセスは、エンドポイントごとに個別に有効になります。 AppID にそれらがない場合は、AppID で Web IQ サポート要求 (問題の種類 認証とアクセス) を開きます。

Endpoints:POST https://api.microsoft.ai/v3/search/commerce/products、 POST https://api.microsoft.ai/v3/fetch/commerce/products/offers、および POST https://api.microsoft.ai/v3/fetch/commerce/products/details

この手順では、REST 呼び出しを示します。 ページの上部にある cURL、Python (REST)、または JavaScript (REST) を選択すると表示されます。

製品を検索する:

curl --request POST "https://api.microsoft.ai/v3/search/commerce/products" \
  --header "x-apikey: $WEBIQ_API_KEY" \
  --header "content-type: application/json" \
  --data '{
    "query": "wireless headphones",
    "maxResults": 3,
    "language": "en",
    "region": "US"
  }'

応答の最初の製品から、その id、その skuId、および最初のオファーの id をコピーします。 以下の PRODUCT_ID、 SKU_ID、 OFFER_ID を置き換え、さらにオファーと製品の詳細を検索します。 一部の製品では、 id または skuIdなしでオファーのみが返されます。オファーは offerId のみを送信し、製品または SKU ID が必要な製品の詳細をスキップします。

curl --request POST "https://api.microsoft.ai/v3/fetch/commerce/products/offers" \
  --header "x-apikey: $WEBIQ_API_KEY" \
  --header "content-type: application/json" \
  --data '{
    "productId": "PRODUCT_ID",
    "skuId": "SKU_ID",
    "offerId": "OFFER_ID",
    "language": "en",
    "region": "US"
  }'

curl --request POST "https://api.microsoft.ai/v3/fetch/commerce/products/details" \
  --header "x-apikey: $WEBIQ_API_KEY" \
  --header "content-type: application/json" \
  --data '{
    "productId": "PRODUCT_ID",
    "skuId": "SKU_ID",
    "language": "en",
    "region": "US"
  }'
import json
import os
import requests

BASE_URL = "https://api.microsoft.ai/v3"
HEADERS = {
    "x-apikey": os.environ["WEBIQ_API_KEY"],
    "content-type": "application/json",
}
MARKET = {"language": "en", "region": "US"}


def post(path, body):
    response = requests.post(BASE_URL + path, headers=HEADERS, json=body, timeout=30)
    response.raise_for_status()
    return response.json()


search = post("/search/commerce/products", {"query": "wireless headphones", "maxResults": 3, **MARKET})
products = search.get("products") or []
if not products:
    print("No matching products.")
else:
    product = products[0]
    first_offer = (product.get("offers") or [{}])[0]
    ids = {"productId": product.get("id"), "skuId": product.get("skuId")}
    ids = {key: value for key, value in ids.items() if value}
    offer_ids = {**ids, "offerId": first_offer.get("id")} if first_offer.get("id") else ids

    offers = post("/fetch/commerce/products/offers", {**offer_ids, **MARKET})
    # Product Details needs a product id or SKU id; some products return only an offer.
    details = post("/fetch/commerce/products/details", {**ids, **MARKET}) if ids else None
    print(json.dumps({"product": product, "offers": offers, "details": details}, indent=2))

この例を commerce.mjs として保存し、 node commerce.mjsで実行します。

const baseUrl = "https://api.microsoft.ai/v3";
const headers = {
  "x-apikey": process.env.WEBIQ_API_KEY,
  "content-type": "application/json",
};
const market = { language: "en", region: "US" };

async function post(path, body) {
  const response = await fetch(`${baseUrl}${path}`, {
    method: "POST",
    headers,
    body: JSON.stringify(body),
  });
  if (!response.ok) {
    throw new Error(`${path} failed: ${response.status} ${await response.text()}`);
  }
  return response.json();
}

const search = await post("/search/commerce/products", {
  query: "wireless headphones",
  maxResults: 3,
  ...market,
});
const product = search.products?.[0];
if (!product) {
  console.log("No matching products.");
} else {
  const ids = {};
  if (product.id) ids.productId = product.id;
  if (product.skuId) ids.skuId = product.skuId;
  const offerId = product.offers?.[0]?.id;
  const offerIds = offerId ? { ...ids, offerId } : ids;

  const offers = await post("/fetch/commerce/products/offers", { ...offerIds, ...market });
  // Product Details needs a product id or SKU id; some products return only an offer.
  const details = Object.keys(ids).length
    ? await post("/fetch/commerce/products/details", { ...ids, ...market })
    : null;
  console.log(JSON.stringify({ product, offers, details }, null, 2));
}

検索は、各製品に主要出品者のオファーが付いた状態で、ランク順に製品を返します。 maxResults は、オファーではなく製品を制限します。 オファーでは、最初にプライマリ オファーが返され、その後に追加のオファーが返されます。 一致するものがない有効な要求は、空のoffersまたは200 OK配列を持つproductsを返します。 価格は通貨のマイナー単位の整数です。 39999 USD は $399.99 です。

ユーザーまたはユーザーに対応するエージェントをオファーに送信するには、その応答で返されたとおりにオファーの clickUrl を使用します。 マーチャントのみを識別する displayUrlは使用しないでください。リンクを書き換えたり、短縮したり、再利用したりしないでください。 モデルで再現するのではなく、アプリケーション コードでリンクをビルドします。 オファーのリンクと帰属表示およびコマース ガイドを参照してください。

Troubleshooting

Status 確認すべきこと
401 Unauthorized WEBIQ_API_KEYが設定されていることを確認し、リクエストがそれをx-apikeyヘッダーで送信することを確認します。
415 Unsupported Media Type content-type: application/jsonを送信。
429 Too Many Requests 再試行する前に待機し、リクエストの頻度を下げてください。
閲覧 404 Not Found URL がパブリックで有効であることを確認してください。 インデックス付きコンテンツが使用できない可能性がある場合は、 liveCrawl: "fallback" を使用します。
閲覧 202 Accepted retryAfter の時刻 (ISO 8601 UTC タイムスタンプ) まで待ってから、同じ要求をもう一度送信してください。
自動 403 Forbidden [プロファイル管理] の [許可されたサービス] に [Auto] が表示されていることを確認します。 そうでない場合は、AppID で Web IQ サポート要求 を開きます。

その他の障害については、traceId を保存し、「エラー処理」を参照してください。 Web IQ サポートに連絡するには、traceIdと AppID、または AppID がない場合は会社名と Web IQ リソースの名前を含めます。

次のステップ