Haldwani Times
Haldwani Times
Technology

jangada-ai 1.15.0

jangada-ai 1.15.0
Photo / Illustration: Haldwani Times Editorial Desk

Skip to main content Switch to mobile version jangada-ai 1.15.0 Camada fina e adaptável sobre SDKs de LLM: texto e vision, async, structured output, fluxos e fallback por erro

pip install jangada-ai==1.15.0 Copy PIP instructions

Camada fina PT-BR sobre os SDKs de LLM: troque de provider sem mudar o código, com observability nativa em 1 linha no .env.

Uma camada fina e adaptável sobre os SDKs de LLM. Uma jangada leve que te leva entre Anthropic, OpenAI, Groq, Gemini, Mistral, Ollama (e Bedrock, Azure, Vertex, OpenRouter, DeepSeek, OmniRoute) sem trocar o leme: você muda provider / model / api_key e o resto do código continua igual.

pip install "jangada-ai[anthropic]" # ou [openai] / [groq] / [gemini] / [mistral] / [ollama] / [all] from jangada_ai import LLM llm = LLM("anthropic", "claude-opus-4-8") print(llm.complete("Explique {{tema}} em 2 frases.", tema="MCP").text) O pitch em 4 linhas — troque o provider, o resto do código não muda:

LLM("openai", "gpt-4o-mini") # mesma chamada .complete()/.parse()/.stream() LLM("groq", "llama-3.3-70b-versatile") LLM("gemini", "gemini-2.5-flash") LLM("anthropic", "claude-opus-4-8").with_fallback(LLM("openai", "gpt-4o-mini")) A mesma API (complete/parse/stream, sync e async) vale para os 4 — com templates {{ }}, structured output, vision, tools/MCP, retry e fallback.

Onde a jangada se encaixa

Existem ótimas libs de abstração de LLM por aí — esta tabela é uma comparação de alto nível, não uma auditoria completa de cada projeto. Use como ponto de partida, não como veredito final.

Se você precisa de um gateway self-hosted com múltiplos times, budgets e virtual keys, o LiteLLM Proxy provavelmente serve melhor. Se você quer grafos de estado complexos e um ecossistema grande de integrações prontas, o LangChain/LangGraph tem mais peças. A jangada mira no meio-termo: uma lib fina que você importa direto no seu backend — sem subir um serviço extra — que já cobre fallback, cache, guardrails e multi-agente básico com as nuances de cada modelo resolvidas.

Por que existe (as nuances que ela resolve)

Chaves de API e .env

Parâmetros de geração

Tools (function calling)

Tools nativas (web search, code execution...)

Transcrição de áudio

Documentos (docx, pdf, csv, xlsx)

Custo e tokens na resposta

Orquestração (Graph)

Agentes & times (Agent/Squad)

Gemini Interactions / Deep Research

Servindo a jangada como servidor MCP

Versionamento de prompts

Tools prontas (prebuilt)

Boas práticas e nuances

Estendendo (novo provider)

Versionamento e estabilidade

Wrappers "genéricos" costumam quebrar em produção por detalhes que só aparecem quando você troca de modelo. A jangada resolve estes:

Modelos do mesmo provider têm contratos diferentes. gpt-5 rejeita temperature (400) e exige max_completion_tokens; gemini-3.x descarta temperature/top_p/top_k e troca thinking_budget por thinking_level. A jangada normaliza o payload por modelo — você só troca o nome.

Nomes de parâmetro divergem entre SDKs. stop vira stop_sequences na Anthropic/Gemini; max_tokens vira max_output_tokens no Gemini. Você usa sempre o nome canônico.

Erros são heterogêneos. Cada SDK levanta exceções diferentes; aqui tudo vira um conjunto único, com status_code, que alimenta retry e fallback.

Falhas transitórias. Rate limit e 5xx ganham retry com backoff no mesmo provider antes de cair pro fallback (outro modelo/provider).

Custo é invisível por padrão. Cada resposta volta com usage e cost estimado, e Flow/Graph agregam o total.

Structured output é diferente em cada um. OpenAI .parse, Groq json_schema, Gemini response_schema, Anthropic tool-forcing — uma só chamada parse() cuida disso.

Detecção de objetos sem amarrar a um provider. detect_objects() devolve bounding boxes em pixels e funciona em qualquer modelo com visão (vision + structured output), não só no Gemini.

Transcrição de áudio onde dá. transcribe() cobre OpenAI, Groq, Gemini e Mistral/Voxtral (Anthropic não aceita áudio na API) — com a mesma interface e o mesmo fallback das outras chamadas. A Mistral ainda faz OCR/Document AI (ocr()): PDF/imagem → markdown por página + bounding boxes.

Documentos nem sempre precisam de vision. docx/pdf/csv/xlsx têm o texto embutido: a jangada extrai localmente (mais barato, roda em modelo sem visão) e só usa vision quando você pede ou quando o PDF é escaneado.

Imports são preguiçosos: import jangada_ai funciona sem nenhum SDK instalado.

Cookbook (receitas prontas)

Casos reais rodáveis em examples/cookbook/: extração de nota fiscal (vision+structured), agente MCP, chatbot RAG, fallback multi-provider, transcrição+resumo e observability. Cada um é script + explicação — pra ler e rodar.

A documentação completa fica no repositório público jangada-docs:

📚 Guias por tema: https://github.com/nerigleston/jangada-docs/tree/main/docs

🌐 Site: https://jangada.dev.br

📖 Docs online: https://docs.jangada.dev.br

🤖 Para LLMs — índice: llms.txt

🤖 Para LLMs — completo: llms-full.txt

📦 Pacote no PyPI: https://pypi.org/project/jangada-ai/

🧩 Doc no seu editor (MCP) — para desenvolvedores

Pluga toda a doc do jangada no Claude Code / Claude Desktop / Cursor via MCP, pra o assistente codar com a API atual (sem chutar). Sem clonar nada, com uvx:

