Observed since 20 Oct, 22:12 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
A building block library for composed agent workflows
A composable building block library for AI agent workflows. / Uma biblioteca componível para construir fluxos de agentes de IA.
A library to build agent workflows like Lego blocks. Each step in your agentic pipeline is a self-contained block, with strictly typed inputs and outputs via Pydantic and natively concurrent execution using AsyncIO and NetworkX graphs.
add_cycle()). The executor handles iteration, feedback propagation, and exit conditions automatically.@as_tool — no class boilerplate required.tool_calls execute actions — text is never reinterpreted as a tool call — and built-in loop detection blocks a call a model keeps repeating verbatim instead of correcting it.Install the latest release:
pip install agenticblocks.io
Or for local development:
pip install -e .
from pydantic import BaseModel
class HelloInput(BaseModel):
name: str
class HelloOutput(BaseModel):
greeting: str
from agenticblocks.core.block import Block
class HelloWorldBlock(Block[HelloInput, HelloOutput]):
name: str = "say_hello"
async def run(self, input: HelloInput) -> HelloOutput:
msg = f"Hello, {input.name}! Welcome to agenticblocks."
return HelloOutput(greeting=msg)
import asyncio
from agenticblocks.core.graph import WorkflowGraph
from agenticblocks.runtime.executor import WorkflowExecutor
async def main():
graph = WorkflowGraph()
graph.add_block(HelloWorldBlock(name="say_hello"))
executor = WorkflowExecutor(graph)
ctx = await executor.run(initial_input={"name": "Alice"})
print(ctx.get_output("say_hello").greeting)
asyncio.run(main())
Any Python function can be registered as a block with @as_tool. Both sync and async functions are supported — sync functions run in a thread pool automatically.
from agenticblocks import as_tool
from agenticblocks.blocks.llm.agent import LLMAgentBlock
@as_tool
async def fetch_weather(city: str) -> str:
"""Returns the current weather for a city."""
return f"Sunny in {city}."
agent = LLMAgentBlock(
name="assistant",
model="gpt-4o-mini",
tools=[fetch_weather], # same interface as any Block
)
LLMAgentBlock is a ready-to-use orchestrator that dynamically translates your other Blocks into Tools (Agent-to-Agent) seamlessly.
max_tool_calls prevents runaway loops.model_kargs (HTTP clients, timeouts, etc.) to optimize API performance.on_iteration parameter to inject callbacks that execute at the beginning of each loop iteration. These callbacks receive the current iteration number and the list of messages, allowing for real-time monitoring, logging, or dynamic prompt adjustments during the agent's execution.AgentInput prompt using Python format-strings. Useful for "diamond" graph patterns (e.g., feeding both the original topic and a search report to a final summarizer).agenticblocks.ImageGenerationBlock returns ImageArtifacts carrying real bytes with a sniffed MIME type, whichever route the provider exposes (images API or multimodal chat). Register your own route with register_image_adapter; anything that cannot generate raises a classified ImageGenerationError instead of returning an empty file.LLMAgentBlock and MemGPTAgentBlock track the (name, arguments) signature of every tool call. A call repeated more than loop_detection_limit times (default 3) is blocked before execution and answered with a corrective tool result, so a weak model changes approach instead of burning its whole budget on the same failing call.Declare validator loops directly in the graph without any wrapper block:
from agenticblocks import as_tool
from agenticblocks.core.graph import WorkflowGraph
from agenticblocks.blocks.llm.agent import LLMAgentBlock
writer = LLMAgentBlock(
name="writer",
model="gpt-4o-mini",
system_prompt="Write a detailed essay about AI."
)
@as_tool
def validate_output(content: str) -> dict:
ok = len(content.split()) >= 100
return {"is_valid": ok, "feedback": "Too short." if not ok else ""}
graph = WorkflowGraph()
graph.add_block(writer)
graph.add_block(validate_output)
graph.add_cycle(
name="refine",
edges=[("writer", "validate_output")],
condition_block="validate_output",
max_iterations=3,
)
# Downstream nodes connect to the cycle output as a normal node
graph.connect("refine", "publisher")
The executor runs the cycle, propagates feedback to the producer on each rejection, and stores the result in ctx under the cycle name.
AgenticBlocks supports dynamic code execution out-of-the-box. Instead of relying on predefined tools, you can use the CodePlanExecutorBlock to orchestrate an LLM that generates a standalone Python script to solve a problem. The generated code is automatically executed either locally or securely in an ephemeral Docker container via the PythonCodeExecutorBlock. See more in docs/codeplanner.md.
It is recommended to install Ollama with the model granite4:1b (ollama run granite4:1b) to test the examples locally. Alternatively, you can modify the examples to use a commercial API, such as Gemini (gemini/gemini-2.0-flash) or OpenAI.
| Example | Description |
|---|---|
01_hello_world.py | Minimal block + graph + executor setup |
02_llm_pipeline.py | Parallel wave execution with multiple blocks |
03_mcp_a2a_agent.py | MCP bridge + Agent-to-Agent (A2A) tool delegation |
04_mcp_python_native.py | Native Python MCP server |
05_basic_blocks.py | Overhead benchmarking |
06_functionastool.py | @as_tool decorator for plain functions |
07_validator_loop.py | Native graph cycle with producer + validator feedback loop |
08_planner.py | JSON Plan-and-Execute pattern |
09_code_planner_local.py | Code-Generation Planner running locally |
10_code_planner_docker.py | Code-Generation Planner running inside a Docker sandbox |
Note: Quantized or small models like
granitemay produce lower-quality reasoning and struggle with native tool calling. Since only nativetool_callsexecute actions, a model that writes its calls as plain-text JSON simply will not act — for reliable local tool usage, usellama3.1ormistral-nemo. Large commercial models (OpenAI, Gemini, Anthropic) yield excellent results but require an API key.
Uma biblioteca para construir fluxos de agentes no estilo Lego. Cada passo do seu pipeline agêntico é um bloco auto-contido, com entradas e saídas rigorosamente tipadas via Pydantic e execução simultânea usando AsyncIO e grafos do NetworkX.
add_cycle(). O executor gerencia iteração, propagação de feedback e condição de saída automaticamente.@as_tool — sem boilerplate de classe.tool_calls nativas do provedor executam ações — texto nunca é reinterpretado como chamada de ferramenta — e a detecção de laços bloqueia a chamada que o modelo repete literalmente em vez de corrigir.Instale o último lançamento:
pip install agenticblocks.io
Ou para desenvolvimento local:
pip install -e .
A estrutura básica é idêntica ao tutorial acima (seção em inglês): defina modelos Pydantic, crie um Block, adicione ao WorkflowGraph e execute com WorkflowExecutor.
Qualquer função pode ser registrada como bloco com @as_tool. Funções síncronas rodam em thread pool automaticamente.
from agenticblocks import as_tool
@as_tool
def buscar_clima(cidade: str) -> str:
"""Retorna o clima atual de uma cidade."""
return f"Ensolarado em {cidade}."
O LLMAgentBlock abstrai e converte sub-blocos em ferramentas nativas (A2A). Destaques:
max_tool_calls: Limita o loop de ferramentas para evitar execuções infinitas.model_kargs.AgentInput formatado. Ideal para padrões de grafo em "diamante".agenticblocks.ImageGenerationBlock devolve ImageArtifacts com bytes reais e MIME detectado, seja qual for a rota do provedor (API images ou chat multimodal). Registre rotas próprias com register_image_adapter; o que não puder ser gerado levanta um ImageGenerationError classificado em vez de devolver um arquivo vazio.LLMAgentBlock e MemGPTAgentBlock acompanham a assinatura (nome, argumentos) de cada chamada. Uma chamada repetida mais de loop_detection_limit vezes (padrão 3) é bloqueada antes da execução e respondida com um resultado corretivo, para o modelo mudar de abordagem em vez de gastar todo o orçamento na mesma chamada que falha.on_iteration): Use o parâmetro on_iteration para injetar funções de callback que serão executadas no início de cada iteração do loop do agente. Isso permite monitoramento em tempo real, logging ou ajustes dinâmicos no prompt durante a execução do agente.Declare um loop validador diretamente no grafo — sem bloco orquestrador especial:
from agenticblocks import as_tool
from agenticblocks.core.graph import WorkflowGraph
from agenticblocks.blocks.llm.agent import LLMAgentBlock
escritor = LLMAgentBlock(
name="escritor",
model="gpt-4o-mini",
system_prompt="Escreva uma redação detalhada sobre IA."
)
@as_tool
def validar(content: str) -> dict:
ok = len(content.split()) >= 100
return {"is_valid": ok, "feedback": "Muito curto." if not ok else ""}
graph = WorkflowGraph()
graph.add_block(escritor)
graph.add_block(validar)
graph.add_cycle(
name="refinar",
edges=[("escritor", "validar")],
condition_block="validar",
max_iterations=3,
)
graph.connect("refinar", "publicador")
O executor itera automaticamente, injeta o feedback no prompt do produtor a cada rejeição e disponibiliza o resultado final em ctx.get_output("refinar").
O AgenticBlocks oferece suporte a execução dinâmica de código nativamente. Em vez de depender de ferramentas pré-definidas, você pode usar o CodePlanExecutorBlock para orquestrar um LLM na geração de um script Python completo capaz de resolver um problema. O código gerado é então testado e executado automaticamente no modo local ou de forma segura isolado em um contêiner Docker via PythonCodeExecutorBlock. Veja mais em docs/codeplanner.md.
Recomenda-se instalar o Ollama com o modelo granite4:1b para testar localmente. Alternativamente, use uma API comercial como Gemini ou OpenAI.
| Exemplo | Descrição |
|---|---|
01_hello_world.py | Setup mínimo: bloco + grafo + executor |
02_llm_pipeline.py | Execução paralela em waves |
03_mcp_a2a_agent.py | Bridge MCP + delegação A2A entre agentes |
04_mcp_python_native.py | Servidor MCP nativo em Python |
05_basic_blocks.py | Benchmark de overhead |
06_functionastool.py | Decorator @as_tool para funções simples |
07_validator_loop.py | Ciclo nativo no grafo: produtor + validador com feedback |
08_planner.py | Padrão JSON Plan-and-Execute |
09_code_planner_local.py | Planejador via Geração de Código (ambiente Local) |
10_code_planner_docker.py | Planejador via Geração de Código (Sandbox Docker) |
Atenção: Modelos quantizados ou menores podem produzir resultados abaixo do esperado e ter dificuldade com chamadas nativas de ferramentas. Como apenas
tool_callsnativas executam ações, um modelo que escreve as chamadas como JSON em texto simplesmente não age — para uso local confiável, prefirallama3.1oumistral-nemo. Modelos comerciais grandes geram excelentes resultados, mas exigem configuração de API KEY.
Download counts and popularity will appear here as the collector receives them.
| Version | Published | Direct dependencies | Open version |
|---|---|---|---|
| 0.9.16 | 23 Aug 2026 | 6 |
This describes our collected data; it is not a security assessment.
Observed since 20 Oct, 22:12 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
package:b8f38f136b65fd4607dc6b18596b60331a5477f3c0c2478d8e3be202542a39db