Sofya

Uma API que oferece a agentes de IA ferramentas de busca na web, captura de páginas como markdown, extração por IA e pesquisa aprofundada.

Documentação

Documentação da API

Tudo o que você precisa para integrar a Sofya ao seu agente de IA.

llms.txt · SKILL.md

Copiar como Markdown

Copiar como Texto

Início Rápido

2. Obtenha créditos

Contas GitHub elegíveis recebem 1.000 créditos/mês no plano gratuito. Precisa de mais? Compre créditos a US$ 0,005 cada.

3. Pesquise na web

curl -X POST https://sofya.co/v1/search \
  -H "Authorization: Bearer ay_live_..." \
  -H "Content-Type: application/json" \
  -d '{"query": "latest AI news"}'

Autenticação

Todas as solicitações de API exigem uma chave de API no cabeçalho Authorization.

Authorization: Bearer ay_live_your_key_here

MCP Model Context Protocol

Conecte a Sofya diretamente ao Claude Code, Cursor ou qualquer cliente compatível com MCP. Seu agente de IA obtém ferramentas de pesquisa, busca, extração e pesquisa profunda, sem necessidade de chamadas REST.

Vá para o seu painel e clique no botão de copiar para o seu cliente. O comando já vem preenchido com sua chave de API.

Claude Code

claude mcp add --transport http sofya https://mcp.sofya.co/mcp \
  --header "Authorization: Bearer ay_live_..."

Cursor · ~/.cursor/mcp.json

{
  "mcpServers": {
    "sofya": {
      "url": "https://mcp.sofya.co/mcp",
      "headers": { "Authorization": "Bearer ay_live_..." }
    }
  }
}

Codex · ~/.codex/config.toml

[mcp_servers.sofya]
url = "https://mcp.sofya.co/mcp"
http_headers = { "Authorization" = "Bearer ay_live_..." }

Windsurf · ~/.codeium/windsurf/mcp_config.json

{
  "mcpServers": {
    "sofya": {
      "serverUrl": "https://mcp.sofya.co/mcp",
      "headers": { "Authorization": "Bearer ay_live_..." }
    }
  }
}

VS Code Copilot ·.vscode/mcp.json

{
  "servers": {
    "sofya": {
      "type": "http",
      "url": "https://mcp.sofya.co/mcp",
      "headers": { "Authorization": "Bearer ay_live_..." }
    }
  }
}

Sua chave de API é enviada via cabeçalho HTTP. O modelo de IA nunca a vê.

Ferramentas Disponíveis

pesquisa

Pesquisa na web com extração de conteúdo de páginas e respostas opcionais de IA. 1-3 créditos (+5 com resposta de IA).

busca

Busca URLs como markdown limpo. 1 crédito por URL.

extração

Extração de dados estruturados com IA. 5 créditos.

pesquisa profunda

Pesquisa profunda com múltiplas consultas e síntese de IA. 25 créditos.

Definições de Ferramentas para Claude e GPT

Copie e cole esses esquemas de ferramentas em suas chamadas de API da Anthropic ou OpenAI. Seu modelo obtém as ferramentas da Sofya sem que você precise escrever definições.

Anthropic (Claude)

Passe este array como o parâmetro tools na sua solicitação /v1/messages. Quando o Claude retornar um bloco tool_use, chame o endpoint REST correspondente da Sofya e retorne o resultado como um tool_result.