claude mcp add jangada-docs -- uvx --from git+https://github.com/nerigleston/jangada-docs-mcp jangada-docs-mcp Ou via endpoint hospedado (HTTP):

{ "mcpServers": { "jangada-mcp": { "url": "https://mcp.jangada.dev.br/mcp/" } } } Repo: jangada-docs-mcp (escopo global ou por projeto — ver o README de lá).

A fonte dos docs está aqui em docs/; o repo público é espelhado por scripts/sync-docs.sh.

pip install -e ".[anthropic]" # só Claude pip install -e ".[openai,groq]" # OpenAI + Groq pip install -e ".[all]" # todos pip install -e ".[ollama]" # Ollama (local ou Cloud) pip install -e ".[files]" # ler docx/pdf/csv/xlsx pip install -e ".[dev]" # ambiente de testes (pytest + libs) Atenção: o extra [all] traz todos os providers (inclui Ollama) + files + mcp, mas não inclui rag nem rerank (drivers de banco) — esses entram à parte, ex.: pip install "jangada-ai[all,rag]".

Precedência: api_key= explícito > variável de ambiente > arquivo .env.

LLM("openai", "gpt-4o", api_key="sk-...") # explícito LLM("openai", "gpt-4o") # lê OPENAI_API_KEY (ambiente ou .env) O .env é detectado na importação, subindo a partir do diretório atual, de forma não-destrutiva (não sobrescreve variáveis já definidas). Usa python-dotenv se instalado, ou um parser embutido. Desligue com JANGADA_NO_DOTENV=1, ou carregue manualmente: jangada.load_env("caminho/.env").

Variáveis lidas: ANTHROPIC_API_KEY, OPENAI_API_KEY, GROQ_API_KEY, GEMINI_API_KEY (ou GOOGLE_API_KEY).

Os params comuns são argumentos nomeados de primeira classe, traduzidos para cada SDK e descartados quando o modelo não os aceita:

llm = LLM("openai", "gpt-4o", temperature=0.2, max_tokens=800, top_p=0.9, top_k=40, stop=["\n\n"], seed=42) canônico OpenAI / Groq Anthropic Gemini temperature temperature temperature temperature max_tokens max_tokens¹ max_tokens max_output_tokens top_p top_p top_p top_p top_k (descartado) top_k top_k stop stop stop_sequences stop_sequences seed seed (descartado) seed ¹ vira max_completion_tokens em modelos de raciocínio (gpt-5).

Params específicos vão em extra={...} (ex.: reasoning_effort, thinking_level, verbosity). Override por chamada: llm.complete("...", params={"temperature": 0.7}).

Diferenças entre modelos (perfis automáticos)

Você troca o nome do modelo e segue — a jangada ajusta o payload:

LLM("openai", "gpt-4o", temperature=0.3, max_tokens=500) # vai como está LLM("openai", "gpt-5.2", temperature=0.3, max_tokens=500) # temperature removido; max_tokens -> max_completion_tokens LLM("gemini", "gemini-2.5-flash", temperature=0.5) # vai como está LLM("gemini", "gemini-3.5-flash", temperature=0.5) # sampling descartado (Gemini 3.x usa defaults) Registre regras para modelos novos:

from jangada_ai import Profile, register_profile register_profile("openai", r"^modelo-novo", Profile(drop=("temperature",), note="...")) Nuance de function calling no Gemini 3.x. A API valida thought signatures de forma estrita: reconstruir o histórico de tools (em vez de devolver o histórico completo e deixar o SDK cuidar) causa 400. Foi isso que quebrou conversores genéricos ao migrar gemini-2.5 → gemini-3.5. A jangada não reconstrói histórico de tools (structured output é single-turn), então não esbarra nisso — mas guarde a regra se for montar loops agênticos.

A mesma parse() em qualquer provider (por baixo: OpenAI .parse, Groq json_schema, Gemini response_schema, Anthropic tool-forcing):

from pydantic import BaseModel class Fatura(BaseModel): fornecedor: str total: float itens: list[str] fatura = llm.parse("Extraia a fatura:\n{{t}}", Fatura, t=texto).parsed # instância validada Async: await llm.aparse(...). Em fluxos/grafos, um passo com schema= guarda o .parsed em result.parsed("passo").

from jangada_ai import Image llm.complete("O que aparece aqui?", images=["foto.jpg"]) img = Image.from_bytes(upload_bytes, "image/png") # ou from_base64 recibo = llm.parse("Extraia o total.", Recibo, images=[img]).parsed Imagens são bytes (path/bytes/base64) e viram o formato nativo de cada SDK. Use sempre um modelo com visão.

from jangada_ai import LLM, Message def get_weather(city: str) -> str: """Retorna o clima atual de uma cidade.""" return "25°C, ensolarado" llm = LLM("openai", "gpt-4o-mini") comp = llm.complete("Tempo em Recife?", tools=[get_weather]) # OpenAI/Groq/Anthropic/Gemini for call in comp.tool_calls: # você executa out = get_weather(**call.args) final = llm.complete("Tempo em Recife?", history=[comp.assistant_message(), Message.tool_results(call.result(out))], tools=[get_weather]) Baixo nível (você executa e reenvia). tools= aceita função/Pydantic/dict. Tools prontas em jangada_ai.prebuilt (ex.: tavily_search). Veja docs/tools.md.

Ferramentas que o próprio provider executa (busca na web, execução de código, leitura de URL, file search, Maps...) com uma API só — misturáveis com as suas funções na mesma lista:

from jangada_ai import LLM, web_search, code_execution llm = LLM("gemini", "gemini-3.8-flash") # ou anthropic, openai, groq, mistral, bedrock, ollama... comp = llm.complete("Qual a Selic hoje? Calcule o juro de 1 ano sobre R$ 10 mil.", tools=[web_search(), code_execution(), get_weather]) print(comp.text) for c in comp.citations: # fontes, normalizadas entre providers print(c.title, c.url) Sem equivalente canônico? native_tool(provider, spec) repassa o objeto nativo do SDK cru (ex.: native_tool("gemini", types.Tool(google_search=...))). Os blocos que a API exige de volta no histórico são preservados por comp.assistant_message(), e a taxa por busca entra em comp.cost. Veja docs/native-tools.md.

