Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Effettua la tua prima chiamata Microsoft Web IQ API in pochi minuti. Cerca nel Web, esamina la risposta ed estrai passaggi incentrati sulle query da un URL noto. Ulteriori esempi mostrano Places Search e il recupero automatico di evidenze.
Se non si dispone già di una risorsa IQ Web, crearne una utilizzando il portale di Azure, interfaccia della riga di comando di Azure o Terraform prima di continuare.
Scegliere un esempio SDK o REST nella parte superiore di questa pagina per cambiare tutti gli esempi insieme. Gli SDK gestiscono automaticamente l'autenticazione, i nuovi tentativi e i tipi di risposta.
Le chiavi API rappresentano il modo più rapido per valutare l'IQ Web. Per i carichi di lavoro di produzione, usare Microsoft Entra ID.
Prerequisites
- Una chiave API Web IQ da Gestione profili.
Note
Se l'applicazione viene eseguita in Cina, chiamare https://api.microsoftol.com/v3 anziché https://api.microsoft.ai/v3 per gli endpoint di ricerca. Negli esempi REST sostituire l'URL. Quando si costruisce un client SDK, impostare lo stesso URL di base con l'argomento base_url di Python, l'opzione baseUrl di TypeScript, WebIqClient::builder().base_url(...) di Rust, WebIQClientOptions.builder().baseUrl(...) di Java o la proprietà WebIQClientOptions.BaseUrl di .NET. Vedi URL di base.
Tip
Preferisce un avvio guidato senza codice? Seguire Introduzione al portale per sviluppatori di IQ Web: selezionare il profilo dell'app, creare una chiave API, inviare una richiesta da Playground, copiare il codice generato e controllare l'utilizzo.
1. Archiviare la chiave API
Inserire la chiave in una variabile di ambiente in modo che gli esempi di richiesta non la ripetano o la inseriscano nel codice sorgente.
macOS o Linux
export WEBIQ_API_KEY="your-api-key"
Windows PowerShell
$env:WEBIQ_API_KEY="your-api-key"
Warning
Non eseguire il commit della chiave nel controllo del codice sorgente né esporla nel browser o nel codice lato client. Memorizza le credenziali di produzione in un Secret Manager.
2. Cerca nel Web
Usare Ricerca Web quando si ha una domanda o una query e si vuole che L'IQ Web rilevi e classifica le pagine pertinenti.
È consigliabile impostare maxResults = 10, contentFormat = passagee maxLength = 3000 su ogni richiesta come punto operativo ottimizzato. Da qui è possibile ottimizzare queste impostazioni in base al caso d'uso.
Endpoint: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
}'
Installare l'SDK con python -m pip install webiq==1.2.1 (Python 3.11 o versione successiva), quindi eseguire:
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)
Installare l'SDK con npm install @microsoft/webiq@1.2.1 (Node.js 22.18+ su 22.x o 24+). Salvare questo esempio come search.mts ed eseguirlo con 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;
});
In un progetto Rust 1.88 o versione successiva eseguire cargo add webiq@1.2.1 e cargo add tokio --features macros,rt-multi-thread. Salva questo esempio come src/main.rs e esegui 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(())
}
In un progetto Maven configurato per Java 11 o versione successiva aggiungere questa dipendenza a pom.xml:
<dependency>
<groupId>com.microsoft.webiq</groupId>
<artifactId>webiq</artifactId>
<version>1.2.1</version>
</dependency>
Salva questo esempio come src/main/java/Search.java e esegui 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());
}
}
}
}
}
In un progetto console di .NET 8 o versione successiva eseguire dotnet add package Microsoft.WebIQ --version 1.2.1. Salva questo esempio come Program.cs e esegui 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))
Salvare questo esempio come search.mjs ed eseguirlo con 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. Comprendere la risposta
Una ricerca Web riuscita restituisce un webResults array. Questo esempio abbreviato mostra i campi che verranno usati più spesso:
{
"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"
}
-
titleeurlidentificano l'origine. -
contentcontiene il passaggio rilevante per la query perché la richiesta ha usatocontentFormat: "passage". -
traceIdaiuta Web IQ Support a esaminare una richiesta.
Tra le risposte REST e i risultati degli strumenti MCP, i campi del modello con null o valori stringa vuota ("") vengono omessi, inclusi i campi dei risultati annidati; i campi list/array vuoti ([]) vengono mantenuti, tranne in Places, in cui i campi elenco possono anche essere assenti. Considera un campo assente come non disponibile e un elenco vuoto o assente come senza elementi. Vengono mantenute stringhe contenenti solo spazi, false, 0, dizionari vuoti, singole voci di matrice/dizionario e JSON non elaborato incorporato. Le matrici radice e le collezioni protocol-envelope, ad esempio MCP content, sono invariate.
Vedere le informazioni di riferimento sull'API Ricerca Web per tutti i parametri e i campi di risposta.
4. Scegliere un endpoint
| Avvia con | Utilizza | Cosa ottieni |
|---|---|---|
| Una domanda o una query di ricerca | Ricerca Web | Pagine classificate con contenuto pertinente per le query |
| un URL specifico | Sfoglia | Contenuto estratto da tale pagina |
| Una query di luogo o attività locale | Luoghi | Dettagli strutturati dei luoghi, ad esempio indirizzi e orari di apertura |
| Una query che richiede tipi di risposta selezionati automaticamente | Auto tramite REST o gli SDK dalla versione 1.2.1 in poi | Prove tipizzate con citazioni riferite al singolo risultato |
| Una query di shopping o prodotto | Commerce (anteprima privata) tramite REST | Prodotti classificati con offerte, prezzi e dettagli del prodotto |
Un flusso di lavoro di base comune usa entrambi gli endpoint: cercare le fonti pertinenti, selezionare un URL dei risultati, quindi esplorare tale URL per estrarre i passaggi rilevanti per una domanda di approfondimento.
5. Estrarre il contenuto da un URL
Usare Sfoglia quando si conosce già la pagina da leggere. Impostare contentFormat su passage e specificare un valore non query semplice per recuperare le parti della pagina più rilevanti per la domanda.
liveCrawl: "fallback" chiede a Web IQ di eseguire la scansione della pagina quando non è già disponibile nell'indice. La scansione in tempo reale è soggetta a restrizioni di cortesia e disponibilità dell'editore; fallback non garantisce una scansione effettiva.
Tutti gli esempi richiedono passaggi pertinenti incentrati sulla query, il formato consigliato per il grounding. La selezione query deve essere diversa da 1000 caratteri e maxLength controlla separatamente la quantità di contenuto restituito. I formati full-document (text, htmle markdown) richiedono l'accesso completo ai documenti.
Endpoint: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"
}'
Installare l'SDK con python -m pip install webiq==1.2.1 (Python 3.11 o versione successiva), quindi eseguire:
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)
Installare l'SDK con npm install @microsoft/webiq@1.2.1 (Node.js 22.18+ su 22.x o 24+). Salvare questo esempio come browse.mts ed eseguirlo con 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;
});
In un progetto Rust 1.88 o versione successiva eseguire cargo add webiq@1.2.1 e cargo add tokio --features macros,rt-multi-thread. Salva questo esempio come src/main.rs e esegui 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(())
}
In un progetto Maven configurato per Java 11 o versione successiva aggiungere questa dipendenza a pom.xml:
<dependency>
<groupId>com.microsoft.webiq</groupId>
<artifactId>webiq</artifactId>
<version>1.2.1</version>
</dependency>
Salva questo esempio come src/main/java/Browse.java e esegui 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());
}
}
}
In un progetto console di .NET 8 o versione successiva eseguire dotnet add package Microsoft.WebIQ --version 1.2.1. Salva questo esempio come Program.cs e esegui 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))
Salvare questo esempio come browse.mjs ed eseguirlo con 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));
Una risposta riuscita 200 include la pagina url, title, estratti content e un traceId. Una ricerca per indicizzazione dinamica può restituire 202 con retryAfter, un timestamp UTC ISO 8601; attendere fino a quel momento, quindi inviare di nuovo la stessa richiesta. Vedere le informazioni di riferimento sulla Browse API per la struttura completa della risposta.
6. Cercare luoghi (facoltativo)
Usa Places Search per ottenere informazioni strutturate sulle aziende locali e altri luoghi. Gli esempi dell'SDK usano i pacchetti 1.2.1 installati nel passaggio 2.
Endpoint: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)
Salvare questo esempio come places.mts ed eseguirlo con 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;
});
Usa la configurazione di Tokio del passaggio 2. Salva questo esempio come src/main.rs e esegui 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(())
}
Salvare questo esempio come src/main/java/Places.java nel progetto Maven dal passaggio 2 ed eseguire 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());
}
}
}
}
}
Nel progetto console .NET del passaggio 2 salvare questo esempio come Program.cs ed eseguire 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))
Salvare questo esempio come places.mjs ed eseguirlo con 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));
Leggere i risultati da placeResults. L'elenco e i singoli campi possono essere assenti, quindi verificare la presenza di valori mancanti prima di usare indirizzi, ore di apertura o altri dettagli. Vedere le informazioni di riferimento sull'API Places.
7. Recuperare elementi di prova con Auto
Usare Auto quando si vuole che Web IQ selezioni le fonti di recupero e restituisca prove tipate con citazioni di supporto. Porre una domanda completa in linguaggio naturale, mantenendo vincoli rilevanti, ad esempio date, posizioni e unità. Questi esempi omettono mode per usare il valore predefinito e consentire 60 secondi per ogni tentativo di richiesta. Impostare mode su advanced per Auto Advanced quando è necessario un recupero più completo per domande complesse.
Auto restituisce evidenze che la tua applicazione può utilizzare, non una risposta finale generata. Leggi ogni risultato delle prove con le proprie citazioni; non trattare le citazioni da un risultato come supporto per un altro. Gli esempi dell'SDK usano la versione 1.2.1 di tutti e cinque gli SDK, installati nel passaggio 2.
Endpoint: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)
Salvare questo esempio come auto.mts ed eseguirlo con 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;
});
Usa la configurazione di Tokio del passaggio 2. Salva questo esempio come src/main.rs e esegui 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(())
}
Salvare questo esempio come src/main/java/Auto.java nel progetto Maven dal passaggio 2 ed eseguire 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());
}
}
}
}
}
}
}
Nel progetto console .NET del passaggio 2 salvare questo esempio come Program.cs ed eseguire 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))
Salvare questo esempio come auto.mjs ed eseguirlo con 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));
Una risposta con esito positivo contiene un results array. Ogni risultato associa un oggetto tipizzato al relativo citations di supporto. Un array results vuoto o assente non contiene prove da elaborare. Consulta il riferimento dell'Auto API per i tipi di evidenza, gli esempi di risposta e i limiti delle richieste.
8. Cercare i prodotti con Commerce (facoltativo)
Usare le Commerce APIs per trovare prodotti e offerte di venditori per una query di shopping: Search restituisce prodotti classificati con le offerte principali del venditore, Offers restituisce più offerte per un prodotto e Product Details restituisce il titolo, la descrizione e la classificazione di un prodotto.
Note
Le API Commerce sono in anteprima privata e sono incluse in AppID con accesso completo ai documenti. L'accesso viene abilitato separatamente per ogni endpoint. Se l'APPID non li ha, aprire una richiesta di supporto di IQ Web (tipo di problema Authentication & Access) con l'APPID.
Endpoints:POST https://api.microsoft.ai/v3/search/commerce/products, POST https://api.microsoft.ai/v3/fetch/commerce/products/offers, e POST https://api.microsoft.ai/v3/fetch/commerce/products/details
Questo passaggio mostra le chiamate REST. Scegliere cURL, Python (REST) o JavaScript (REST) nella parte superiore della pagina per visualizzarli.
Cerca i prodotti:
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"
}'
Dal primo prodotto nella risposta, copiare il relativo id, il relativo skuId e il id della sua prima offerta. Sostituire PRODUCT_ID, SKU_ID e OFFER_ID di seguito, quindi cercare altre offerte e i dettagli del prodotto. Alcuni prodotti restituiscono solo un'offerta, senza id o skuId: inviare solo Offers e il offerId e ignorare i dettagli del prodotto, che richiedono un prodotto o un ID SKU.
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))
Salvare questo esempio come commerce.mjs ed eseguirlo con 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));
}
La ricerca restituisce i prodotti in ordine di classificazione con le offerte principali del venditore; maxResults limita i prodotti, non le offerte. Le offerte restituiscono prima l'offerta principale, seguita da eventuali offerte aggiuntive. Una richiesta valida senza corrispondenza restituisce 200 OK con un array offers o products vuoto. I prezzi sono numeri interi nelle unità secondarie della valuta: 39999 USD è $399,99.
Per inviare un utente, o un agente che agisce per conto dell'utente, a un'offerta, usa il clickUrl dell'offerta esattamente come restituito in tale risposta. Non usare displayUrl, che identifica solo il commerciante e non riscrivere, abbreviare o riutilizzare il collegamento. Crea i link nel codice dell'applicazione anziché farli riprodurre da un modello. Vedi Collegamenti e attribuzione delle offerte e guida commerciale.
Troubleshooting
| Stato | Controlli da eseguire |
|---|---|
401 Unauthorized |
Verificare che WEBIQ_API_KEY sia impostato e che la richiesta lo invii nell'intestazione x-apikey. |
415 Unsupported Media Type |
Invia content-type: application/json. |
429 Too Many Requests |
Attendere prima di riprovare e ridurre la frequenza delle richieste. |
Sfoglia 404 Not Found |
Verificare che l'URL sia pubblico e valido. Usare liveCrawl: "fallback" quando il contenuto indicizzato potrebbe non essere disponibile. |
Sfoglia 202 Accepted |
Attendere fino all'ora in retryAfter (timestamp UTC ISO 8601), quindi inviare di nuovo la stessa richiesta. |
Auto 403 Forbidden |
Verificare che Auto sia elencato in Servizi consentiti in Gestione profili. In caso contrario, aprire una richiesta di Web IQ Support con l'ID app. |
Per altri errori, salvare traceId e vedere Gestione degli errori. Per contattare il Web IQ Support, includere traceId e l'AppID, oppure il nome della società e il nome della risorsa Web IQ, se non si dispone dell'AppID.
Passaggi successivi
- Esplora i riferimenti API Ricerca Web e Sfoglia.
- Recupera i dati aziendali locali strutturati con Places o le evidenze selezionate automaticamente con Auto.
- Crea un'esperienza di acquisto con la guida Commerce.
- Usare gli SDK Python, TypeScript, Rust, Java e .NET.
- Installare il server MCP in Claude Code, Cursor o VS Code.
- Configurare l'autenticazione di produzione con Microsoft Entra ID.
- Eseguire esempi completi dai campioni di codice di Web IQ su GitHub.
- Segui il modulo di formazione Integra le informazioni basate sul Web nel tuo agente con Web IQ.
- Guarda Grounding degli agenti con intelligence del mondo reale, l'episodio Web IQ della serie Microsoft IQ.