[
  {
    "name": "sofya_search",
    "description": "Search the web for current information. Returns extracted page content, not just snippets. Set topic='news' for current events. Set include_answer=true for an AI-synthesized answer (+5 credits). Returns: query, answer, results [{title, url, content, description, fetched, published_date}], search_depth, topic, elapsed_ms, credits_used, credits_remaining, altered_query.",
    "input_schema": {
      "type": "object",
      "required": ["query"],
      "properties": {
        "query": {"type": "string", "description": "The search query"},
        "search_depth": {"type": "string", "description": "\"snippets\" (1 credit) or \"basic\" (3, default)"},
        "max_results": {"type": "integer", "description": "Number of results, 1-20 (default 10)"},
        "include_answer": {"type": "boolean", "description": "Add AI answer synthesized from results (+5 credits)"},
        "topic": {"type": "string", "description": "\"general\" (default) or \"news\""},
        "freshness": {"type": "string", "description": "\"day\", \"week\", \"month\", \"year\", or \"YYYY-MM-DD:YYYY-MM-DD\""},
        "include_domains": {"type": "array", "items": {"type": "string"}, "description": "Only these domains (max 10)"},
        "exclude_domains": {"type": "array", "items": {"type": "string"}, "description": "Exclude these domains (max 10)"}
      }
    }
  },
  {
    "name": "sofya_fetch",
    "description": "Fetch one or more URLs and return their content as clean markdown. Supports web pages, PDF, DOCX, and other document formats. 1 credit per URL, max 10 URLs. Failed URLs are not charged. Returns: results [{title, url, content, raw_html, published_time, success, error}], credits_used, credits_remaining.",
    "input_schema": {
      "type": "object",
      "required": ["urls"],
      "properties": {
        "urls": {"type": "array", "items": {"type": "string"}, "description": "URLs to fetch (max 10)"},
        "include_raw_html": {"type": "boolean", "description": "Include raw HTML source in response (default false)"}
      }
    }
  },
  {
    "name": "sofya_extract",
    "description": "Fetch a URL and extract specific information using AI. Use when you need structured data (pricing, specs, contact info) rather than raw content. 5 credits. If the page has no usable text it returns empty content with usage.low_content=true instead of a fabricated answer. Returns: content, url, credits_used, credits_remaining, usage (input_tokens, output_tokens, content_chars, low_content).",
    "input_schema": {
      "type": "object",
      "required": ["url", "prompt"],
      "properties": {
        "url": {"type": "string", "description": "The URL to extract from"},
        "prompt": {"type": "string", "description": "What to extract, e.g. \"list all pricing tiers with features\""}
      }
    }
  },
  {
    "name": "sofya_research",
    "description": "Deep research on a topic. Decomposes query into sub-queries, searches and reads multiple sources in parallel, synthesizes a structured report with citations. 25 credits. Returns: query, report, sources [{title, url, fetched}], sub_queries, credits_used, credits_remaining, usage.",
    "input_schema": {
      "type": "object",
      "required": ["query"],
      "properties": {
        "query": {"type": "string", "description": "The research question or topic"},
        "topic": {"type": "string", "description": "\"general\" (default) or \"news\""},
        "freshness": {"type": "string", "description": "\"day\", \"week\", \"month\", \"year\", or \"YYYY-MM-DD:YYYY-MM-DD\""},
        "max_sources": {"type": "integer", "description": "Max sources to use, 5-30 (default 20)"}
      }
    }
  }
]

OpenAI (GPT)

Passe este array como o parâmetro tools na sua solicitação /chat/completions. Quando o modelo retornar tool_calls, chame o endpoint REST correspondente da Sofya e retorne o resultado como uma mensagem role: "tool".