MCP (Model Context Protocol)

from jangada_ai import LLM, MCPServer # remoto por URL — o provider executa as tools (Anthropic/OpenAI/Groq) llm = LLM("anthropic", "claude-opus-4-8") llm.complete("Liste as issues.", mcp_servers=[ MCPServer(url="https://mcp.exemplo.com/sse", name="github", authorization_token="TOKEN")]) # Gemini é client-side (sessão), só no async: await llm.acomplete(..., mcp_servers=[session]) MCP nativo (server-side) — dois modelos conforme o SDK: remoto/URL (Anthropic/OpenAI/Groq) e sessão (Gemini, async).

Ou use o cliente + agente próprios (jangada-ai[mcp]), que conecta no servidor e roda o loop sozinho em qualquer provider:

from jangada_ai import LLM, MCPClient, run_agent async with MCPClient("https://meu-mcp/mcp/") as mcp: # ou stdio (command=/args=) ans = await run_agent(LLM("openai", "gpt-4o-mini"), "Role uns dados", client=mcp) print(ans.text) Veja docs/mcp.md.

from jangada_ai import LLM, detect_objects llm = LLM("gemini", "gemini-2.5-flash") # funciona em qualquer modelo com visão for d in detect_objects(llm, "foto.png"): print(d.label, d.box) # box = [x1, y1, x2, y2] em pixels # acrescente contexto sem perder o formato de saída: detect_objects(llm, "foto.png", target="todos os carros", instructions="Ignore os desfocados; rotule em inglês.") Bounding boxes em pixels absolutos. É vision + structured output, então roda em todos os providers (o Gemini é o mais preciso). Veja docs/detect.md.

RAG (embeddings + busca vetorial/híbrida)

from jangada_ai import LLM from jangada_ai.rag import RAG, vector_store # pip install "jangada-ai[rag]" emb = LLM("openai", "text-embedding-3-small") # embed: OpenAI ou Gemini store = vector_store("postgresql://...") # ou "mongodb+srv://..." (pela conn string) rag = RAG(emb, store, chat=LLM("openai", "gpt-4o-mini")) rag.add_document("manual.pdf") print(rag.ask("Como faço backup?", mode="hybrid").text) # vetorial + texto (RRF) embed() está em OpenAI/Gemini/Mistral (Anthropic/Groq não têm). O vector store é escolhido pela string de conexão (pgvector ou Mongo) e cria tabelas/índices sozinho. Veja docs/rag.md.

from jangada_ai import LLM LLM("openai", "gpt-4o-transcribe").transcribe("entrevista.mp3").text LLM("groq", "whisper-large-v3-turbo").transcribe("entrevista.mp3", language="pt").text LLM("gemini", "gemini-2.5-flash").transcribe("entrevista.mp3").text Suportado em OpenAI, Groq e Gemini; o Anthropic não aceita áudio na API (levanta UnsupportedError). Honra retry e fallback como qualquer chamada. Veja docs/audio.md.

from jangada_ai import Document # Por padrão EXTRAI O TEXTO localmente (não usa vision): mais barato e # funciona em qualquer modelo. Tabelas viram markdown. llm.complete("Resuma:", files=["relatorio.pdf", "contrato.docx"]) # xlsx: todas as abas entram, cada uma rotulada (## Aba: ...). # max_rows limita planilhas gigantes para economizar tokens. llm.complete("Maior total?", files=[Document("vendas.xlsx", max_rows=200)]) # Bytes em memória (upload/fila) — informe o nome para detectar o tipo. llm.parse("Há duplicadas?", Relatorio, files=[Document(blob, name="x.csv")]) # Forçar vision (PDF escaneado, sem camada de texto / quando o layout importa): llm.complete("Transcreva:", files=[Document("scan.pdf", mode="vision")]) Regra do mode="auto" (padrão): csv/xlsx/docx e PDF com camada de texto são extraídos como texto; imagens vão para vision. Um PDF sem texto (escaneado) levanta DocumentError sugerindo mode="vision" — nunca devolve um bloco vazio em silêncio. files= existe em complete/parse/stream (sync e async) e convive com images=.

Requer o extra: pip install "jangada[files]" (pypdf, python-docx, openpyxl).

for token in llm.stream("Conte sobre {{x}}", x="João Pessoa"): print(token, end="") async for token in llm.astream("..."): # FastAPI ... Retry + fallback

Duas camadas, com semântica clara:

Retry no mesmo provider (com backoff exponencial + jitter) para erros transitórios: rate limit (429), timeout, conexão e 5xx.

Fallback para o próximo candidato quando o retry esgota — pode ser outro modelo ou outro provider.

llm = LLM( "groq", "llama-3.3-70b-versatile", max_retries=3, backoff_base=0.5, backoff_max=8.0, jitter=True, ).with_fallback( LLM("openai", "gpt-5.2"), LLM("anthropic", "claude-opus-4-8"), ) resp = llm.complete("...") print(resp.provider) # quem de fato respondeu O que não dispara retry nem fallback por padrão: AuthError (401/403) e BadRequestError (400/422) — trocar de provider ou repetir não resolveria. NotFoundError (modelo inexistente) não faz retry, mas faz fallback (ótimo para "modelo de reserva"). Tudo configurável via retry_on= (failover) e backoff_on= (quais erros repetem). Vale em sync, async e streaming (o failover de stream ocorre antes do 1º token).

Toda resposta volta com usage e cost (USD estimado):

r = llm.complete("...") r.usage # {'input_tokens': 120, 'output_tokens': 84} r.cost # 0.00042 (None se o modelo não estiver na tabela) Flow e Graph agregam o total da execução:

res = flow.run(...) res.usage # soma de todos os passos res.cost # custo total estimado Preços mudam direto. A tabela embutida é um retrato aproximado — verifique a página de preços e sobrescreva quando precisar de exatidão: jangada.register_price(r"gpt-5\.2", 1.75, 14.00) (USD por 1M tokens).

A saída de cada passo vira variável {{ }} dos próximos:

from jangada_ai import Flow flow = ( Flow(llm) .step("resumo", "Resuma:\n{{texto}}") .step("traducao", "Traduza para {{idioma}}:\n{{resumo}}") ) r = flow.run(texto="...", idioma="inglês") r["traducao"]; r.cost; r.usage Cada passo pode ter llm= próprio (misturar providers) e schema= (parse).

Orquestração (Graph: roteamento + paralelo)

Quando o Flow linear não basta — um agente decide o próximo, ou vários rodam em paralelo:

from jangada_ai import Graph # roteamento condicional g = Graph() g.node("triagem", clf, "Responda 'tecnico' ou 'geral': {{pergunta}}") g.node("tecnico", tec, "Responda técnico: {{pergunta}}") g.node("geral", ger, "Responda simples: {{pergunta}}") g.route("triagem", lambda ctx: "tecnico" if "tecnico" in ctx["triagem"].lower() else "geral") r = g.run("triagem", pergunta="...") r.path # ['triagem', 'tecnico'] # paralelo + junção g = Graph() g.parallel("pesquisas", { "mercado": (llm_a, "Mercado de: {{tema}}"), "tecnica": (llm_b, "Viabilidade de: {{tema}}"), }, join="sintese") g.node("sintese", llm_s, "Combine:\n{{mercado}}\n{{tecnica}}") r = g.run("pesquisas", tema="...") Compõe nos dois sentidos (rota → paralelo, ou paralelo → rota). O núcleo é async: em FastAPI use await g.arun(...); fora de loop, g.run(...).

Camada de composição em cima do que já existe (tools, MCPClient, RAG) — sem infraestrutura nova. Agent é um LLM com papel/objetivo e um loop de tool calling; Squad orquestra vários agentes, em sequência (handoff) ou hierarquia (um gerente delega).

from jangada_ai import LLM, Agent, Squad def clima(cidade: str) -> str: """Retorna o clima de uma cidade.""" return f"ensolarado em {cidade}" pesquisador = Agent(LLM("openai", "gpt-4o-mini"), role="Meteorologista", goal="informar o clima", tools=[clima]) escritor = Agent(LLM("openai", "gpt-4o-mini"), role="Redator", goal="resumir em 1 frase") # sequencial: a saída de um vira contexto do próximo squad = Squad([pesquisador, escritor]) print(squad.run("Como está o clima em Recife?").text) # hierárquico: um gerente delega via tools geradas automaticamente squad = Squad([pesquisador, escritor], manager=Agent(LLM("openai", "gpt-4o-mini"), role="Gerente")) Memória de longo prazo: RAGMemory (sobre um RAG do jangada_ai.rag) via Agent(..., memory=RAGMemory(rag)) — recall busca, remember indexa.

MCP como tools do agente: Agent(..., mcp_client=MCPClient(...)), disponível no arun (async).

Planejamento: plan(llm, goal) decompõe um objetivo em lista de tarefas (structured output).

A2A: agent.card() gera o Agent Card (com protocolVersion/preferredTransport) e jangada_ai.a2a (A2AHandler + build_a2a_app, extra [a2a]) serve o agente por HTTP/JSON-RPC, com o card em /.well-known/agent-card.json (e a rota legada agent.json).

Veja docs/agents.md.

Camada fina sobre a Interactions API do Gemini (agentes gerenciados como o Deep Research, background + polling, loop de function calling):

from jangada_ai import GeminiInteractions gi = GeminiInteractions() # GEMINI_API_KEY res = gi.deep_research("Panorama do mercado de pagamentos instantâneos no Brasil em 2026") print(res.text) Preview; exige google-genai>=2.3. Veja docs/interactions.md.

Mantém a LLM dentro de um domínio e barra falas fora do escopo — intercepta a chamada antes (input) e/ou depois (output) do modelo principal, sem infra nova.

