Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,24 @@ AnyCode is a multi-agent AI orchestration framework for Python. It composes auto

---

## Using the Library

When writing code that *uses* AnyCode (examples, tests, docs snippets), do not read the
source tree to learn the API:

```bash
anycode api --core # the 15 symbols covering most use, with live signatures
anycode api Agent # one symbol in full
anycode api --json # the whole surface, machine-readable
```

`site_docs/reference/recipes.md` holds complete runnable snippets, and
`site_docs/reference/llm-guide.md` is a short orientation written for AI coding agents.
Prefer `Agent(name=..., tools=[...])` and the `@tool` decorator over hand-built
`ToolRegistry`/`ToolExecutor` wiring, which remains public for advanced use.

---

## Project Structure & Module Organization

Source code lives under `src/anycode/` and follows a layered architecture:
Expand Down
31 changes: 31 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [0.10.0] - 2026-07-25

Developer-experience release. **No 0.9.0 API was removed, renamed, or changed** — every
existing program runs unchanged. See [Migrating to 0.10](https://quantlix.github.io/anycode/latest/contributing/migration-0.10/).

### Added

- **`@tool` decorator** - any Python function becomes an agent tool. The signature becomes the Pydantic input model, the Google-style docstring becomes the description and per-parameter descriptions, and the return value is coerced into a `ToolResult`. Sync functions run off the event loop; a `ToolUseContext` parameter is injected rather than exposed in the schema; `Annotated` constraints survive into the JSON Schema. The decorated function stays directly callable. `as_tool_definition()` normalizes a `ToolDefinition`, a decorated function, a plain function, or a built-in tool name.
- **Keyword agent construction** - `Agent(name=..., instructions=..., tools=[...])` wires its own registry and executor, so one working agent is one object instead of three. Provider and model are auto-detected from whichever credentials are present (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GOOGLE_API_KEY`, `AZURE_OPENAI_API_KEY`, `AWS_DEFAULT_REGION`, `OLLAMA_BASE_URL`), overridable with `ANYCODE_DEFAULT_PROVIDER` / `ANYCODE_DEFAULT_MODEL`. CrewAI-style `role`/`goal`/`backstory` compose into a system prompt. `tools=` accepts functions, `ToolDefinition`s, and built-in names.
- **Blocking entry points** - `Agent.run_sync`, `prompt_sync`, `stream_sync` (incremental, via a worker loop), `call_tool` / `call_tool_sync`, plus `Crew.run_sync` and `CompiledWorkflow.run_sync` / `stream_sync`.
- **`Crew`** - a one-import multi-agent entry point over the existing wavefront scheduler. Tasks accept a `TaskSpec`, a dict, or a bare string title; `process="sequential"` chains tasks that declare no dependency of their own; with no tasks, `run(goal)` falls through to coordinator decomposition. `CrewResult` exposes `success`, `output`, `outputs`, `usage`, and `cost` while keeping the full `TeamRunResult` attached.
- **`Workflow`** - a state-graph runtime for branching, looping, retry, and fan-out. Frozen Pydantic state (or a dict), nodes returning patches, `Command` for dynamic routing, reducers (`add`, `merge`, `keep_first`, `keep_last`), conditional edges with or without a path map, compile-time validation that aggregates every structural problem, a `max_steps` cap surfaced as the new `max_steps` stop reason, event streaming, and `to_mermaid()` / `to_dict()`. Nodes may be async or sync functions, an `Agent`, a `Crew`, or another compiled workflow.
- **Long-horizon capabilities on `Agent`** - `planning=True` registers `write_todos` and exposes `agent.todos`; `subagents=[SubAgentSpec(...)]` registers a `delegate` tool whose sub-agents run on a fresh conversation with depth capped at one and usage merged into the parent result; `workspace=` creates a directory and confines the file tools to it. Each is inert unless switched on. There is no separate deep-agent class.
- **`TaskSpec` ergonomics** - `agent=`, `expected_output=`, and `context=`, with `description` defaulting to the title. `expected_output` reaches the agent prompt as an explicit line, and `Task` carries it through the queue and checkpoints.
- **Machine-readable API map** - `anycode.describe()` and the `anycode api` command (`--core`, `--compact`, `--json`, or a single symbol) render the public surface as data so an AI coding agent can learn the API without reading the source.
- **`AnyCode.register_agent(agent)`** - adopt a pre-built agent into an engine so it keeps the tool registry it was constructed with.
- **Documentation** - new guides for function tools, crews, workflows, and long-horizon agents; a recipes page of runnable snippets; an orientation page for AI coding agents; a core-surface table in the public API reference; and a migration page.
- **Examples** - `45_function_tools.py`, `46_crew_quickstart.py`, `47_workflow_graph.py`, and `48_long_horizon_agent.py`, all verified against a live provider.

### Changed

- **Lazy public API** - `import anycode` dropped from ~1913 ms and 1312 modules to ~33 ms and 73 modules. Symbols resolve on first attribute access and cache into the module namespace; a `TYPE_CHECKING` block keeps every name statically resolvable. Optional dependencies (chromadb, redis, OpenTelemetry, the MCP SDK, provider clients) are imported only when their code path runs. Unknown attributes raise `AttributeError` with a did-you-mean suggestion. First use of `Agent` fell from 1758 ms to ~414 ms, and of `Crew` from 1855 ms to ~476 ms.
- **`Agent(tools=[])` means no tools.** An empty list was previously indistinguishable from `None`; `tools=None` remains the default and still means every built-in tool.
- **Missing optional memory backends** report the extra to install instead of silently vanishing from `anycode.memory.__all__`.

### Fixed

- **Latent circular import** - `anycode.types` → `identity` → `contracts` → `helpers` → `anycode.types` meant `import anycode.types` failed on its own; the eager package `__init__` had been masking it. Each of `anycode.types`, `.helpers`, `.contracts`, `.identity`, `.core`, and `.memory` is now importable standalone.
- **`Agent.call_tool` could not invoke a side-effecting tool** - it now supplies a fresh idempotency key when the arguments do not carry one.
- **Clock-resolution flake in `FilesystemRunStore.mark_interrupted_runs`** - the staleness cutoff is inclusive, so `stale_after_seconds=0` means "every running run is stale" even when the platform clock has not ticked since the heartbeat was written.

## [0.9.0] - 2026-07-24

### Added
Expand Down
164 changes: 65 additions & 99 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ AnyCode is built for experimentation, evaluation, local development, research pr
| --- | --- |
| Distribution | `anycode-py` |
| Import package | `anycode` |
| Current version | `0.9.0` |
| Current version | `0.10.0` |
| Python | `>=3.12` |
| Project status | Alpha |
| License | MIT |
Expand All @@ -64,6 +64,10 @@ Key use cases include:

| Area | What is available today |
| --- | --- |
| Getting started | `Agent(name=..., tools=[...])`, the `@tool` decorator, `run_sync`, and provider auto-detection |
| Multi-agent | `Crew` over the wavefront scheduler, with `TaskSpec` dependencies and `expected_output` |
| Control flow | `Workflow` state graphs with conditional edges, loops, fan-out, reducers, and a step cap |
| Long-horizon | `planning=`, `subagents=`, and `workspace=` on the same `Agent` — no separate deep-agent class |
| Core orchestration | `AnyCode`, `Agent`, `AgentRunner`, `AgentPool`, `Team`, `TaskQueue`, and `Scheduler` |
| Team coordination | `MessageBus`, `SharedMemory`, task queues, event callbacks, and team-level results |
| Task scheduling | Explicit `TaskSpec` dependencies, topological sort, wavefront execution, and cascading failure handling |
Expand All @@ -78,6 +82,7 @@ Key use cases include:
| Verification | Built-in `ruff`, `pyright`, `pytest`, `schema`, and `regex` sensors with quality gate decisions |
| Evaluation | Scenario loading, deterministic fake responses, benchmark reports, markdown rendering, and report comparison |
| Developer experience | CLI commands, YAML/TOML config, examples cookbook, CLI inspection, and deterministic eval reports |
| AI agent affordances | `anycode api` and `anycode.describe()` for a machine-readable API map, plus a recipes page |
| Extension ecosystem | Typed `Plugin` bundles (tools, provider factories, sensors, hooks) registered via `engine.register_plugin()` or auto-discovered through the `anycode.plugins` entry-point group |
| Service client | Dependency-free TypeScript preview for lifecycle, artifact, cancellation, and resumable-stream operations in Node.js 20+ and modern browsers |

Expand Down Expand Up @@ -144,128 +149,89 @@ Only one supported provider is required to run the basic examples. Never commit
### 4. Run One Agent

```python
import asyncio
import os

from dotenv import load_dotenv

from anycode import AnyCode
from anycode import Agent, tool

load_dotenv()


def resolve_model() -> tuple[str, str]:
if os.environ.get("ANTHROPIC_API_KEY"):
return "anthropic", "claude-haiku-4-5"
if os.environ.get("OPENAI_API_KEY"):
return "openai", "gpt-4o-mini"
raise RuntimeError("Set ANTHROPIC_API_KEY or OPENAI_API_KEY first.")


async def main() -> None:
provider, model = resolve_model()
engine = AnyCode(config={"default_provider": provider, "default_model": model})
@tool
def word_count(text: str) -> int:
"""Count the words in a block of text."""
return len(text.split())

result = await engine.run_agent(
config={
"name": "explainer",
"provider": provider,
"model": model,
"system_prompt": "You explain Python clearly and briefly.",
"tools": [],
"max_turns": 2,
},
prompt="Explain what an async generator is in two sentences.",
)

print(result.output)
print(f"tokens: in={result.token_usage.input_tokens} out={result.token_usage.output_tokens}")
editor = Agent(
name="editor",
instructions="You are a concise copy editor. Use your tools rather than guessing.",
tools=[word_count],
)


asyncio.run(main())
result = editor.run_sync("How many words are in: 'the quick brown fox jumps over it'?")
print(result.output)
print(f"tokens: in={result.token_usage.input_tokens} out={result.token_usage.output_tokens}")
```

### 5. Run A Team With Dependencies
The provider and model are detected from whichever API key is present, the tool schema
comes from the function signature, and its description comes from the docstring. Pass
`provider=` and `model=` to be explicit, and use `await agent.run(...)` inside async code.

```python
import asyncio
import os
### 5. Run A Crew With Dependencies

```python
from dotenv import load_dotenv

from anycode import AgentConfig, AnyCode, TaskSpec, TeamConfig
from anycode import Agent, Crew, TaskSpec

load_dotenv()

PROVIDER = "anthropic" if os.environ.get("ANTHROPIC_API_KEY") else "openai"
MODEL = "claude-haiku-4-5" if PROVIDER == "anthropic" else "gpt-4o-mini"
researcher = Agent(name="researcher", role="a research analyst", goal="gather the facts", tools=[])
writer = Agent(name="writer", role="a technical writer", goal="turn facts into prose", tools=[])

crew = Crew(
agents=[researcher, writer],
tasks=[
TaskSpec("Research", "List three tradeoffs of vector databases.", agent=researcher),
TaskSpec(
"Write",
"Turn those tradeoffs into a short briefing.",
agent=writer,
depends_on=["Research"],
expected_output="Under 120 words, no bullet points.",
),
],
verbose=True,
)

result = crew.run_sync()
print(result)
```

async def main() -> None:
engine = AnyCode(config={"max_concurrency": 3})

team = engine.create_team(
"guide-crew",
TeamConfig(
name="guide-crew",
shared_memory=True,
agents=[
AgentConfig(
name="planner",
provider=PROVIDER,
model=MODEL,
system_prompt="Create concise technical plans.",
tools=[],
),
AgentConfig(
name="writer",
provider=PROVIDER,
model=MODEL,
system_prompt="Turn plans into clear developer documentation.",
tools=[],
),
AgentConfig(
name="reviewer",
provider=PROVIDER,
model=MODEL,
system_prompt="Review documentation for clarity and missing steps.",
tools=[],
),
],
),
)

result = await engine.run_tasks(
team,
[
TaskSpec(
title="Plan guide",
description="Outline a getting started guide for a Python agent framework.",
assignee="planner",
),
TaskSpec(
title="Draft guide",
description="Write the guide using the plan from the planner.",
assignee="writer",
depends_on=["Plan guide"],
),
TaskSpec(
title="Review guide",
description="Review the draft and list concrete improvements.",
assignee="reviewer",
depends_on=["Draft guide"],
),
],
)

print(f"success={result.success}")
for agent_name, agent_result in result.agent_results.items():
print(f"\n[{agent_name}]\n{agent_result.output[:600]}")
Independent tasks run concurrently; `depends_on` feeds one task's output into the next.
Drop `tasks` and call `crew.run("some goal")` to have the first agent plan the work itself.
`Crew` is a facade over the `AnyCode` engine, which stays public — see
[Run a multi-agent team](https://quantlix.github.io/anycode/latest/guides/multi-agent-team/)
for the engine-level API.

### 5b. Compose A Workflow With Branching

asyncio.run(main())
```python
from anycode import END, START, Agent, Workflow

workflow = Workflow()
workflow.add_node("draft", Agent(name="writer", tools=[]), input_key="topic", output_key="draft")
workflow.add_edge(START, "draft")
workflow.add_conditional_edge("draft", lambda state: END if state["draft"] else "draft")

result = workflow.compile().run_sync({"topic": "hybrid search"})
print(result.state["draft"], result.path)
```

Use a crew when the work is a dependency graph, and a workflow when you need branching,
looping, or retry. See [Workflows](https://quantlix.github.io/anycode/latest/guides/workflows/).


### 6. Use YAML Or TOML Config

Install the CLI extra first:
Expand Down
Loading
Loading