Il client sincrono (Olostep) fornisce un’interfaccia bloccante perfetta per script e casi d’uso semplici.
from olostep import Olostep# Fornisci la chiave API passando il parametro 'api_key' o# impostando la variabile d'ambiente OLOSTEP_API_KEY# Il client sincrono gestisce automaticamente la gestione delle risorse# Non è necessario chiudere esplicitamente - le risorse vengono pulite dopo ogni operazioneclient = Olostep(api_key="YOUR_REAL_KEY")scrape_result = client.scrapes.create(url_to_scrape="https://example.com")
from olostep import Olostepclient = Olostep(api_key="your-api-key")# Elabora più URL in modo efficientebatch = client.batches.create( urls=[ "https://www.google.com/search?q=python", "https://www.google.com/search?q=javascript", "https://www.google.com/search?q=typescript" ])# Attendi il completamento ed elabora i risultatifor item in batch.items(): content = item.retrieve(["html"]) print(f"Processed {item.url}: {len(content.html_content)} bytes")
from olostep import Olostepclient = Olostep(api_key="your-api-key")# Estrai tutti i link da un sito webmaps = client.maps.create(url="https://example.com")# Ottieni tutti gli URL scopertiurls = []for url in maps.urls(): urls.append(url) if len(urls) >= 10: # Limite per demo breakprint(f"Found {len(urls)} URLs")
from olostep import Olostepclient = Olostep(api_key="your-api-key")# Ottieni risposte dalle pagine web usando l'AIanswer = client.answers.create( task="What is the main topic of https://example.com?")print(f"Answer: {answer.answer}")
Il client asincrono (AsyncOlostep) è il client consigliato per applicazioni ad alte prestazioni, servizi backend e quando hai bisogno di gestire molte richieste concorrenti.
from olostep import AsyncOlostep# Fornisci la chiave API passando il parametro 'api_key' o# impostando la variabile d'ambiente OLOSTEP_API_KEY# GESTIONE DELLE RISORSE# ======================# L'SDK supporta due modelli di utilizzo per la gestione delle risorse:# 1. Gestore di Contesto (Consigliato per uso una tantum):# Gestisce automaticamente la pulizia delle risorseasync with AsyncOlostep(api_key="YOUR_REAL_KEY") as client: scrape_result = await client.scrapes.create(url_to_scrape="https://example.com")# Il trasporto viene chiuso automaticamente qui# 2. Chiusura Esplicita (Per servizi di lunga durata):# Richiede la pulizia manuale delle risorseclient = AsyncOlostep(api_key="YOUR_REAL_KEY")try: scrape_result = await client.scrapes.create(url_to_scrape="https://example.com")finally: await client.close() # Chiudi manualmente il trasporto
import asynciofrom olostep import AsyncOlostepasync def main(): async with AsyncOlostep(api_key="your-api-key") as client: # Elabora più URL in modo efficiente batch = await client.batches.create( urls=[ "https://www.google.com/search?q=python", "https://www.google.com/search?q=javascript", "https://www.google.com/search?q=typescript" ] ) # Attendi il completamento ed elabora i risultati async for item in batch.items(): content = await item.retrieve(["html"]) print(f"Processed {item.url}: {len(content.html_content)} bytes")asyncio.run(main())
import asynciofrom olostep import AsyncOlostepasync def main(): async with AsyncOlostep(api_key="your-api-key") as client: # Estrai tutti i link da un sito web maps = await client.maps.create(url="https://example.com") # Ottieni tutti gli URL scoperti urls = [] async for url in maps.urls(): urls.append(url) if len(urls) >= 10: # Limite per demo break print(f"Found {len(urls)} URLs")asyncio.run(main())
import asynciofrom olostep import AsyncOlostepasync def main(): async with AsyncOlostep(api_key="your-api-key") as client: # Ottieni risposte dalle pagine web usando l'AI answer = await client.answers.create( task="What is the main topic of https://example.com?" ) print(f"Answer: {answer.answer}")asyncio.run(main())
Cattura tutti gli errori SDK utilizzando la classe di eccezione base:
from olostep import Olostep, Olostep_BaseErrorclient = Olostep(api_key="your-api-key")try: result = client.scrapes.create(url_to_scrape="https://example.com")except Olostep_BaseError as e: print(f"Error has occurred: {type(e).__name__}") print(f"Error message: {e}")
Per informazioni dettagliate sulla gestione degli errori, inclusa la gerarchia completa delle eccezioni e le opzioni di gestione degli errori granulari, vedi Gestione Dettagliata degli Errori.
L’SDK riprova automaticamente in caso di errori transitori (problemi di rete, problemi temporanei del server) basati sulla configurazione di RetryStrategy. Puoi personalizzare il comportamento di riprova passando un’istanza di RetryStrategy quando crei il client:
from olostep import Olostep, Countryclient = Olostep(api_key="your-api-key")batch = client.batches.create([ {"url": "https://www.google.com/search?q=python", "custom_id": "search_1"}, {"url": "https://www.google.com/search?q=javascript", "custom_id": "search_2"}, {"url": "https://www.google.com/search?q=typescript", "custom_id": "search_3"}],country=Country.US,parser="@olostep/google-search")# Elabora i risultati per ID personalizzato# Quando si utilizza un parser, recupera il contenuto JSON invece di HTMLfor item in batch.items(): if item.custom_id == "search_2": content = item.retrieve(["json"]) print(f"Search result: {content.json_content}")
from olostep import Olostepclient = Olostep(api_key="your-api-key")# Prima crea una rispostacreated_answer = client.answers.create( task="What is the main topic of https://example.com?")# Poi recuperala usando l'IDanswer = client.answers.get(answer_id=created_answer.id)print(f"Answer: {answer.answer}")
La classe RetryStrategy controlla come l’SDK Olostep gestisce gli errori API transitori tramite riprove automatiche con backoff esponenziale e jitter. Questo aiuta a garantire un funzionamento affidabile in ambienti di produzione dove problemi di rete temporanei, limiti di velocità e sovraccarico del server possono causare fallimenti intermittenti.
from olostep import AsyncOlostep, RetryStrategy# Crea strategia di riprova personalizzataretry_strategy = RetryStrategy( max_retries=3, initial_delay=1.0, jitter_min=0.2, # 20% di jitter minimo jitter_max=0.8, # 80% di jitter massimo)# Usa con il clientasync with AsyncOlostep( api_key="your-api-key", retry_strategy=retry_strategy) as client: result = await client.scrapes.create("https://example.com")
# Disabilita le riprove per feedback immediato di fallimentoretry_strategy = RetryStrategy(max_retries=0)client = AsyncOlostep(api_key="your-api-key", retry_strategy=retry_strategy)
# Ottimizzato per operazioni ad alto volumeretry_strategy = RetryStrategy( max_retries=2, initial_delay=0.5, jitter_min=0.1, jitter_max=0.3 # Jitter più basso per tempistiche più prevedibili)# Durata massima: ~1.95s
Il jitter aggiunge randomizzazione per prevenire problemi di “thundering herd” quando molti client riprovano contemporaneamente. Il jitter è calcolato come:
Quando tutte le riprove sono esaurite, viene sollevato l’errore originale:
try: result = await client.scrapes.create("https://example.com")except OlostepServerError_TemporaryIssue as e: print(f"Failed after all retries: {e}") # Gestisci il fallimento permanente
L’SDK Olostep fornisce una gerarchia completa di eccezioni per diversi scenari di fallimento. Tutte le eccezioni ereditano da Olostep_BaseError.Ci sono tre tipi principali di errori che ereditano direttamente da Olostep_BaseError:
Olostep_APIConnectionError - Fallimenti di connessione a livello di rete
OlostepServerError_BaseError - Errori sollevati (in qualche modo) dal server API
OlostepClientError_BaseError - Errori sollevati dal client SDK
Olostep_APIConnectionError è separato dagli errori del server perché rappresenta fallimenti a livello di rete che si verificano prima che l’API possa elaborare la richiesta. Questi sono problemi a livello di trasporto (fallimenti DNS o HTTP, timeout, connessione rifiutata, ecc.) piuttosto che errori a livello di API. I codici di stato HTTP (4xx, 5xx) sono considerati risposte API e sono categorizzati come errori del server, anche se indicano problemi.
Per la maggior parte dei casi d’uso, cattura l’errore base e stampa il nome dell’errore:
from olostep import AsyncOlostep, Olostep_BaseErrortry: result = await client.scrapes.create(url_to_scrape="https://example.com")except Olostep_BaseError as e: print(f"Error has occurred: {type(e).__name__}") print(f"Error message: {e}")
Questo approccio cattura tutti gli errori SDK e fornisce informazioni chiare su cosa è andato storto. Il nome dell’errore (es. OlostepServerError_AuthFailed) è abbastanza descrittivo per comprendere il problema.
Se hai bisogno di una gestione degli errori più specifica, cattura direttamente i tipi di errore specifici. Evita di usare OlostepServerError_BaseError o OlostepClientError_BaseError - queste classi base indicano solo chi ha sollevato l’errore (server vs client), non chi è responsabile di risolverlo. Questo è un dettaglio di implementazione che non aiuta con la logica di gestione degli errori.Invece, cattura i tipi di errore specifici che indicano il problema reale:
from olostep import ( AsyncOlostep, Olostep_BaseError, Olostep_APIConnectionError, OlostepServerError_AuthFailed, OlostepServerError_CreditsExhausted, OlostepClientError_NoAPIKey,)try: result = await client.scrapes.create(url_to_scrape="https://example.com")except Olostep_APIConnectionError as e: print(f"Network error: {type(e).__name__}")except OlostepServerError_AuthFailed: print("Invalid API key")except OlostepServerError_CreditsExhausted: print("Credits exhausted")except OlostepClientError_NoAPIKey: print("API key not provided")except Olostep_BaseError as e: print(f"Error has occurred: {type(e).__name__}")