[
  {
    "type": "function",
    "function": {
      "name": "sofya_search",
      "description": "Search the web for current information. Returns extracted page content, not just snippets. Set topic='news' for current events. Set include_answer=true for an AI-synthesized answer (+5 credits). Returns: query, answer, results [{title, url, content, description, fetched, published_date}], search_depth, topic, elapsed_ms, credits_used, credits_remaining, altered_query.",
      "parameters": {
        "type": "object",
        "required": ["query"],
        "properties": {
          "query": {"type": "string", "description": "The search query"},
          "search_depth": {"type": "string", "description": "\"snippets\" (1 credit) or \"basic\" (3, default)"},
          "max_results": {"type": "integer", "description": "Number of results, 1-20 (default 10)"},
          "include_answer": {"type": "boolean", "description": "Add AI answer synthesized from results (+5 credits)"},
          "topic": {"type": "string", "description": "\"general\" (default) or \"news\""},
          "freshness": {"type": "string", "description": "\"day\", \"week\", \"month\", \"year\", or \"YYYY-MM-DD:YYYY-MM-DD\""},
          "include_domains": {"type": "array", "items": {"type": "string"}, "description": "Only these domains (max 10)"},
          "exclude_domains": {"type": "array", "items": {"type": "string"}, "description": "Exclude these domains (max 10)"}
        },
        "additionalProperties": false
      }
    }
  },
  {
    "type": "function",
    "function": {
      "name": "sofya_fetch",
      "description": "Fetch one or more URLs and return their content as clean markdown. Supports web pages, PDF, DOCX, and other document formats. 1 credit per URL, max 10 URLs. Failed URLs are not charged. Returns: results [{title, url, content, raw_html, published_time, success, error}], credits_used, credits_remaining.",
      "parameters": {
        "type": "object",
        "required": ["urls"],
        "properties": {
          "urls": {"type": "array", "items": {"type": "string"}, "description": "URLs to fetch (max 10)"},
          "include_raw_html": {"type": "boolean", "description": "Include raw HTML source in response (default false)"}
        },
        "additionalProperties": false
      }
    }
  },
  {
    "type": "function",
    "function": {
      "name": "sofya_extract",
      "description": "Fetch a URL and extract specific information using AI. Use when you need structured data (pricing, specs, contact info) rather than raw content. 5 credits. If the page has no usable text it returns empty content with usage.low_content=true instead of a fabricated answer. Returns: content, url, credits_used, credits_remaining, usage (input_tokens, output_tokens, content_chars, low_content).",
      "parameters": {
        "type": "object",
        "required": ["url", "prompt"],
        "properties": {
          "url": {"type": "string", "description": "The URL to extract from"},
          "prompt": {"type": "string", "description": "What to extract, e.g. \"list all pricing tiers with features\""}
        },
        "additionalProperties": false
      }
    }
  },
  {
    "type": "function",
    "function": {
      "name": "sofya_research",
      "description": "Deep research on a topic. Decomposes query into sub-queries, searches and reads multiple sources in parallel, synthesizes a structured report with citations. 25 credits. Returns: query, report, sources [{title, url, fetched}], sub_queries, credits_used, credits_remaining, usage.",
      "parameters": {
        "type": "object",
        "required": ["query"],
        "properties": {
          "query": {"type": "string", "description": "The research question or topic"},
          "topic": {"type": "string", "description": "\"general\" (default) or \"news\""},
          "freshness": {"type": "string", "description": "\"day\", \"week\", \"month\", \"year\", or \"YYYY-MM-DD:YYYY-MM-DD\""},
          "max_sources": {"type": "integer", "description": "Max sources to use, 5-30 (default 20)"}
        },
        "additionalProperties": false
      }
    }
  }
]

Exemplo: conectando tudo

Quando o modelo chamar uma ferramenta, mapeie o nome da ferramenta para o endpoint da Sofya e encaminhe os argumentos:

# Python - handle tool calls from Claude or GPT
TOOL_TO_ENDPOINT = {
    "sofya_search": "/v1/search",
    "sofya_fetch": "/v1/fetch",
    "sofya_extract": "/v1/extract",
    "sofya_research": "/v1/research",
}

def call_sofya(tool_name: str, args: dict) -> dict:
    import httpx
    resp = httpx.post(
        f"https://sofya.co{TOOL_TO_ENDPOINT[tool_name]}",
        headers={"Authorization": "Bearer ay_live_..."},
        json=args,
        timeout=120,
    )
    return resp.json()

Ferramentas Principais

POST /v1/search 1-3 créditos (+5 com resposta)

Pesquise na web. Retorna o conteúdo da página, não apenas trechos. Escolha uma profundidade de pesquisa para controlar o trade-off entre qualidade e custo. Adicione include_answer a qualquer profundidade para obter uma resposta sintetizada por IA (+5 créditos). Esta é uma alternativa leve ao endpoint de pesquisa profunda de 25 créditos.

snippets 1 crédito

Apenas trechos de SERP. Mais rápido.

basic 3 créditos (padrão)

Busca páginas e retorna conteúdo extraído (~5000 caracteres por resultado).

Corpo da Solicitação

{
  "query": "string",              // required
  "search_depth": "basic",        // "snippets" or "basic"
  "max_results": 10,               // 1-20
  "include_answer": false,         // AI answer from results (+5 credits). Combine with any depth for search + synthesis (e.g. basic = 8 credits)
  "include_domains": [],           // e.g. ["reddit.com", "github.com"]
  "exclude_domains": [],           // e.g. ["pinterest.com"]
  "topic": "general",             // "general" or "news"
  "freshness": null               // "day", "week", "month", "year", or "YYYY-MM-DD:YYYY-MM-DD"
}

Resposta

