Python 및 TypeScript에서 사용할 수 있는 Microsoft Web IQ API에 대한 공식 SDK입니다. 이러한 SDK를 통해 애플리케이션은 정확하고 최신의 정보로 LLM 응답의 근거를 제공하도록 설계된 웹 검색, 비디오 검색, 찾아보기, 뉴스 검색 및 이미지 검색에 실시간으로 액세스할 수 있습니다.
| Python | TypeScript | |
|---|---|---|
| 패키지 | pip install webiq |
npm install @microsoft/webiq |
| 런타임 | Python 3.11 이상 | Node.js 22 이상 |
| 라이선스 | MIT | MIT |
Installation
Python
pip install webiq
TypeScript
npm install @microsoft/webiq
Quickstart
Python 가이드
import os
from webiq import WebIQClient
from webiq.types import BrowseContentFormat, ContentFormat
with WebIQClient(api_key=os.environ["WEBIQ_API_KEY"]) as client:
# Web search
web = client.web.search(
"Python programming",
max_results=5,
content_format=ContentFormat.passage,
)
for r in web.webResults or []:
print(r.title, r.url)
# Videos search
videos = client.videos.search("machine learning tutorial", max_results=5)
for v in videos.videoResults or []:
print(v.title, v.length)
# Browse a URL
page = client.browse.fetch("https://www.microsoft.com", content_format=BrowseContentFormat.markdown)
print(page.content)
# News search
news = client.news.search("technology", max_results=5)
for item in news.newsResults or []:
print(item.title, "-", item.source)
# Image search
images = client.images.search("golden gate bridge", max_results=5)
for img in images.imageResults or []:
print(img.title, img.url)
TypeScript 가이드
import { WebIQClient, BrowseContentFormat, ContentFormat } from '@microsoft/webiq';
async function main() {
const client = new WebIQClient({ apiKey: process.env.WEBIQ_API_KEY });
// Web search
const web = await client.web.search('TypeScript programming', {
maxResults: 5,
contentFormat: ContentFormat.PASSAGE,
});
for (const r of web.webResults ?? []) console.log(r.title, r.url);
// Videos search
const videos = await client.videos.search('machine learning tutorial');
for (const v of videos.videoResults ?? []) console.log(v.title, v.length);
// Browse a URL
const page = await client.browse.fetch('https://www.microsoft.com', {
contentFormat: BrowseContentFormat.MARKDOWN,
});
console.log(page.content);
// News search
const news = await client.news.search('technology', { maxResults: 5 });
for (const item of news.newsResults ?? []) console.log(item.title, '-', item.source);
// Image search
const images = await client.images.search('golden gate bridge', { maxResults: 5 });
for (const img of images.imageResults ?? []) console.log(img.title, img.url);
await client.close();
}
main().catch(console.error);
Authentication
API 키
# Python
import os
from webiq import WebIQClient
client = WebIQClient(api_key=os.environ["WEBIQ_API_KEY"])
// TypeScript
import { WebIQClient } from '@microsoft/webiq';
const client = new WebIQClient({ apiKey: process.env.WEBIQ_API_KEY });
Microsoft Entra ID (마이크로소프트 엔트라 ID)
Azure Identity를 전달하세요TokenCredential
# Python — uses `azure-identity`
from azure.identity import DefaultAzureCredential
from webiq import WebIQClient
client = WebIQClient(credential=DefaultAzureCredential())
// TypeScript — uses `@azure/identity`
import { DefaultAzureCredential } from '@azure/identity';
import { WebIQClient } from '@microsoft/webiq';
const client = new WebIQClient({
credential: new DefaultAzureCredential(),
});
SDK 리소스 및 메서드
클라이언트는 5개의 리소스 네임스페이스(videos, browse, news, images 및 web)를 노출합니다.
Web Search
client.web.search() — 웹을 검색하고 근거 자료용 페이지 콘텐츠를 가져옵니다.
response = client.web.search(
query="search terms", # Required, 1–1000 chars
max_results=10, # 1–50 (default 10)
language="en", # ISO 639-1 code
region="US", # Country/region code
location="lat:40.7;long:-74.0", # Optional
content_format=ContentFormat.passage, # passage (default) | text | html | markdown (full-page content)
max_length=3000, # Max content chars (default 3000)
)
# response.webResults → list of { title, url, content, lastUpdatedAt, crawledAt, language, isAdult }
비디오 검색
client.videos.search() — 선택적 재생 목록 지원을 사용하여 관련 비디오 콘텐츠를 찾습니다.
response = client.videos.search(
query="search terms", # Required, 1–1000 chars
max_results=30, # 1–30 (default 30)
language="en",
region="US",
enable_playlist=True, # Include playlist results
freshness="month", # week | month | year
)
# response.videoResults → list of { title, url, description, length, viewCount, moments[], thumbnailUrl, ... }
# response.playlists → list of { title, videos[] }
찾아보기
client.browse.fetch() — 모든 URL에서 콘텐츠를 추출합니다. 라이브 크롤링 및 JavaScript 렌더링을 지원합니다.
response = client.browse.fetch(
url="https://www.microsoft.com", # Required
max_length=10000, # Max content chars, 1–500000
live_crawl="fallback", # "none" (cached only, default) | "fallback" (crawl if not cached) | "force" (always crawl, bypass cache)
include_web_links=True, # Include outbound hyperlinks
include_image_links=True, # Include image URLs
render_dynamic_pages=False, # JS rendering (requires live_crawl="fallback")
content_format=BrowseContentFormat.markdown, # text | html | markdown
)
# response → { url, title, content, isAdult, lastUpdatedAt, crawledAt, retryAfter, traceId }
News Search
client.news.search() — 쿼리와 가장 관련된 구절이 포함된 최신 뉴스 기사를 가져옵니다.
response = client.news.search(
query="search terms", # Required, 1–1000 chars
max_results=10, # 1–20 (default 10)
language="en",
region="US",
location="lat:40.7;long:-74.0", # Optional
content_format=ContentFormat.passage,
max_length=3000,
)
# response.newsResults → list of { title, url, content, source, lastUpdatedAt, thumbnail, isAdult }
Image Search
client.images.search() - 가로 세로 비율, 크기 및 안전한 검색을 기준으로 필터링된 이미지를 찾습니다.
from webiq.types import ImageAspectRatio, ImageSize, SafeSearch
response = client.images.search(
query="search terms", # Required, 1–1000 chars
max_results=30, # 1–30 (default 30)
language="en",
region="US",
aspect_ratio=ImageAspectRatio.wide, # square | wide | tall
image_size=ImageSize.large, # small | medium | large | extraLarge
safe_search=SafeSearch.strict, # off | strict
watermark_free=True,
)
# response.imageResults → list of { title, url, hostPageUrl, caption, width, height, thumbnailUrl, ... }
Note
TypeScript 메서드는 camelCase에서 동일한 매개 변수를 사용합니다(예: maxResults, contentFormat, liveCrawl, aspectRatio). 호출 규칙에 대해서는 위의 TypeScript 빠른 시작을 참조하세요.
비동기 지원
Python 지원
import asyncio
from webiq import WebIQAsyncClient
async def main():
async with WebIQAsyncClient(api_key="your-api-key") as client:
web, news = await asyncio.gather(
client.web.search("async Python"),
client.news.search("programming"),
)
for r in web.webResults or []:
print(r.title)
asyncio.run(main())
TypeScript 지원
TypeScript는 본질적으로 비동기입니다. 동시성에는 Promise.all 사용:
const [web, news, videos] = await Promise.all([
client.web.search('TypeScript'),
client.news.search('programming'),
client.videos.search('tutorial'),
]);
Configuration
시간 제한 및 재시도
클라이언트는 timeout 및 retry를 최상위 옵션으로 허용합니다.
timeout 호출별 설정은 각 리소스 메서드에서 클라이언트 수준 기본값을 재정의합니다. SDK는 408, 500, 502, 503, 504를 지수 백오프 및 지터와 함께 자동으로 재시도합니다. 응답 본문에 "30s" 필드(예: retryAfter)가 포함된 경우 SDK는 백오프 지연 대신 해당 힌트를 기다립니다.
429 및 430은 자동으로 재시도되지 않습니다. 즉, 애플리케이션이 자체 백오프 정책을 적용할 수 있도록 즉시 RateLimitError로 처리됩니다. 클라이언트 쪽 시간 제한도 다시 시도되지 않습니다(APIConnectionError 예외가 발생합니다).
# Python
from webiq import WebIQClient, RetryPolicy
client = WebIQClient(
api_key="your-api-key",
timeout=10.0, # seconds (default: 10.0)
retry=RetryPolicy(
max_retries=2, # defaults shown
base_delay_s=0.25,
max_delay_s=4.0,
),
)
# Per-call override
response = client.web.search("query", language="de", region="DE", timeout=30.0)
// TypeScript
import { WebIQClient, RetryPolicy } from '@microsoft/webiq';
const client = new WebIQClient({
apiKey: 'your-api-key',
timeout: 10000, // milliseconds (default: 10000)
retry: new RetryPolicy({
maxRetries: 2, // defaults shown
baseDelaySeconds: 0.25,
maxDelaySeconds: 4.0,
}),
});
사용자 지정된 HTTP 클라이언트(프록시, TLS, ...)
고급 HTTP 설정의 경우 프록시, 사용자 지정 TLS, 연결 풀링 등이 있습니다. SDK는 호출자 소유 클라이언트를 닫지 않습니다.
# Python — pass a pre-configured `httpx.Client` via `http_client`
import httpx
from webiq import WebIQClient, WebIQAsyncClient
# sync
http_client = httpx.Client(
base_url="https://api.microsoft.ai/v3",
proxy="http://proxy:8080",
)
client = WebIQClient(api_key="your-api-key", http_client=http_client)
# async
http_client = httpx.AsyncClient(
base_url="https://api.microsoft.ai/v3",
proxy="http://proxy:8080",
)
client = WebIQAsyncClient(api_key="your-api-key", http_client=http_client)
// TypeScript — pass a custom `fetchFn` that wraps the global `fetch`
import { ProxyAgent } from 'undici';
import { WebIQClient } from '@microsoft/webiq';
const proxyAgent = new ProxyAgent('http://my-proxy:8080');
const client = new WebIQClient({
apiKey: 'your-api-key',
// Spread `init` so headers, body, and the SDK's internal `AbortSignal` are preserved.
fetchFn: (url, init) => fetch(url, { ...init, dispatcher: proxyAgent }),
});
취소 (TypeScript)
모든 TypeScript 리소스 메서드는 AbortSignal를 통해 options.signal을 허용합니다. 신호가 중단되면 진행 중인 요청이 취소되고 재시도가 중지되며 신호의 reason가 변경 없이 다시 throw됩니다(APIConnectionError으로 래핑하지 않음).
// Apply a wall-clock budget that includes retries (the `timeout` option is per attempt only)
const result = await client.web.search('latest news', {
signal: AbortSignal.timeout(5_000),
});
// Combine signals (e.g. an inbound request signal plus a wall-clock cap)
const result2 = await client.web.search('latest news', {
signal: AbortSignal.any([req.signal, AbortSignal.timeout(5_000)]),
});
텔레메트리 후크
로깅, 메트릭 수집 또는 디버깅을 위해 모든 요청/응답을 모니터링합니다.
# Python
from webiq import WebIQClient, TelemetryEvent
def on_request(event: TelemetryEvent):
print(f"{event.method} {event.path} → {event.status_code} ({event.elapsed_ms}ms)")
client = WebIQClient(api_key="your-api-key", telemetry_hook=on_request)
// TypeScript
import { WebIQClient, TelemetryEvent } from '@microsoft/webiq';
const client = new WebIQClient({
apiKey: 'your-api-key',
telemetryHook: (event: TelemetryEvent) => {
console.log(`${event.method} ${event.path} → ${event.statusCode} (${event.elapsedMs}ms)`);
},
});
TelemetryEvent 필드는 다음과 같습니다.
-
Python (snake_case):
method,path,transport,status_code,attempt,request_id,trace_id,retry_after,elapsed_ms,error,error_body -
TypeScript (camelCase):
method,path,attempt,transport,statusCode,requestId,traceId,retryAfter,error,elapsedMs,errorBody
오류 처리
두 SDK 모두 구조적 오류 처리에 대한 타입이 지정된 예외를 제공합니다. 모든 오류는 WebIQError에서 상속됩니다.
| 예외 | HTTP 상태 | 트리거 |
|---|---|---|
AuthenticationError |
401 | 잘못되었거나 누락된 API 키 |
PermissionDeniedError |
403 | 인증되었지만 리소스에 대해 권한이 부여되지 않음 |
RateLimitError |
429, 430 | 속도 제한/동시 요청 제한을 초과했습니다. |
APIStatusError |
400, 404, 500, 503, 504, ... | 다른 모든 HTTP 오류 |
APIConnectionError |
— | 네트워크 문제, DNS 오류, 시간 초과 |
WebIQError |
— | 모든 SDK 오류에 대한 기본 클래스 |
PermissionDeniedError와 RateLimitError는 둘 다 APIStatusError의 서브클래스이므로, APIStatusError의 더 포괄적인 핸들러에서도 여전히 이를 catch합니다. SDK는 430 않습니다429 / . 서버의 백오프 힌트는 애플리케이션이 이를 처리할 수 있도록 error.retryAfter (Python) / error.retry_after (TypeScript)에 표시됩니다.
# Python
from webiq import (
WebIQError,
APIConnectionError,
APIStatusError,
AuthenticationError,
PermissionDeniedError,
RateLimitError,
)
try:
response = client.web.search("test")
except PermissionDeniedError as e:
# 403 — authenticated, but not allowed to call this resource
print(f"Forbidden (HTTP {e.status_code}): {e}")
except AuthenticationError as e:
# 401 — invalid or missing API key
print(f"Auth failed (HTTP {e.status_code}): {e}")
except RateLimitError as e:
# 429 or 430 — rate limit / concurrent-request limit (never auto-retried)
print(f"Rate limited. Retry after: {e.retry_after}")
except APIStatusError as e:
print(f"API error (HTTP {e.status_code}): {e}")
except APIConnectionError as e:
print(f"Connection failed: {e}")
except WebIQError as e:
print(f"SDK error: {e}")
// TypeScript
import {
WebIQError,
APIConnectionError,
APIStatusError,
AuthenticationError,
PermissionDeniedError,
RateLimitError,
} from '@microsoft/webiq';
try {
const results = await client.web.search('test');
} catch (error) {
if (error instanceof PermissionDeniedError) {
// 403 — authenticated, but not allowed to call this resource
console.error(`Forbidden (HTTP ${error.statusCode}):`, error.message);
} else if (error instanceof AuthenticationError) {
// 401 — invalid or missing API key
console.error(`Auth failed (HTTP ${error.statusCode}):`, error.message);
} else if (error instanceof RateLimitError) {
// 429 or 430 — rate limit / concurrent-request limit (never auto-retried)
console.error(`Rate limited. Retry after: ${error.retryAfter}`);
} else if (error instanceof APIStatusError) {
console.error(`API error (HTTP ${error.statusCode}):`, error.message);
} else if (error instanceof APIConnectionError) {
console.error('Connection failed:', error.message);
}
}
오류 세부 정보 확인
모든 APIStatusError 인스턴스(PermissionDeniedError 및 RateLimitError를 포함한)는 전체 오류 응답 본문을 노출합니다. Python SDK의 대부분의 입력 유효성 검사 문제(예: max_results 범위 외, 비어 있는 query)는 Pydantic에 의해 클라이언트 측에서 포착되며 요청이 전송되기 전에 pydantic.ValidationError 예외를 발생시킵니다. 아래 패턴은 서버가 요청을 거부할 때 적용됩니다.
browse.fetch 는 이러한 구조화된 오류를 트리거하는 편리한 방법입니다. 즉, 누락되거나 필터링된 URL은 구조화된 오류로 표시됩니다.
# Python
from webiq import WebIQClient
from webiq.errors import APIStatusError
client = WebIQClient(api_key="your-api-key")
try:
response = client.browse.fetch("https://www.not-microsoft.com")
except APIStatusError as e:
print(f"Status: {e.status_code}") # e.g. 404
print(f"Message: {e}") # e.g. "No result is found"
if isinstance(e.body, dict):
print(f"Error code: {e.body.get('errorCode')}") # e.g. "BrowseApiDocNotFound"
print(f"Category: {e.body.get('errorCategory')}") # e.g. "UserError"
print(f"Details: {e.body.get('technicalDetails')}") # e.g. "NotFound"
print(f"Trace ID: {e.body.get('traceId')}")
print(f"Retry after: {e.body.get('retryAfter')}")
// TypeScript
import { WebIQClient, APIStatusError } from '@microsoft/webiq';
async function main() {
const client = new WebIQClient({ apiKey: 'your-api-key' });
try {
await client.browse.fetch('https://www.not-microsoft.com');
} catch (error) {
if (error instanceof APIStatusError) {
console.error(`Status: ${error.statusCode}`); // e.g. 404
console.error(`Message: ${error.message}`); // e.g. "No result is found"
// Full error body from the API response
if (error.body && typeof error.body === 'object') {
const body = error.body as Record<string, unknown>;
console.error(`Error code: ${body.errorCode}`); // e.g. "BrowseApiDocNotFound"
console.error(`Category: ${body.errorCategory}`); // e.g. "UserError"
console.error(`Details: ${body.technicalDetails}`); // e.g. "NotFound"
console.error(`Trace ID: ${body.traceId}`); // for debugging with support
console.error(`Retry after: ${body.retryAfter}`); // for retryable errors
}
}
}
}
main().catch(console.error);
디버깅 팁
-
traceId— 모든 응답에는 엔드 투 엔드 디버깅을 위한traceId필드가 포함됩니다. 지원에 문의할 때 이를 포함하세요. - 원격 분석 후크 - 콜백을 연결하여 모든 요청 시도, 상태 코드 및 타이밍을 기록합니다.
-
오류 본문 —
APIStatusError.body에는errorCode,errorCategory,technicalDetails, 및traceId를 포함한 전체 서버 응답이 포함됩니다.