Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
Microsoft Web IQ SDK'ları, Auto, web, haber, video, görüntü ve Places araması ile Browse için tipli istemciler sağlar. Tüm yükleme komutlarını ve örneklerini birlikte değiştirmek için bu sayfanın üst kısmından bir dil seçin.
Bu örneklerde, türlendirilmiş kanıt ve sonuç kapsamlı atıflarla Auto search için genel 1.2.1 SDK sürümleri kullanılır. Çalıştırmadan önce önceki SDK sürümlerini yükseltin.
| Property | Python | TypeScript | Rust | Java | .NET |
|---|---|---|---|---|---|
| Package | webiq |
@microsoft/webiq |
webiq |
com.microsoft.webiq:webiq |
Microsoft.WebIQ |
| Kullanılan sürüm | 1.2.1 | 1.2.1 | 1.2.1 | 1.2.1 | 1.2.1 |
| Çalışma zamanı | Python 3.11+ | Node.js 22.13+ (22.x) veya 24+ | Rust 1.88+ | Java 11+ | .NET 8+ |
| License | MIT | MIT | MIT | MIT | MIT |
Web IQ API anahtarına veya Web IQ'ya erişimi olan bir Microsoft Entra kimliğine ihtiyacınız vardır. Bkz. Kimlik doğrulaması.
Installation
python -m pip install webiq==1.2.1
npm install @microsoft/webiq@1.2.1
PROJEnize SDK ve Tokio çalışma zamanını ekleyin:
cargo add webiq@1.2.1
cargo add tokio --features macros,rt-multi-thread
Maven Central bağımlılığını projenizin pom.xmlöğesine ekleyin. Projeyi Java 11 veya sonraki sürümler için derlenecek şekilde yapılandırın.
<dependency>
<groupId>com.microsoft.webiq</groupId>
<artifactId>webiq</artifactId>
<version>1.2.1</version>
</dependency>
Gradle için:
implementation "com.microsoft.webiq:webiq:1.2.1"
Bu örneklerde public Microsoft.WebIQ 1.2.1 paketi kullanılır ve .NET 8 veya üzeri gerekir. .NET konsol projesinde şu komutu çalıştırın:
dotnet add package Microsoft.WebIQ --version 1.2.1
Quickstart
WEBIQ_API_KEY ortam değişkenini, örneği çalıştırmadan önce API anahtarınıza ayarlayın. API anahtarlarını kaynak koda koymayın.
Örnek, deneme başına 60 saniyelik zaman aşımı ile advanced modunda Auto'yu çağırır, destekleyici alıntılarıyla birlikte her kanıt sonucunu yazdırır, ardından Web, Haberler, Video, Görüntü ve Yer Arama'yı çağırır ve Browse ile bir sayfa alır. Otomatik, oluşturulan son yanıtı değil kanıtı döndürür. Kanıt türleri ve istek seçenekleri için Auto reference bölümüne bakın.
Web, Haberler ve Gözatma istek pasajları, dayanaklandırma için önerilen biçimdir. Göz atma için 1000 karaktere kadar boş olmayan bir seçim query de gerekir. Tam belge biçimleri için bkz. İçerik biçimleri.
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(())
}
Bu örneği Maven projenizde src/main/java/WebIqSample.java olarak kaydedin ve mvn compile exec:java -Dexec.mainClass=WebIqSample çalıştırın.
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 kimlik doğrulaması
API anahtarı yerine Azure Identity kimlik bilgilerini geçirin. Yerel geliştirme için, Azure CLI gibi desteklenen bir geliştirici aracıyla oturum açın. Azure barındırılan uygulamalar için yönetilen kimliği veya iş yükü kimliğini kullanın. Kimliğinizin Web IQ'ya erişimi olmalıdır.
Varsayılan OAuth kapsamı https://api.microsoft.ai/.default.
İsteğe bağlı kimlik doğrulama bağımlılığını yükleyin:
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 Kimlik desteği SDK'ya dahildir.
azure_identity, SDK tarafından yeniden dışa aktarılır, bu nedenle ek bağımlılık gerekmez. Bu örnekte, azd auth login veya az login sonrasında bir geliştirici kimlik bilgisi kullanılır:
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);
Barındırılan uygulamalar için, ManagedIdentityCredential içinden WorkloadIdentityCredential veya webiq::azure_identity seçin.
Projenizin Azure SDK bağımlılıklarıyla uyumlu bir sürüm kullanarak com.azure:azure-identity öğesini Maven veya Gradle bağımlılıklarınıza ekleyin.
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);
Kaynaklar ve istek seçenekleri
Parametre açıklamaları, desteklenen değerler, yanıt alanları ve hizmet sınırları için REST başvurusunu kullanın.
| Resource | Yöntem | Reference |
|---|---|---|
| Auto | client.auto.search(query, ...) |
Otomatik |
| İnternet | client.web.search(query, ...) |
Web Search |
| Haberler | client.news.search(query, ...) |
Haber Arama |
| Videos | client.videos.search(query, ...) |
Video Araması |
| Görüntüler | client.images.search(query, ...) |
Resim Araması |
| Yerler | client.places.search(query, ...) |
Yerler |
| Göz atmak | client.browse.fetch(url, ...) |
Gözat |
İstek seçeneklerinde snake_case kullanılır; yanıt özelliklerinde camelCase kullanılır. Desteklenen değerler için SDK enum'larını kullanın. Örneğin:
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,
)
Kalan kod parçacıkları, açıkça oluşturmadıkları sürece açık bir client olduğunu varsayar.
| Resource | Yöntem | Reference |
|---|---|---|
| Auto | client.auto.search(query, options) |
Otomatik |
| İnternet | client.web.search(query, options) |
Web Search |
| Haberler | client.news.search(query, options) |
Haber Arama |
| Videos | client.videos.search(query, options) |
Video Araması |
| Görüntüler | client.images.search(query, options) |
Resim Araması |
| Yerler | client.places.search(query, options) |
Yerler |
| Göz atmak | client.browse.fetch(url, options) |
Gözat |
İstek seçenekleri ve yanıt özellikleri, contentFormat, liveCrawl, aspectRatio ve maxResults gibi camelCase kullanır. İkinci bağımsız değişken olarak seçenekleri geçirin. Hızlı başlangıçta gösterildiği gibi desteklenen değerler için SDK enumlarını kullanın.
Kalan kod parçacıkları, istemciyi açıkça oluşturmadıkları sürece client öğesinin açık olduğunu varsayar ve zaman uyumsuz bir işlev içinde çalışır. Üst düzey await için bir ES modülü gerekir.
| Resource | Yöntem | Reference |
|---|---|---|
| Auto | client.auto().search(query, options) |
Otomatik |
| İnternet | client.web().search(query, options) |
Web Search |
| Haberler | client.news().search(query, options) |
Haber Arama |
| Videos | client.videos().search(query, options) |
Video Araması |
| Görüntüler | client.images().search(query, options) |
Resim Araması |
| Yerler | client.places().search(query, options) |
Yerler |
| Göz atmak | client.browse().fetch(url, options) |
Gözat |
WebSearchOptions, VideoSearchOptions, ImageSearchOptions, PlacesSearchOptions, BrowseOptions, AutoSearchOptions veya NewsSearchOptions ile derleme seçenekleri oluşturun. Yanıt alanları snake_case kullanır ve isteğe bağlı değerler Option kullanır.
Kalan kod parçacıkları, açıkça bir tane oluşturmadıkları sürece, açık bir client ile Result döndüren zaman uyumsuz bir işlevin içinde çalışır. Hızlı başlangıçtaki Tokio çalışma zamanı kurulumunu kullanın.
| Resource | Yöntem | Reference |
|---|---|---|
| Auto | client.auto.search(query, AutoSearchOptions) |
Otomatik |
| İnternet | client.web.search(query, WebSearchOptions) |
Web Search |
| Haberler | client.news.search(query, NewsSearchOptions) |
Haber Arama |
| Videos | client.videos.search(query, VideosSearchOptions) |
Video Araması |
| Görüntüler | client.images.search(query, ImagesSearchOptions) |
Resim Araması |
| Yerler | client.places.search(query, PlacesSearchOptions) |
Yerler |
| Göz atmak | client.browse.fetch(url, BrowseFetchOptions) |
Gözat |
contentFormat, maxLength ve maxResults gibi camelCase builder yöntemleriyle istek seçeneklerini oluşturun.
getTraceId() ve getWebResults() gibi get metotlarıyla yanıt özelliklerini okuyun. İsteğe bağlı yanıt alanları olabilir null.
Kalan kod parçacıkları, açıkça bir client oluşturmadıkları sürece, açık bir client ile bir yöntem içinde çalışır. İçeri aktarmaları Java dosyanızın en üstüne yerleştirin.
| Resource | Asenkron yöntem | Reference |
|---|---|---|
| Auto | client.Auto.SearchAsync(query, configure) |
Otomatik |
| İnternet | client.Web.SearchAsync(query, configure) |
Web Search |
| Haberler | client.News.SearchAsync(query, configure) |
Haber Arama |
| Videos | client.Videos.SearchAsync(query, configure) |
Video Araması |
| Görüntüler | client.Images.SearchAsync(query, configure) |
Resim Araması |
| Yerler | client.Places.SearchAsync(query, configure) |
Yerler |
| Göz atmak | client.Browse.FetchAsync(url, configure) |
Gözat |
İstek ve yanıt özellikleri PascalCase kullanır. Yapılandırma geri çağırmasında istek seçeneklerini ayarlayın veya doğrudan bir istek modeli geçirin. Eşzamanlı Search ve Fetch yöntemler de kullanılabilir.
Kalan kod parçacıkları, açıkça oluşturmadıkları sürece açık bir client olduğunu varsayar.
Auto'nun kullanılabilirliği
Auto, 1.2.1 sürümündeki beş SDK'nın tümünde kullanılabilir. Python ve Java hem zaman uyumlu hem de zaman uyumsuz istemcileri aracılığıyla Auto'yu kullanıma sunar; .NET, Search ve SearchAsync sağlar; TypeScript ve Rust zaman uyumsuz çağrılar kullanır.
Tam bir doğal dil sorusu yazın ve uygulamanız için önemli olan kısıtlamaları koruyun. Her bir sonucun evidence öğesini, o sonucun citations öğesiyle birlikte okuyun; alıntılar yalnızca onları içeren sonucu destekler. Parametreler, kanıt türleri ve hizmet sınırları için bkz. Otomatik API başvurusu.
Asenkron destek
Uygulamanızın birden çok sonuç türüne ihtiyacı olduğunda eşzamanlı olarak bağımsız istekler oluşturun.
WebIQAsyncClient ile asyncio kullanın:
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 kullanın; kaynak yöntemleri CompletableFuture döndürür:
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
Zaman aşımları ve yeniden denemeler
İstemci düzeyinde bir zaman aşımı ayarlayın ve gerektiğinde bunu istek bazında değiştirin. Zaman aşımları deneme başına uygulanır, yeniden denenmeye harcanan toplam süreye uygulanmaz.
Varsayılan olarak, SDK'lar geçici ağ hatalarını ve HTTP 408, 500, 502, 520, 523 ve 524 yanıtlarını üstel geri alma ve jitter ile en fazla iki kez yeniden dener. Yanıt gövdesindeki geçerli retryAfter değeri, oluşturulan geri çekilme süresine göre önceliklidir. HTTP 429 ve 430 hiçbir zaman otomatik olarak yeniden denenmez: Hatanın yeniden deneme kılavuzunu inceleyin ve kendi backoff stratejinizi uygulayın. İstemci tarafı zaman aşımları yeniden denenmez.
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)
Zaman aşımları saniye cinsindendir. İstemci varsayılanı 10 saniyedir.
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();
}
Zaman aşımları milisaniye cinsindendir. İstemci varsayılanı 10.000 milisaniyedir.
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?;
İstemci varsayılanı 10 saniyedir.
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());
}
İstemci varsayılanı 10 saniyedir.
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));
İstemci varsayılanı 30 saniyedir.
Özel HTTP istemcileri
Ara sunucu, TLS veya bağlantı havuzu yapılandırması için özel bir HTTP istemcisi kullanın. Sertifika doğrulamayı devre dışı bırakma.
Çağıranın sahip olduğu HTTP istemcisini kendiniz geçirin http_client ve kapatın. Eşzamansız istekler için httpx.AsyncClient öğesini WebIQAsyncClient ile kullanın.
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 öğesini ara sunucu desteği için yükleyin:
npm install undici
Özel bir fetchFn iletin.
AbortSignal öğesini koruyun; böylece SDK'nın üst bilgileri, gövdesi ve iç init öğesi iletilir.
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 ögesini SDK ile uyumlu bir sürümle doğrudan bağımlılık olarak ekleyin.
Yapılandırılmış java.net.http.HttpClient öğesini WebIQClientOptions.builder().httpClient(...) aracılığıyla geçirin. SDK, çağıranın sahip olduğu istemcileri kapatmaz; uygulamanızda yaşamlarını yönetin.
Bir HttpClient öğesini WebIQClientOptions.HttpClient üzerinden geçirin. SDK, çağırana ait bir HTTP istemcisini serbest bırakmaz; uygulamanızda bunun yaşam döngüsünü yönetin.
İptal
Asenkron istekler için, görev iptalini kullanın asyncio veya yeniden deneme beklemelerini içeren bir duvar saati bütçesi uygulamak için asyncio.timeout kullanın. İstek başına SDK zaman aşımı her HTTP girişimini sınırlar.
Her kaynak yöntemi, AbortSignal aracılığıyla options.signal kabul eder. Durdurma işlemi, uçuş içi isteği ve yeniden deneme beklemelerini de iptal eder; sinyalin nedeni değiştirilmeden yeniden fırlatılır.
const response = await client.web.search('Microsoft Web IQ', {
signal: AbortSignal.timeout(5_000),
});
Gelen isteğin sinyalini duvar saati sınırıyla birleştirmek için AbortSignal.any([request.signal, AbortSignal.timeout(5_000)]) kullanın.
yeniden deneme beklemeleri de dahil olmak üzere işlemi kesintiye uğratmak için istek future’ını iptal edin veya bırakın. Son başvuru tarihi için Tokio zaman yardımcı programlarını kullanın ve Tokio'nun time özelliğini etkinleştirin.
Her HTTP denemesini sınırlamak için çağrı başına bir timeout kullanın. SDK 1.2.1 istek iptal belirtecini kullanıma sunmaz. Döndürülen CompletableFuture öğesinin iptal edilmesi, temel alınan HTTP isteğinin veya yeniden deneme beklemelerinin iptalini garanti etmez.
yeniden deneme beklemeleri de dahil olmak üzere işlemi iptal etmek için bir CancellationToken geçirin:
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var response = await client.Web.SearchAsync("Microsoft Web IQ",
cancellationToken: cancellation.Token);
Telemetry
Her istek denemesini, durumunu ve geçen süreyi günlüğe kaydetmek için bir telemetri geri çağrısı ekleyin. Telemetri ayrıca istek ve izleme kimliklerini, yeniden deneme kılavuzlarını ve hata bilgilerini içerir. Kimlik bilgilerini veya hassas sorgu içeriğini günlüğe kaydetmekten kaçının.
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")
Telemetri alanları, status_code, retry_after, request_id, trace_id, elapsed_ms, error, error_body ve attempt dahil olmak üzere snake_case kullanır.
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();
}
Telemetri alanları, statusCode, traceId, requestId, retryAfter, elapsedMs, error, errorBody ve attempt dahil olmak üzere camelCase kullanır.
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");
Hata yönetimi
Kimlik doğrulaması, izin ve hız sınırı hatalarını geçici hatalardan ayrı olarak işleyin. HTTP 429 ve 430, SDK yeniden denemeleri olmadan hemen görünür. Yeniden ne zaman deneneceğine karar vermek için döndürülen yeniden deneme kılavuzunu kullanın.
Tüm SDK özel durumları WebIQError öğesinden devralınır. HTTP hataları, PermissionDeniedError, AuthenticationError ve APIStatusError dahil olmak üzere RateLimitError öğesinden devralır. Ağ hataları ve zaman aşımları APIConnectionError oluşturur. Python istek doğrulaması, istek göndermeden önce pydantic.ValidationError tetikleyebilir.
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 dahil olmak üzere technicalDetails, retryAfter, traceId, errorCategory ve APIStatusError.body içeren tam sunucu hata yanıtı için errorCode öğesini inceleyin.
Tüm SDK hataları WebIQError sınıfından türetilir. HTTP hataları, PermissionDeniedError, AuthenticationError ve APIStatusError dahil olmak üzere RateLimitError öğesinden devralır. Ağ hataları ve zaman aşımları APIConnectionError oluşturur.
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 dahil olmak üzere technicalDetails, retryAfter, traceId, errorCategory ve APIStatusError.body içeren tam sunucu hata yanıtı için errorCode öğesini inceleyin.
Çağrılar döndürür Result<T, WebIqError>. API hatalarını eşleştirin veya yapılandırılmış tanılama için hata erişimcilerini inceleyin:
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 hataları error_category(), error_code(), user_message(), technical_details(), retry_after(), trace_id(), request_id(), body() ve status_code() öğelerini gösterir. Eksik isteğe bağlı alanlar None döndürür.
Tüm SDK özel durumları WebIQException öğesinden devralınır. HTTP durum özel durumları, APIStatusException sınıfından devralır. Ağ hataları ve zaman aşımları APIConnectionException oluşturur.
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());
}
Durum istisnaları getErrorCategory(), getErrorCode(), getUserMessage(), getTechnicalDetails(), getRetryAfter(), getTraceId(), getRequestId(), getBody() ve getStatusCode() öğelerini açığa çıkarır. Eksik isteğe bağlı alanlar null döndürür.
HTTP durum özel durumları, ApiStatusException sınıfından devralır. Ağ hataları ve zaman aşımları ApiConnectionException oluşturur.
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}");
}
Durum özel durumları ErrorCode, UserMessage, TechnicalDetails, RetryAfter, RequestId, TraceId, Body ve ErrorCategory gösterir. Eksik isteğe bağlı alanlar null.
Bir tarama beklemedeyken Gözat, HTTP 202 Accepted döndürebilir. Bu bir özel durum değil normal bir yanıttır ve SDK otomatik olarak yoklamaz. Daha sonra yeniden denemek için yanıt URL'sini ve UTC retryAfter zaman damgasını kullanın. Kısmi HTTP 200 yanıtları, truncationReason gibi bir "encumbrance" içerebilir.
Hata ayıklama ve sonraki adımlar
- Desteğe başvururken
traceIddahil edin. Rust kullanırtrace_id, Java kullanırgetTraceId()ve .NET kullanırTraceId. - Denemeleri, yanıt kodlarını ve geçen süreyi ilişkilendirmek için telemetriyi kullanın.
- Bir hatayı yeniden denenebilir olarak değerlendirmeden önce yapılandırılmış hata gövdesini inceleyin. Hata işleme bölümüne bakınız.
- Arama sonuçlarını görüntülerken veya alıntı yaparken tıklama ve alıntı enstrümantasyonu ekleyin.