{
  "query": "latest AI news",
  "answer": "According to...",     // null unless include_answer
  "results": [
    {
      "title": "...",
      "url": "...",
      "content": "Extracted page content...",
      "description": "SERP snippet",
      "fetched": true,             // true if page was fetched, false if snippet only
      "published_date": "2026-03-08",  // YYYY-MM-DD, normalized from page metadata or SERP (or null)
      "sublinks": [],
      "table": {}
    }
  ],
  "search_depth": "basic",
  "topic": "general",
  "elapsed_ms": 4200,
  "credits_used": 3,
  "credits_remaining": 997,
  "altered_query": null            // if the query was auto-corrected
}

topic: "general" (padrão) para pesquisa na web, ou "news" para pesquisa específica de notícias. Use "news" para eventos atuais, notícias de última hora, política ou qualquer consulta sensível ao tempo. Retorna artigos com datas de publicação.

freshness: "day", "week", "month", "year", ou intervalo personalizado "YYYY-MM-DD:YYYY-MM-DD"

curl -X POST https://sofya.co/v1/search \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ay_live_..." \
  -d '{"query": "latest AI news", "search_depth": "basic"}'
import httpx

resp = httpx.post("https://sofya.co/v1/search",
    headers={"Authorization": "Bearer ay_live_..."},
    json={"query": "latest AI news", "search_depth": "basic"})
print(resp.json())
const resp = await fetch("https://sofya.co/v1/search", {
  method: "POST",
  headers: { "Content-Type": "application/json", "Authorization": "Bearer ay_live_..." },
  body: JSON.stringify({ query: "latest AI news", search_depth: "basic" })
});
console.log(await resp.json());

POST /v1/fetch 1 crédito por URL

Busque uma ou mais URLs e retorne seu conteúdo como markdown limpo.

Corpo da Solicitação

{
  "urls": ["string", ...],       // required, max 10
  "include_raw_html": false      // optional - include raw HTML source
}

Resposta

{
  "results": [
    {
      "title": "Example Page",
      "url": "https://example.com",
      "content": "# Markdown content...",
      "raw_html": null,
      "published_time": null,           // YYYY-MM-DD, extracted from page metadata when available (or null)
      "success": true,
      "error": null
    }
  ],
  "credits_used": 1,
  "credits_remaining": 999
}
curl -X POST https://sofya.co/v1/fetch \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ay_live_..." \
  -d '{"urls": ["https://example.com"]}'
import httpx

resp = httpx.post("https://sofya.co/v1/fetch",
    headers={"Authorization": "Bearer ay_live_..."},
    json={"urls": ["https://example.com"]})
print(resp.json())
const resp = await fetch("https://sofya.co/v1/fetch", {
  method: "POST",
  headers: { "Content-Type": "application/json", "Authorization": "Bearer ay_live_..." },
  body: JSON.stringify({ urls: ["https://example.com"] })
});
console.log(await resp.json());

POST /v1/extract 5 créditos

Busque uma página da web e extraia informações específicas usando IA. Custa 5 créditos. Se a página não tiver texto utilizável (corpo vazio ou renderizado por JavaScript), o modelo não é chamado e content é retornado vazio com usage.low_content: true em vez de uma resposta fabricada.

Corpo da Solicitação

{
  "url": "string",          // required
  "prompt": "string"        // required, what to extract
}

Resposta

{
  "content": "Extracted information...",
  "url": "https://example.com",
  "credits_used": 5,
  "credits_remaining": 995,
  "usage": { "input_tokens": 90, "output_tokens": 24, "content_chars": 4820, "low_content": false }
}

usage.content_chars é o número de caracteres do texto da página que o modelo recebeu; usage.low_content é verdadeiro quando a página tinha texto insuficiente para extração (o modelo foi ignorado). Use esses campos para detectar páginas vazias ou não renderizáveis.

curl -X POST https://sofya.co/v1/extract \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ay_live_..." \
  -d '{"url": "https://example.com", "prompt": "Summarize this page"}'
import httpx

resp = httpx.post("https://sofya.co/v1/extract",
    headers={"Authorization": "Bearer ay_live_..."},
    json={"url": "https://example.com", "prompt": "Summarize this page"})
print(resp.json())
const resp = await fetch("https://sofya.co/v1/extract", {
  method: "POST",
  headers: { "Content-Type": "application/json", "Authorization": "Bearer ay_live_..." },
  body: JSON.stringify({ url: "https://example.com", prompt: "Summarize this page" })
});
console.log(await resp.json());

POST /v1/research 25 créditos

Pesquisa profunda sobre qualquer tópico. Decompõe sua consulta em subconsultas, pesquisa e lê múltiplas fontes em paralelo e, em seguida, sintetiza um relatório estruturado com citações. Custa 25 créditos.