from jangada_ai import LLM, ScopeGuard guard = ScopeGuard( "Suporte do e-Gestor: notas fiscais, financeiro, cadastros; NÃO responde outros assuntos", judge=LLM("openai", "gpt-4o-mini"), # modelo barato pra classificar (recomendado) block=[r"senha", r"cart[aã]o de cr[eé]dito"], # blocklist: barra na hora, sem LLM check="both", # "input" (padrão) | "output" | "both" ) llm = LLM("openai", "gpt-4o", guardrails=[guard]) Dois mecanismos, do barato ao robusto: blocklist (regex/termos, sem custo) e classificador de escopo (LLM-as-judge, via structured output). Quando barra, devolve um Completion com a mensagem de recusa (curto-circuita antes de gastar o modelo principal); com raise_on_block=True, levanta GuardrailError. fail_closed controla o comportamento se o judge falhar.

Plugado via LLM(..., cache=...). Consulta antes de chamar o provider, popula depois de uma resposta bem-sucedida.

from jangada_ai import LLM, ExactCache, SemanticCache # exato: só acerta requisição idêntica (hash de método+escopo+mensagens) llm = LLM("openai", "gpt-4o-mini", cache=ExactCache(max_size=512, ttl=3600)) # semântico: acerta por similaridade de cosseno (reusa embed + vector_store do RAG) llm = LLM("openai", "gpt-4o-mini", cache=SemanticCache( embedder=LLM("openai", "text-embedding-3-small"), threshold=0.85, )) Calibre o threshold por modelo de embedding — a escala de similaridade varia bastante entre modelos (paráfrases ficam ~0.6 no text-embedding-3-small, mas ~0.9 no gemini-embedding-001). Meça paráfrases vs. perguntas distintas no seu modelo antes de confiar no padrão.

Além de consumir MCP (MCPServer/MCPClient), a jangada também serve: exponha suas funções ou um Agent inteiro como servidor MCP pra Claude Desktop, Cursor ou outro agente consumirem.

from jangada_ai import serve_mcp def soma(a: int, b: int) -> int: """Soma dois números.""" return a + b serve_mcp("minha-calc", tools=[soma]) # transporte stdio # ou exponha um Agent inteiro como uma ferramenta `ask`: from jangada_ai import Agent, LLM agente = Agent(LLM("openai", "gpt-4o-mini"), role="suporte", tools=[soma]) serve_mcp("suporte", agent=agente) Construído sobre o Server low-level do SDK oficial mcp (extra jangada-ai[mcp]) — o protocolo, não um framework como FastMCP. É o lado servidor equivalente ao MCPClient.

Registry opt-in pra versionar prompts fora do código e referenciá-los pelo nome — convive com prompt hardcoded, que continua funcionando normalmente.

A régua de qualidade sobre a observabilidade: roda um target sobre um Dataset, dá notas com Evaluators (heurística e/ou LLM-juiz), agrega score/custo/latência. Funciona offline.

Funções já prontas pra passar em tools=[...] — o schema sai da assinatura, você executa e reenvia como qualquer tool.

from jangada_ai.prebuilt import calculator, current_datetime, fetch_url, wikipedia_search, tavily_search, brave_search, openweather Sem chave: calculator, current_datetime, fetch_url, wikipedia_search, http_request. Com chave (via env): tavily_search/tavily_tool, brave_search, openweather.

Debug passo a passo (por agente)

debug=True narra a cadeia: prompt, params, resposta (tempo, tokens, custo), retries, erros e trocas de fallback. Cada LLM tem seu debug e name, então em fluxos/grafos o trace sai por agente.

┌─ [resumidor] groq/llama-3.3-70b-versatile │ user: Resuma: ... │ params: temperature=0.2, max_tokens=8192 │ ↻ tentativa 1 após 0.5s (RateLimitError) │ ✗ RateLimitError (429): quota exceeded │ ↪ fallback → anthropic/claude-opus-4-8 ┌─ [resumidor] anthropic/claude-opus-4-8 │ ← 412ms · ↑12 ↓84 tok · $0.006330: Resumo do texto... └─ Para mandar pro log: llm.debug.sink = logging.getLogger("jangada").info.

system templatizado é strict. Se você definir system="Aja como {{persona}}." no construtor, passe persona em toda chamada. Em fluxos, prefira system fixo no LLM e ponha a parte variável nos prompts dos passos.

Modelos de raciocínio (gpt-5, gemini-3.x) ignoram temperature. Não adianta ajustar sampling; use extra={"reasoning_effort": "..."} / extra={"thinking_level": "..."}. A jangada já descarta o que não cabe.

Cadeia de fallback barato → forte. Coloque o modelo rápido/barato como primário e os caros como reserva; o retry segura picos de 429 sem trocar.

NotFoundError é seu amigo no fallback de modelo. Aponte um modelo novo como primário e um estável como fallback: se o nome ainda não existir na sua região, ele cai pro estável sem quebrar.

Flow para pipeline fixo; Graph quando há decisão ou paralelismo. Não use Graph se a ordem é sempre a mesma — Flow é mais simples de ler.

Em FastAPI use sempre as versões async (acomplete/aparse/astream e graph.arun) para não bloquear o event loop.

Cheque o custo em produção. Logue resp.cost e result.cost; sobrescreva a tabela de preços com os valores do seu contrato.

Endpoints compatíveis com OpenAI (Ollama, OpenRouter, vLLM) funcionam pelo provider openai passando base_url: LLM("openai", "llama3", base_url="http://localhost:11434/v1", api_key="ollama").

Vision é só bytes. URLs remotas não são baixadas automaticamente; carregue com Image.from_path/bytes/base64 para uniformidade entre os 4 providers.

Em jangada.errors, todos com .provider, .status_code e .original: RateLimitError, APITimeoutError, APIConnectionError, ServerError, OverloadedError, AuthError, BadRequestError, NotFoundError, ProviderError. Conjuntos prontos: TRANSIENT (retry) e DEFAULT_FAILOVER.

Herde de jangada.Provider, implemente os 6 métodos (complete/acomplete/ parse/aparse/stream/astream) + os dois _build_*_client, e registre com jangada.register("nome", lambda: SuaClasse). Veja CLAUDE.md para as invariantes (imports preguiçosos, tradução de erro, ordem translate→profile).

Providers prontos: anthropic, openai, groq, gemini, openrouter, azure (Azure OpenAI), bedrock (AWS Bedrock, Converse API) e vertex (Gemini no Google Cloud).

A jangada segue SemVer. Na fase 0.x, mudanças incompatíveis podiam ocorrer em releases minor (0.X.0) — sempre documentadas no CHANGELOG.md. A partir do 1.0 (versão atual), SemVer pleno: sem breaking change em minor/patch.

A API pública é o que está em jangada_ai.__all__; submódulos internos e nomes com _ podem mudar a qualquer momento. O que é estável × experimental está em docs/estabilidade.md; as regras de versionamento e deprecação em docs/semver.md.

Contribuições são bem-vindas — issues, PRs de bugfix, novos providers ou melhorias na doc.

Abra uma issue descrevendo o problema ou a proposta antes de um PR grande.

pip install -e ".[dev]" para o ambiente de testes.

Rode a suíte local antes de abrir o PR.

PRs de doc podem ir direto pro repositório jangada-docs.

Dúvidas rápidas? Abra uma issue — é o canal mais rápido de resposta.

Feito com 🛶 em PT-BR · jangada.dev.br · MIT License

Mantido por Neri Filho, que trabalha com IA em produção, sistemas sob medida e consultoria técnica.

Released: Nov 28, 2026

MIT View SPDX License List

a2a all anthropic bedrock code-mode dev files gemini groq mcp mistral ollama openai rag rerank

anthropic azure-openai bedrock claude deepseek fallback gemini groq grounding llm mistral ocr ollama openai openrouter structured-output vertex-ai vision web-search

Development Status 4 - Beta

Intended Audience Developers

Programming Language Python :: 3

Topic Scientific/Engineering :: Artificial Intelligence

Software Development :: Libraries :: Python Modules

Release files for jangada-ai 1.15.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Built distribution (wheel)

Total release size: 988.6 kB

Release files / jangada_ai-1.15.0.tar.gz

Release files / jangada_ai-1.15.0-py3-none-any.whl

Security for jangada-ai 1.15.0

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

Nov 28, 2026 2 release files No provenance

Nov 24, 2026 2 release files Loss of provenance

Nov 14, 2026 2 release files Full provenance

Nov 13, 2026 2 release files Full provenance

Nov 8, 2026 2 release files Full provenance

Nov 7, 2026 2 release files Full provenance

Nov 3, 2026 2 release files Full provenance

Nov 2, 2026 2 release files Full provenance

Nov 1, 2026 2 release files Full provenance

Oct 28, 2026 2 release files Full provenance

Oct 27, 2026 2 release files Full provenance

Oct 26, 2026 2 release files Full provenance

Sep 23, 2026 2 release files Full provenance

Sep 18, 2026 2 release files Full provenance

Sep 17, 2026 2 release files Full provenance

Sep 8, 2026 2 release files Full provenance

Sep 7, 2026 2 release files Full provenance

Aug 25, 2026 2 release files Full provenance

Aug 21, 2026 2 release files Full provenance

Jul 28, 2026 2 release files Full provenance

Jul 27, 2026 2 release files Full provenance

Jul 19, 2026 2 release files Full provenance

Jul 18, 2026 2 release files Full provenance

Jul 13, 2026 2 release files Full provenance

Jul 9, 2026 2 release files Full provenance

Jul 4, 2026 2 release files Full provenance

Jul 2, 2026 2 release files Full provenance

Jun 30, 2026 2 release files Full provenance

Jun 28, 2026 2 release files Full provenance

Jun 27, 2026 2 release files Full provenance

Jun 26, 2026 2 release files Full provenance

Jun 25, 2026 2 release files Full provenance

Jun 24, 2026 2 release files Full provenance

Jun 23, 2026 2 release files Full provenance

Jun 22, 2026 2 release files Full provenance

Jun 22, 2026 2 release files No provenance

"PyPI", "Python Package Index", and the blocks logos are registered trademarks of the Python Software Foundation.

© 2026 Python Software Foundation

Deployed from fc0d8e6

Source Attribution: This report incorporates information referenced or syndicated from Pypi.org. Read original coverage at Pypi.org.

More from Technology →
Haldwani Times
Haldwani Times Independent News & Editorial
Login
MARKETS & FINANCE
BRENT CRUDE: $78.40 -0.52% SENSEX: 81,450.20 +0.42% NIFTY 50: 24,820.15 +0.38% GOLD (24K): ₹74,500/10g -0.18% USD/INR: ₹95.54 +0.10%

ADMINISTRATIVE LEADERSHIP

Mr. Narendra Modi
Mr. Narendra Modi
Mr. Lt. Gen. Gurmit Singh
Mr. Lt. Gen. Gurmit Singh
Mr. Pushkar S. Dhami
Mr. Pushkar S. Dhami
Mr. Lalit M. Rayal
Mr. Lalit M. Rayal
Mr. Gajraj S. Bisht
Mr. Gajraj S. Bisht

Top Headlines & Breaking Stories

View All News →

Haldwani Times – Everything in Haldwani: News, Shops, Businesses & Services

Haldwani Times is the premier digital news and commercial discovery platform built specifically for the citizens, business owners, students, professionals, and visitors of Haldwani, Nainital district, and the wider Kumaon region of Devbhoomi Uttarakhand. As the economic gateway to the Kumaon Himalayas, Haldwani is a bustling metropolis connecting the plains of northern India with the scenic mountain districts of Nainital, Almora, Pithoragarh, Bageshwar, Champawat, and Udham Singh Nagar. Haldwani Times serves as the definitive digital heartbeat of the city, bringing breaking hyperlocal news, verified commercial directories, educational updates, healthcare guides, Mandi Bhav rates, and civic announcements onto a single unified, trusted platform.

The Definitive Source for Breaking Haldwani News & Civic Updates

Haldwani stands as one of the fastest-growing urban conglomerates and commercial engines in northern India. Positioned in the fertile Terai-Bhabhar belt at the foothills of the Shivalik range, the twin cities of Haldwani and Kathgodam form the administrative and logistical nerve center for the entire Kumaon division. With rapid urbanization, expanding commercial infrastructure, flourishing educational centers, and increasing inter-state transit, the demand for fast, fact-checked, and unbiased local journalism has never been greater. Haldwani Times delivers 24/7 comprehensive news coverage built on rigorous journalistic standards: - **Hyperlocal Civic News:** Real-time coverage of municipal corporation affairs, city drainage projects, traffic management blueprints, and road widening drives across Tikonia, Mukhani, Kusumkhera, Bareilly Road, and Rampur Road. - **Administrative Directives:** Official notifications from the District Magistrate (DM) Nainital, Senior Superintendent of Police (SSP), and state secretariat decisions affecting citizen welfare. - **Kumaon Weather & Disaster Alerts:** Timely mountain rainfall warnings, landslide advisories along NH-109 (Haldwani-Nainital Highway), and emergency bulletins during the monsoon and winter seasons. - **Education & Campus News:** Timely reports on Kumaon University examination schedules, Uttarakhand Board (UBSE) results, medical college admissions, and competitive coaching updates. - **Commercial & Market Trends:** Daily wholesale Mandi Bhav rates from Haldwani Subzi Mandi, real estate trends, retail market festivals, and local business openings. - **Cultural & Pahadi Heritage:** In-depth feature stories celebrating Kumaoni folk traditions, Aipan art, Nanda Devi festivals, and local community milestones.

Everything in Haldwani on One Unified Digital Ecosystem

Beyond traditional news reporting, Haldwani Times is engineered as an exhaustive local discovery engine. Historically, finding verified local business telephone numbers, emergency hospital contacts, specialized doctors, reliable plumbers, or trusted real estate consultants in Haldwani required asking neighbors or browsing outdated social media posts. Haldwani Times eliminates this friction by organizing every commercial, professional, and civic resource into searchable, verified categories. Whether you are a newly arrived resident in Kusumkhera looking for high-speed broadband providers, a parent searching for reputable CBSE schools near Kaladhungi Road, or a tourist seeking taxi rentals to Nainital, our portal delivers accurate, verified, and actionable information in seconds.

Local Shops, Retail Hubs & Traditional Bazaars in Haldwani

The retail commerce of Haldwani spans centuries-old traditional bazaars and modern commercial complexes: - **Bada Bazaar & Mangal Parao:** The historic retail heart of Haldwani, renowned for traditional Kumaoni wedding jewelry (Pauji, Guloband, Nath), brass utensils, ethnic handlooms, and wholesale clothing. - **Nainital Road & Tikonia Commercial Corridor:** Modern multi-brand retail showrooms, electronics stores, authorized smartphone service centers, branded footwear outlets, and international apparel stores. - **Bareilly Road & Rampur Road Trade Hubs:** Major agricultural machinery dealers, hardware and building material wholesalers, furniture manufacturing units, plywood distributors, and automobile showrooms. - **Subzi Mandi & Wholesale Grain Market:** One of the largest agricultural distribution centers in North India, supplying fresh vegetables, hill fruits (apples, peaches, plums), and organic Pahadi pulses (Gahat, Bhatt, Rajma) across northern states.

Healthcare Hub of Kumaon: Hospitals & Emergency Services

Haldwani serves as the premier medical lifeline for all six hill districts of Kumaon. Patients travel from Almora, Pithoragarh, Bageshwar, and Champawat to access specialized clinical treatments in Haldwani: - **Government Healthcare Institutions:** Dr. Susheela Tiwari Government Medical College & Hospital (STGH) and Base Hospital Haldwani provide tertiary trauma care, specialized super-specialties, pediatric ICUs, and 24/7 emergency response. - **Private Multi-Specialty Hospitals:** Advanced private medical centers specializing in cardiology, joint replacements, neurology, critical care, nephrology, and advanced laparoscopic surgeries. - **Diagnostic Centers & 24/7 Pharmacies:** Fully automated pathology laboratories, high-resolution MRI/CT scan centers, and round-the-clock emergency pharmacies clustered around Medical College Road, Kaladhungi Road, and Rampur Road.

Education, Colleges, Coaching Academies & Youth Development

Haldwani is the educational capital of the Kumaon region, home to thousands of ambitious students preparing for medical, engineering, defense, and civil services careers: - **Premier Degree Colleges:** Motiram Baburam Government Post Graduate College (MBPG College) and Women's Degree College providing extensive undergraduate and postgraduate humanities, commerce, and science programs. - **Competitive Coaching Ecosystem:** Highly reputed coaching academies for NEET UG, JEE Main & Advanced, UPSC Civil Services, UKPSC/UKSSSC, NDA, CDS, and Banking examinations along Kaladhungi Road and Tikonia. - **Affiliated Schooling Infrastructure:** Esteemed CBSE, ICSE, and Uttarakhand Board schools imparting value-based holistic education with modern sports and laboratory facilities.

Real Estate, Housing Colonies & Urban Expansion Trends

Driven by rapid infrastructure expansion and high quality of life, Haldwani's real estate market is expanding outward into organized residential colonies: - **Prime Residential Localities:** Highly sought-after residential sectors in Mukhani, Kusumkhera, Kaladhungi Road, Judge Farm, Daharia, and Bhotia Parao offering planned housing, green parks, and modern civic amenities. - **Commercial Property Investments:** Thriving commercial retail complexes, office spaces, and warehouse hubs developing rapidly along the proposed Haldwani Ring Road and transport corridors. - **Property Advisory & RERA Compliance:** In-depth real estate updates, circle rate revisions by the Nainital district administration, and buyer advisory guidelines for safe property acquisitions.

Strategic Transit Gateway, Tourism Routes & Kumaon Himalayan Connectivity

Haldwani-Kathgodam is the vital transit bridge connecting the plains of Delhi NCR and Uttar Pradesh with the hill stations of Uttarakhand: - **Kathgodam Railway Terminal:** Connecting Kumaon directly to New Delhi (Shatabdi Express, Ranikhet Express), Lucknow, Kolkata, Jammu, and Dehradun. - **ISBT Haldwani:** Operating round-the-clock interstate and mountain bus routes managed by Uttarakhand Transport Corporation (UTC) and private deluxe coaches. - **Pantnagar Airport (PGH):** Located just 26 km from Haldwani, offering scheduled domestic flights to New Delhi, Dehradun, Pithoragarh, and regional hubs. - **Himalayan Tourism Hub:** The primary staging point for journeys to Nainital (34 km), Bhimtal (30 km), Mukteshwar (72 km), Kainchi Dham (42 km), Almora (90 km), Ranikhet (80 km), and Jim Corbett National Park (55 km).

Gaula River Mining, Ecological Balance & The Bhabhar Economy

The Gaula River represents the undisputed economic and hydrological lifeline of Haldwani and the broader Nainital district. Originating from the Sattal-Bhimtal catchment in the lesser Himalayas, the river flows south past Kathgodam and Haldwani before merging into the Ramganga. For generations, the Gaula riverbed has provided the foundation for both regional agriculture and the construction economy across northern India: - **Regulated Minor Mineral Extraction:** During the open mining season (typically October to May), thousands of registered tractor-trolleys and heavy dumpers harvest riverbed gravel, sand, and boulders under strict surveillance by the Uttarakhand Forest Development Corporation and the Nainital district administration. - **Livelihood Support for Over 50,000 Families:** The Gaula mining economy directly and indirectly sustains vehicle owners, drivers, mechanics, diesel pump stations, roadside eateries, and local laborers, circulating over ₹500 crore into Haldwani's local markets annually. - **Environmental Safeguards & Flood Mitigation:** In strict adherence to High Court and National Green Tribunal (NGT) directives, scientific replenishment studies, satellite GPS tracking on transport vehicles, and seasonal mining bans during the monsoon protect the river's ecological balance and prevent bank erosion along low-lying residential sectors.

Culinary Landscape: From Traditional Kumaoni Rasoi to Modern Cafes

Haldwani's gastronomic scene reflects a delightful blend of rustic mountain traditions and cosmopolitan dining: - **Authentic Kumaoni Specialties:** Local restaurants and heritage dhabas serve traditional mountain delicacies cooked in iron vessels, including Bhatt ki Churkani (black soybean curry), Gahat ke Dubke (horsegram puree), Aloo ke Gutke tempered with wild Himalayan chives (Jamboo) and Jakhiya, and refreshing cucumber Raita flavored with freshly crushed mustard seeds. - **Traditional Confectioneries:** Historic sweet shops along Bada Bazaar and Nainital Road craft Almora's world-famous Bal Mithai (roasted caramelized khoya fudge coated in sugar balls) and Singaudi (sweetened khoya wrapped in wild Malu leaves). - **Vibrant Street Food & Cafe Culture:** As dusk falls, Tikonia and Nainital Road come alive with bustling street food stalls offering steaming Tibetan momos, spiced thukpa, Kathi rolls, and hot Masala Chai, alongside modern rooftop cafes serving specialty Italian coffees and continental snacks.

Cultural Festivals, Folk Heritage & The Aipan Art of Kumaon

Beyond commercial enterprise, Haldwani is the proud cultural showcase of Devbhoomi Uttarakhand: - **Aipan Folk Art Tradition:** The sacred geometrical floor and wall art handcrafted with red ochre (Geru) and white rice paste (Biswar) adorning thresholds, altars, and chowkis during auspicious ceremonies, now preserved through local women's self-help cooperatives. - **Classical Baithki & Khadi Holi:** Unique to Kumaon, musical celebrations starting as early as the month of Paush, featuring classical Hindustani ragas sung in community courtyards followed by energetic Chholiya dance performances during spring. - **Nanda Devi & Chholiya Heritage:** Grand annual fairs celebrating the patron deity Nanda Devi, accompanied by martial sword-and-shield Chholiya dancers whose rhythmic brass trumpets (Ransingha) and hurka drums resonate through the valley.

Public Amenities, Parks & Community Spaces in Haldwani

Urban lifestyle and recreational infrastructure in the city: - **Green Parks & Walking Tracks:** Walkway projects around Daharia, Judge Farm, and Awas Vikas providing lush recreational zones for families and seniors. - **Community Centers & Sports Grounds:** Multi-purpose auditoriums and grounds hosting cultural melas, badminton tournaments, and community celebrations. - **Gaula Barrage & Forest Trails:** Scenic river viewpoints and natural birdwatching areas attracting eco-tourists and local nature enthusiasts on weekends.

Frequently Asked Questions (FAQs)

How can I access live breaking news and weather alerts for Haldwani?

Haldwani Times operates a dedicated 24/7 hyperlocal newsroom providing real-time breaking bulletins, traffic alerts, and meteorological warnings. You can access live news directly from our homepage, subscribe to instant browser push notifications, or view categorical updates on Uttarakhand, Education, and Mandi Bhav. During monsoon and winter weather events, our correspondents provide live updates on NH-109 road blockages and emergency administrative orders issued by the Nainital District Magistrate.

Is Haldwani Times completely free to read for all visitors?

Yes, Haldwani Times offers completely unrestricted, open-access reading to all users without mandatory paywalls. Readers across Haldwani, Uttarakhand, and the global diaspora can freely browse all breaking news reports, investigative articles, business directory listings, and historical archives. Our public-interest mission ensures that essential civic information, emergency hospital directories, and educational circulars remain universally accessible to everyone at zero cost.

How can local business owners list their shop or service in the Haldwani directory?

Local merchants, medical practitioners, schools, and service professionals can register their business by navigating to our 'Business Directory' page and selecting 'Add Listing'. The registration process allows you to input your business name, address, contact numbers, operational hours, services offered, and high-resolution showroom photographs. Once submitted, our local verification team verifies the physical address within 24 hours to ensure high consumer trust and top ranking on Google.

Can I read Haldwani Times articles in Hindi as well as English?

Yes, Haldwani Times features a seamless, native bilingual reading experience tailored for our regional readership. With our one-click language toggle located prominently in the navigation bar, you can instantly switch between English and pure Hindi. Both versions feature carefully crafted editorial phrasing, accurate regional terminology, and culturally resonant storytelling to ensure maximum readability for students, families, and senior citizens alike.

How do I submit news tips, event notices, or press releases to the editorial team?

Our newsroom warmly welcomes verified news tips, community event notices, civic grievances, and official press releases from citizens and local organizations. You can submit your documents, photos, or video evidence directly to our central editorial desk at editorial@haldwanitimes.com or via our Help & Support page. Our senior editors review every submission for factual authenticity, multi-source verification, and public relevance prior to publication.

Where can visitors find authentic Kumaoni Bal Mithai and Singaudi in Haldwani?

Renowned traditional sweet houses clustered along Bada Bazaar, Mangal Parao, Kathgodam Station Road, and Nainital Road specialize in daily batches of authentic Bal Mithai and fragrant Singaudi prepared with pure mountain dairy khoya and natural ingredients.

What transportation options are available for traveling from Haldwani to Nainital and Bhimtal?

Continuous state transport buses (UTC), KMOU coaches, and registered taxi union sharing cabs operate 24/7 from the Haldwani Roadways Bus Station (near Tikonia) and Kathgodam Railway Station. Fares are regulated by the transport department, with mountain travel times ranging between 1 to 1.5 hours.