Rust 的代理循环 - 从 7 个 LLM 协议中读取流,运行工具,直到完成为止。
git clone https://github.com/yologdev/yoagent && cd yoagent
ollama serve & # any local model works
cargo run --example cli -- --provider ollamaThat's a working coding agent in your terminal — file read/write/edit, shell, ripgrep search, streaming output, skills. No signup, no key, nothing to configure.
yoagent cli — mini coding agent
Type /quit to exit, /clear to reset
model: llama3.1:8b
cwd: /home/user/my-project
> find all TODO comments in src/
▶ search 'TODO' ✓
Found 3 TODOs:
src/main.rs:42: // TODO: handle edge case
src/lib.rs:15: // TODO: add tests
src/utils.rs:8: // TODO: optimize this
tokens: 1250 in / 89 outPoint it at a hosted model instead by swapping the flag:
ANTHROPIC_API_KEY=sk-... cargo run --example cli
GROQ_API_KEY=... cargo run --example cli -- --provider groq --model llama-3.3-70b-versatile
cargo run --example cli -- --api-url http://localhost:1234/v1 --model my-model # LM Studio, llama.cpp, vLLM[dependencies]
yoagent = "0.15"
tokio = { version = "1", features = ["full"] }An agent that actually uses a tool — the thing the crate exists for:
…Swap the model by swapping the config — the provider follows, and the key is read from that provider's conventional env var:
Agent::from_config(ModelConfig::groq("llama-3.3-70b-versatile", "Llama 3.3 70B")); // GROQ_API_KEY
Agent::from_config(ModelConfig::google("gemini-2.5-pro", "Gemini 2.5 Pro")); // GEMINI_API_KEY
Agent::from_config(ModelConfig::ollama("http://localhost:11434", "llama3.1:8b")); // no keyyoagent is deliberately narrow. It is the loop, tool execution, and the machinery you need to run that loop in production. It ships no vector stores, embedding pipelines, or task-graph layer — if your problem is retrieval or orchestration, one of these is the better fit:
| If you need | Look at |
|---|---|
| RAG pipelines, vector stores, embeddings, transcription and image generation | rig — "Build modular and scalable LLM Applications in Rust" |
| Typed task graphs and streaming RAG indexing alongside agents | swiftide — "Composable LLM agents and harness, typed task graphs, and streaming RAG pipelines in Rust" |
| A tool-calling loop you host, gate, steer, branch, and record | yoagent |
What that focus bought:
agent_loop() is stateless and takes
everything it needs as arguments. Agent is an optional wrapper that adds history and queues.
You can drive the loop yourself without adopting our state model.ToolMiddleware can allow, modify, or deny each call
at a single choke point shared by all execution strategies — the mechanism behind approval
prompts and policy engines.Session forks, checkpoints, and seeks.
Edit an earlier turn and re-run it without destroying the original branch.features = ["gasp"], a run becomes an append-only semantic
event log in a git repo — restore is clone + replay. Conformance-checked in CI.MockProvider scripts multi-turn tool-calling
conversations and honours cancellation, so abort and steering paths are testable with no
network. 456 of our 463 tests need no key.yoyo-evolve [![][yoyo-stars]][yoyo-link] — a coding
agent that evolves its own source in public. It began as 200 lines of Rust; every commit since has
been agent-written and gated on tests. It runs on this loop with the openapi feature enabled.
Also built on yoagent:
| Project | What it is |
|---|---|
rab |
A lightweight, extensible Rust coding agent |
greatsage |
"Rimuru's Unique Skill, you know the one" |
yoclaw |
OpenClaw reborn in Rust — a single-binary agent that remembers you |
Built something on yoagent? Open a PR and add it here — we'd like to see it.
The loop & control
AgentStart → TurnStart → MessageUpdate (deltas) → ToolExecution* → TurnEnd → AgentEndSequential and Batched { size } strategies availableToolMiddleware — async Allow / Modify(args) / Deny(reason) hooks gating every call. A denial becomes an error tool result the model sees, so the loop keeps goingInputFilter — rewrite or reject user input before it reaches the model (PII redaction, prompt-injection guards)abort(), and lifecycle callbacks (before_turn, after_turn, on_error)Providers — 7 protocols, 20+ providers
| Protocol | Providers |
|---|---|
| Anthropic Messages | Anthropic (Claude) |
| OpenAI Completions | OpenAI, xAI, Groq, Cerebras, OpenRouter, Mistral, DeepSeek, MiniMax, Z.ai, Qwen, Meta (Muse Spark), Ollama, local servers, custom compatible APIs |
| OpenAI Responses | OpenAI (Responses API) |
| Azure OpenAI | Azure OpenAI |
| Google Generative AI | Google Gemini |
| Google Vertex | Google Vertex AI |
| Bedrock ConverseStream | Amazon Bedrock |
ModelConfig presets cover the common providers; ModelConfig::openai_compat(..) handles anything
else with a base_url. Per-provider quirks (auth style, reasoning format, max_tokens field name)
live in OpenAiCompat / AnthropicCompat flags — 12 compat profiles ship in the box.
The opencode_zen(..) / opencode_go(..) gateways pick the wire protocol from the model id
automatically, so one config reaches models across several vendors.
Thinking/reasoning controls are wired for all 7 protocols. Client-side cache hints are sent on two:
Anthropic gets cache_control breakpoints, native OpenAI gets a prompt_cache_key. Most others cache
server-side with nothing to configure; Bedrock does not cache automatically, and its explicit
cachePoint blocks are not yet wired. Context-overflow detection is centralised across 15+
provider-specific error strings.
Tools — built-in, custom, MCP, OpenAPI
Built in: bash (timeout, deny patterns), read_file / write_file (line numbers, path
restrictions), edit_file (fuzzy-match hints on failure), list_files, search (ripgrep).
Tools return stdout and stderr even on failure, so the model can self-correct.
Custom tools implement one trait:
…MCP — with_mcp_server_stdio() / with_mcp_server_http() connect to Model Context Protocol
servers over stdio or Streamable HTTP (session ids, SSE framing, incremental parsing) and register
their tools transparently.
OpenAPI (features = ["openapi"]) — point with_openapi_url() at a spec and every operation
becomes a tool, filtered by OperationFilter.
Sub-agents & shared state
SubAgentTool delegates to a child loop with its own model, system prompt, tools, skills,
middleware, retry policy, and turn limits — a fully independent configuration, not a thin shim.
Run a cheap model for triage and an expensive one for the hard step in the same session.
SharedState is a pluggable key-value store (MemoryBackend, FileBackend, or your own via the
SharedStateBackend trait). A parent stores a large artifact once and sub-agents read it by key,
so it never gets re-pasted into every context window. Opt in with .with_shared_state(state) —
it injects the shared_state tool and a state summary into the sub-agent's system prompt.
Context, sessions & skills
ContextTracker — hybrid real-usage + estimation, calibrated against actual provider usage
Tiered compaction — truncate tool outputs → summarise old turns → drop middle turns
LlmCompaction — opt-in alternative that summarises the dropped span with a background LLM request instead of discarding it. The request runs off the hot path and is spliced in on a later turn, so the loop never stalls and can never wedge on it — an unfinished or failed summary falls back to the deterministic tiers. Buys retention quality; costs tokens the default never spends, and does not reduce prefix-cache breaks. Both paths report their own cost on AgentEvent::ContextCompacted
let agent = Agent::from_config(ModelConfig::anthropic("claude-sonnet-5", "Sonnet 5"))
.with_compaction_strategy(LlmCompaction::from_config(
ModelConfig::anthropic("claude-haiku-4-5", "Haiku 4.5"), // cheap model for summaries
));Session — history as an id/parent tree with append, seek, checkpoint, branch_tips, and JSONL persistence. Appending after a seek forks a branch; it never overwrites
Skills — load AgentSkills-standard SKILL.md directories. The agent sees a compact index and reads the full skill on demand, so skills stay cross-compatible with Claude Code, Codex CLI, Cursor, and others
Structured outputs — prompt_structured::() returns typed, schema-validated replies, enforced natively where supported (Anthropic tool-forcing, OpenAI json_schema, Gemini responseSchema)
Production concerns
CostConfig carries separate input/output/cache-read/cache-write rates plus optional context tiers; session_cost_usd() gives a running total, AgentEvent::AgentEnd carries a SessionStats rollup, and is_configured() distinguishes "free" from "pricing unknown"AgentEvent::LoopDetected either waySharedState and the full text is stashed, with the marker naming a key the model can fetchtracing spans per loop / LLM stream / tool, recording tokens and cost. OpenTelemetry is bridged app-side via tracing-opentelemetry; the library carries no OTel dependency by designfeatures = ["gasp"]) — record runs into a GASP agent repo; yoagent is a tested-conformant runtime, with the 7-check suite running in CISerialize / Deserialize / PartialEq, so sessions persist and replayset_model() — hot-swap the model mid-session without rebuilding the agentTen runnable examples in examples/. Five need no API key at all.
| Example | What it shows | Key needed |
|---|---|---|
cli |
A 370-line coding agent — all tools, skills, streaming, colored output. Like a baby Claude Code | optional¹ |
rlm |
An LLM that explores a codebase on its own by spawning sub-agents |
暂无开放 Issues,或尚未同步最近议题。