Corpo da Solicitação

{
  "query": "string",              // required
  "topic": "general",             // "general" or "news"
  "freshness": null,              // "day", "week", "month", "year", or "YYYY-MM-DD:YYYY-MM-DD"
  "max_sources": 20               // 5-30
}

Resposta

{
  "query": "How do modern LLMs handle long context?",
  "report": "## Key Findings\n\n- ...",
  "sources": [
    {
      "title": "Scaling Transformer Context Windows",
      "url": "https://arxiv.org/abs/...",
      "fetched": true
    }
  ],
  "sub_queries": [
    "transformer context window scaling techniques",
    "RoPE positional encoding extensions"
  ],
  "credits_used": 25,
  "credits_remaining": 975,
  "usage": { "input_tokens": 12400, "output_tokens": 1850 }
}
curl -X POST https://sofya.co/v1/research \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ay_live_..." \
  -d '{"query": "How do modern LLMs handle long context?"}'
import httpx

resp = httpx.post("https://sofya.co/v1/research",
    headers={"Authorization": "Bearer ay_live_..."},
    json={"query": "How do modern LLMs handle long context?"},
    timeout=120)
print(resp.json())
const resp = await fetch("https://sofya.co/v1/research", {
  method: "POST",
  headers: { "Content-Type": "application/json", "Authorization": "Bearer ay_live_..." },
  body: JSON.stringify({ query: "How do modern LLMs handle long context?" })
});
console.log(await resp.json());

Conta

GET /v1/auth/me

Obtenha informações da sua conta, incluindo créditos, plano e total de solicitações.

Resposta

{
  "credits": 997,
  "plan_credits": 997,
  "purchased_credits": 0,
  "is_free_tier": true,
  "credits_reset_at": "2026-04-04T12:00:00Z",
  "total_requests": 3,
  "api_key": "ay_live_...",
  "last_login_method": "github",
  "email": "user@example.com",
  "github_username": "octocat"
}

GET /v1/auth/transactions

Obtenha suas transações de crédito recentes (recargas). Retorna as últimas 50.

Resposta

[
  {
    "id": "uuid",
    "type": "credit",
    "amount": 5000,
    "endpoint": "top-up",
    "balance_after": 6000,
    "created_at": "2026-02-22T12:00:00Z"
  }
]

GET /v1/auth/usage

Obtenha o detalhamento do uso diário, por endpoint.

Parâmetros de Consulta

days=7           // 1-90, default 7
offset_days=0    // pagination offset in days

Resposta

[
  {
    "date": "2026-02-22",
    "endpoint": "/v1/search",
    "request_count": 312,
    "total_credits": 312
  }
]

Cobrança

POST /v1/billing/checkout

Compre créditos (PAYG). Compra mínima: 2.000 créditos (US$ 10). Redireciona para a página de pagamento.

Corpo da Solicitação

{
  "credits": 5000           // required, minimum ~2000
}

Resposta

{
  "checkout_url": "https://checkout.creem.io/pay/..."
}

Limites de Taxa

Os endpoints da API REST têm limite de 10 solicitações por segundo por chave de API. Isso se aplica a todos os endpoints /v1/*. O MCP (/mcp) tem limite de 30 solicitações por segundo.

Se você exceder o limite, a API retorna 429 Too Many Requests com um cabeçalho Retry-After indicando quantos segundos aguardar antes de tentar novamente.

Resposta 429

HTTP/1.1 429 Too Many Requests
Retry-After: 0.85

{
  "detail": "Rate limit exceeded. 10 requests per second."
}

Solicitações com limite de taxa não consomem créditos. Implemente backoff exponencial ou respeite o cabeçalho Retry-After para obter melhores resultados.

Códigos de Erro

CódigoStatusDescrição
400Solicitação InválidaParâmetros inválidos (ex.: consulta ausente, formato de freshness inválido)
401Não AutorizadoChave de API inválida ou ausente
402Pagamento NecessárioCréditos insuficientes
403ProibidoProibido
429Muitas SolicitaçõesLimite de taxa excedido. Verifique o cabeçalho Retry-After.
502Gateway InválidoErro interno. Tente novamente.
504Tempo Esgotado do GatewayA pesquisa expirou. Tente uma consulta mais simples ou menos fontes.

Status e Monitoramento

A página pública de status da Sofya está hospedada externamente em status.sofya.co. Ela verifica a API a cada 60 segundos a partir de um servidor separado, para continuar reportando com precisão mesmo se a Sofya estiver fora do ar. Todos os feeds são públicos, sem necessidade de chave de API.

Feeds JSON

  • /api/v2/summary.json — Compatível com Atlassian Statuspage. Substituição direta para qualquer ferramenta que já leia status.anthropic.com, status do GitHub, etc.
  • /api/v2/status.json — Apenas metadados da página + indicador geral. Poll mais barato se você só precisa de online/offline.
  • /api/status.json — Feed mais rico nativo da Sofya: latência por componente, uptime de 24h / 90d, último erro.

Exemplo

$ curl https://status.sofya.co/api/v2/status.json
{
  "page": { "id": "sofya", "name": "Sofya Status", ... },
  "status": {
    "indicator": "none",
    "description": "All Systems Operational"
  }
}

O campo indicator segue a convenção do Statuspage: none (operacional), minor (degradado) ou major (fora do ar). Trate qualquer valor diferente de none como motivo para exibir um aviso aos seus usuários ou reduzir as tentativas. # Documentação da API Sofya Base URL: https://sofya.co\

Início Rápido

1. Cadastre-se via GitHub

Visite o painel e faça login com o GitHub para começar.

2. Obtenha créditos

Contas GitHub elegíveis recebem 1.000 créditos/mês no plano gratuito. Precisa de mais? Compre créditos a $0,005 cada no painel.

3. Pesquise na web

\``bash curl -X POST https://sofya.co/v1/search \\ -H "Authorization: Bearer ay\_live\_..." \\ -H "Content-Type: application/json" \\ -d '{"query": "latest AI news"}' \``\

Autenticação

Todas as solicitações à API exigem uma chave de API no cabeçalho Authorization\.

\`` Authorization: Bearer ay\_live\_your\_key\_here \``\


MCP (Model Context Protocol)

Conecte a Sofya diretamente ao Claude Code, Cursor ou qualquer cliente compatível com MCP. Seu agente de IA obtém ferramentas de busca, obtenção, extração e pesquisa, sem necessidade de chamadas REST.

Vá ao seu painel e clique no botão de copiar para o seu cliente. O comando já vem preenchido com sua chave de API.

Claude Code

\``bash claude mcp add --transport http sofya https://mcp.sofya.co/mcp \\ --header "Authorization: Bearer ay\_live\_..." \``\

Cursor (~/.cursor/mcp.json\)

\``json { "mcpServers": { "sofya": { "url": "https://mcp.sofya.co/mcp", "headers": { "Authorization": "Bearer ay\_live\_..." } } } } \``\

Codex (~/.codex/config.toml\)

\``toml \[mcp\_servers.sofya\] url = "https://mcp.sofya.co/mcp" http\_headers = { "Authorization" = "Bearer ay\_live\_..." } \``\

Windsurf (~/.codeium/windsurf/mcp\_config.json\)

\``json { "mcpServers": { "sofya": { "serverUrl": "https://mcp.sofya.co/mcp", "headers": { "Authorization": "Bearer ay\_live\_..." } } } } \``\

VS Code Copilot (.vscode/mcp.json\)

\``json { "servers": { "sofya": { "type": "http", "url": "https://mcp.sofya.co/mcp", "headers": { "Authorization": "Bearer ay\_live\_..." } } } } \``\

Sua chave de API é enviada via cabeçalho HTTP. O modelo de IA nunca a vê.

Ferramentas disponíveis:

  • search\ · Busca na web com extração de conteúdo da página. 1-3 créditos, +5 com include\_answer: true\ para uma resposta sintetizada por IA. Esta é uma alternativa leve ao endpoint de pesquisa completo.
  • fetch\ · Busca URLs como markdown limpo. 1 crédito por URL.
  • extract\ · Extração de dados estruturados com IA. 5 créditos.
  • research\ · Pesquisa profunda com múltiplas consultas e síntese por IA. 25 créditos.

Ferramentas Principais

POST /v1/search · 1-3 créditos (+5 com resposta de IA)

Pesquise na web. Retorna o conteúdo da página, não apenas trechos. Escolha uma profundidade de busca para controlar o equilíbrio entre qualidade e custo.

ProfundidadeCréditosDescrição
snippets1Apenas trechos de SERP. Mais rápido.
basic3Busca páginas, retorna conteúdo extraído (~5000 caracteres por resultado). Padrão.

Dica: Adicione include\_answer: true\ a qualquer profundidade para uma resposta sintetizada por IA (+5 créditos). Por exemplo, basic + answer = 8 créditos. Esta é uma alternativa leve ao endpoint de pesquisa de 25 créditos quando você precisa de uma síntese rápida sem decomposição em múltiplas consultas.

Solicitação:

\``json { "query": "string", "search\_depth": "basic", "max\_results": 10, "include\_answer": false, "include\_domains": \[\], "exclude\_domains": \[\], "topic": "general", "freshness": null } \``\

Resposta:

\``json { "query": "latest AI news", "answer": null, "results": \[ { "title": "...", "url": "...", "content": "Extracted page content...", "description": "SERP snippet", "fetched": true, "published\_date": "2026-03-08", "sublinks": \[\], "table": {} } \], "search\_depth": "basic", "topic": "general", "elapsed\_ms": 4200, "credits\_used": 3, "credits\_remaining": 997, "altered\_query": null } \``\

curl:

\``bash curl -X POST https://sofya.co/v1/search \\ -H "Content-Type: application/json" \\ -H "Authorization: Bearer ay\_live\_..." \\ -d '{"query": "latest AI news", "search\_depth": "basic"}' \``\

Python:

\``python import httpx resp = httpx.post("https://sofya.co/v1/search", headers={"Authorization": "Bearer ay\_live\_..."}, json={"query": "latest AI news", "search\_depth": "basic"}) print(resp.json()) \``\

JavaScript:

\``javascript const resp = await fetch("https://sofya.co/v1/search", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer ay\_live\_..." }, body: JSON.stringify({ query: "latest AI news", search\_depth: "basic" }) }); console.log(await resp.json()); \``\

POST /v1/fetch · 1 crédito por URL

Busque uma ou mais URLs e retorne seu conteúdo como markdown limpo. Máximo de 10 URLs por solicitação. URLs com falha não são cobradas.

Solicitação:

\``json { "urls": \["string",...\], "include\_raw\_html": false } \``\

Resposta:

\``json { "results": \[ { "title": "Example Page", "url": "https://example.com", "content": "# Markdown content...", "raw\_html": null, "published\_time": null, // YYYY-MM-DD, extracted from page metadata when available (or null) "success": true, "error": null } \], "credits\_used": 1, "credits\_remaining": 999 } \``\

curl:

\``bash curl -X POST https://sofya.co/v1/fetch \\ -H "Content-Type: application/json" \\ -H "Authorization: Bearer ay\_live\_..." \\ -d '{"urls": \["https://example.com"\]}' \``\

Python:

\``python import httpx resp = httpx.post("https://sofya.co/v1/fetch", headers={"Authorization": "Bearer ay\_live\_..."}, json={"urls": \["https://example.com"\]}) print(resp.json()) \``\

JavaScript:

\``javascript const resp = await fetch("https://sofya.co/v1/fetch", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer ay\_live\_..." }, body: JSON.stringify({ urls: \["https://example.com"\] }) }); console.log(await resp.json()); \``\

POST /v1/extract · 5 créditos

Busque uma página da web e extraia informações específicas usando IA. Custa 5 créditos.

Solicitação:

\``json { "url": "string", "prompt": "string" } \``\

Resposta:

\``json { "content": "Extracted information...", "url": "https://example.com", "credits\_used": 5, "credits\_remaining": 995, "usage": { "input\_tokens": 90, "output\_tokens": 24 } } \``\

curl:

\``bash curl -X POST https://sofya.co/v1/extract \\ -H "Content-Type: application/json" \\ -H "Authorization: Bearer ay\_live\_..." \\ -d '{"url": "https://example.com", "prompt": "Summarize this page"}' \``\

Python:

\``python import httpx resp = httpx.post("https://sofya.co/v1/extract", headers={"Authorization": "Bearer ay\_live\_..."}, json={"url": "https://example.com", "prompt": "Summarize this page"}) print(resp.json()) \``\

JavaScript:

\``javascript const resp = await fetch("https://sofya.co/v1/extract", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer ay\_live\_..." }, body: JSON.stringify({ url: "https://example.com", prompt: "Summarize this page" }) }); console.log(await resp.json()); \``\

POST /v1/research · 25 créditos

Pesquisa profunda sobre qualquer tópico. Decompõe sua consulta em subconsultas, busca e lê múltiplas fontes em paralelo e, em seguida, sintetiza um relatório estruturado com citações. Custa 25 créditos.

Solicitação:

\``json { "query": "string", "topic": "general", "freshness": null, "max\_sources": 20 } \``\

Resposta:

\``json { "query": "How do modern LLMs handle long context?", "report": "## Key Findings\\n\\n-...", "sources": \[ { "title": "Scaling Transformer Context Windows", "url": "https://arxiv.org/abs/...", "fetched": true } \], "sub\_queries": \[ "transformer context window scaling techniques", "RoPE positional encoding extensions" \], "credits\_used": 25, "credits\_remaining": 975, "usage": { "input\_tokens": 12400, "output\_tokens": 1850 } } \``\

curl:

\``bash curl -X POST https://sofya.co/v1/research \\ -H "Content-Type: application/json" \\ -H "Authorization: Bearer ay\_live\_..." \\ -d '{"query": "How do modern LLMs handle long context?"}' \``\

Python:

\``python import httpx resp = httpx.post("https://sofya.co/v1/research", headers={"Authorization": "Bearer ay\_live\_..."}, json={"query": "How do modern LLMs handle long context?"}, timeout=120) print(resp.json()) \``\

JavaScript:

\``javascript const resp = await fetch("https://sofya.co/v1/research", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer ay\_live\_..." }, body: JSON.stringify({ query: "How do modern LLMs handle long context?" }) }); console.log(await resp.json()); \``\


Conta

GET /v1/auth/me

Obtenha informações da sua conta, incluindo créditos, nível e total de solicitações.

Resposta:

\``json { "credits": 997, "plan\_credits": 997, "purchased\_credits": 0, "is\_free\_tier": true, "credits\_reset\_at": "2026-04-04T12:00:00Z", "total\_requests": 3, "api\_key": "ay\_live\_...", "last\_login\_method": "github", "email": "user@example.com", "github\_username": "octocat" } \``\

GET /v1/auth/transactions

Obtenha suas transações de crédito recentes (recargas). Retorna as últimas 50.

Resposta:

\``json \[ { "id": "uuid", "type": "credit", "amount": 5000, "endpoint": "top-up", "balance\_after": 6000, "created\_at": "2026-02-22T12:00:00Z" } \] \``\

GET /v1/auth/usage

Obtenha o detalhamento do uso diário, por endpoint.

Parâmetros de consulta: days\ (1-90, padrão 7), offset\_days\ (deslocamento de paginação em dias, padrão 0)

Resposta:

\``json \[ { "date": "2026-02-22", "endpoint": "/v1/search", "request\_count": 312, "total\_credits": 312 } \] \``\


Cobrança

POST /v1/billing/checkout

Compre créditos (PAYG). Compra mínima: 2.000 créditos ($10).

Solicitação:

\``json { "credits": 5000 } \``\

Resposta:

\``json { "checkout\_url": "https://checkout.creem.io/pay/..." } \``\


Limites de Taxa

Os endpoints da API REST são limitados a 10 solicitações por segundo por chave de API. Isso se aplica a todos os endpoints /v1/\*\. O MCP (/mcp\) é limitado a 30 solicitações por segundo. Se você exceder o limite, a API retorna 429 Too Many Requests\ com um cabeçalho Retry-After\ indicando quantos segundos aguardar antes de tentar novamente.

Resposta 429:

\`` HTTP/1.1 429 Too Many Requests Retry-After: 0.85 { "detail": "Rate limit exceeded. 10 requests per second." } \``\

Solicitações limitadas por taxa não consomem créditos. Implemente backoff exponencial ou respeite o cabeçalho Retry-After\ para obter melhores resultados.


Códigos de Erro

CódigoStatusDescrição
400Solicitação InválidaParâmetros inválidos (ex.: consulta ausente, formato de atualização incorreto)
401Não AutorizadoChave de API inválida ou ausente
402Pagamento NecessárioCréditos insuficientes
403ProibidoProibido
429Muitas SolicitaçõesLimite de taxa excedido. Verifique o cabeçalho Retry-After\.
502Gateway InválidoErro interno. Tente novamente a solicitação.
504Tempo Esgotado do GatewayA pesquisa expirou. Tente uma consulta mais simples ou menos fontes.