From d779c21b54843d2abf618e09eb63b596e2ac4a3b Mon Sep 17 00:00:00 2001 From: Dhruv Garg Date: Mon, 16 Nov 2026 12:07:25 +0530 Subject: [PATCH] docs: cover five v3 agent runtime features --- docs/agents/federation.md | 72 ++++++++++++++++++++++++++++++++ docs/agents/mcp-tool-scanning.md | 68 ++++++++++++++++++++++++++++++ docs/agents/mcp.md | 65 ++++++++++++++++++---------- docs/api/evaluation.md | 6 +++ docs/cookbook/agent-patterns.md | 42 ++++++++++++------- docs/evaluation/ruler-rewards.md | 64 ++++++++++++++++++++++++++++ docs/evaluation/simulation.md | 57 +++++++++++++++++++++++++ docs/llms/deliberation.md | 49 ++++++++++++++++++++++ docs/llms/overview.md | 1 + docs/patterns/agent-patterns.md | 42 ++++++++++++------- sidebars.ts | 4 +- 11 files changed, 416 insertions(+), 54 deletions(-) create mode 100644 docs/agents/mcp-tool-scanning.md create mode 100644 docs/evaluation/ruler-rewards.md create mode 100644 docs/evaluation/simulation.md create mode 100644 docs/llms/deliberation.md diff --git a/docs/agents/federation.md b/docs/agents/federation.md index 45151545a..27430d947 100644 --- a/docs/agents/federation.md +++ b/docs/agents/federation.md @@ -145,6 +145,78 @@ federation = AgentFederation( - `discover(*, tools=None, tags=None, min_capacity=None, healthy_only=True) -> list[AgentMetadata]` — list agents matching filters - `select_agent(*, strategy=None, tags=None, tools=None, min_capacity=None, healthy_only=True) -> AgentMetadata` — select one agent using the routing strategy - `async run(prompt: str, *, agent_id=None, strategy=None, tags=None, tools=None, min_capacity=None, healthy_only=True, **kwargs) -> Any` — select an agent and dispatch the prompt +- `async negotiate(initial: NegotiationMessage, *, max_rounds=10, deliver_terminal=True) -> Negotiation` — exchange bounded price/SLA offers between two registered clients + +## Price and SLA negotiation + +Negotiation is an explicit operation; accepted agreements can optionally be supplied to sealed-bid market routing as described below. Both agents must already be registered, healthy, and provide a client implementing `negotiate(message)`. `BoundedNegotiationPolicy` makes deterministic decisions against each participant's own reservation bounds: + +```python +import asyncio +from decimal import Decimal +from synapsekit.agents import ( + AgentFederation, AgentMetadata, BoundedNegotiationPolicy, + NegotiationMessage, NegotiationMessageKind, NegotiationRole, NegotiationTerms, +) + +def terms(price, latency_ms, availability): + return NegotiationTerms( + Decimal(price), "USD", Decimal(latency_ms), Decimal(availability), Decimal("3600") + ) + +buyer_policy = BoundedNegotiationPolicy( + NegotiationRole.BUYER, terms("15", "200", "99.9") +) +seller_policy = BoundedNegotiationPolicy( + NegotiationRole.SELLER, terms("12", "150", "99.95") +) + +class Participant: + def __init__(self, policy, role): + self.policy = policy + self.role = role + self.terminal = None + + async def run(self, prompt, **kwargs): + return prompt # Normal execution is separate from negotiation. + + async def negotiate(self, message): + can_counter = self.role == NegotiationRole.SELLER + return self.policy.respond( + message, + message_id=f"{message.message_id}-response", + can_counter=can_counter, + ) + + async def receive_negotiation(self, message): + self.terminal = message + +async def main(): + buyer = Participant(buyer_policy, NegotiationRole.BUYER) + seller = Participant(seller_policy, NegotiationRole.SELLER) + federation = AgentFederation(clients={"buyer": buyer, "seller": seller}) + federation.register_agent(AgentMetadata(id="buyer", model="local")) + federation.register_agent(AgentMetadata(id="seller", model="local")) + initial = NegotiationMessage( + "neg-1", "offer-1", "buyer", "seller", NegotiationMessageKind.OFFER, + terms("10", "200", "99.9"), + ) + session = await federation.negotiate(initial, max_rounds=4, deliver_terminal=True) + assert session.agreement == seller_policy.reservation + assert seller.terminal.kind == NegotiationMessageKind.ACCEPT + +asyncio.run(main()) +``` + +By default, both clients must implement `receive_negotiation(message)`; the final ACCEPT or REJECT is delivered to its recipient, and delivery errors propagate. Explicit `deliver_terminal=False` selects transcript-only mode, which does not deliver the terminal response. Delivery is in-memory, not durable or exactly-once. + +`NegotiationTerms` uses finite `Decimal` values: nonnegative price per task with a three-letter uppercase currency code; maximum latency in milliseconds; and availability percentage over a window in seconds. The bounded policy checks the receiving party's price/SLA bounds, counters with its reservation if permitted, or rejects. The caller must ensure its first offer meets its own limits. These terms record agreement only—no authentication, payment, measurement, SLA enforcement, or dispute resolution is provided. + +### Opt-in market routing + +Pass `negotiated_agreements={seller_id: accepted_session}`, `negotiation_buyer=buyer_id`, and `negotiation_requirements=buyer_terms` to `federation.run(..., strategy="market")` or `AgentSwarm.execute(...)`. In this mode only sellers with matching accepted agreements within the buyer's price/SLA bounds and market budget compete; accepted prices influence bid scoring and sealed-bid settlement estimates. Other auction types are rejected. Ordinary market routing remains unchanged when no agreements are supplied. + +The caller must verify transcript authenticity, delivery, freshness, task scope and replay policy. Agreements do not prove identity or enforce payment or SLA fulfillment; the market's float estimates may be rounded, and reported actual cost may differ from the estimate. --- diff --git a/docs/agents/mcp-tool-scanning.md b/docs/agents/mcp-tool-scanning.md new file mode 100644 index 000000000..153a5d97f --- /dev/null +++ b/docs/agents/mcp-tool-scanning.md @@ -0,0 +1,68 @@ +--- +sidebar_position: 7 +title: "MCP tool scanning — SynapseKit Agents" +--- + +# MCP tool-definition scanning + +MCP servers supply tool names, descriptions and schemas at runtime. The `MCPClient` scanner applies deterministic local heuristics to effective descriptions and every input-schema string key and value, including nested property descriptions and defaults. It runs without a model call and is **off by default**. Each string is scanned separately, so patterns split across fields may be missed. + +## Enable the registration gate + +```python +from synapsekit.mcp import MCPClient, ToolScanBlockedError +from synapsekit.mcp.pinning import ToolApprovalRequiredError, ToolDriftDetectedError + +client = MCPClient( + block_on_high_severity=True, + server_id="catalog-prod", + pin_store_path="tool-pins.json", +) +try: + tools = await client.connect_stdio("example-mcp-server") +except ToolScanBlockedError as exc: + for finding in exc.report.findings: + print(finding.tool_name, finding.severity, finding.rule) +except (ToolApprovalRequiredError, ToolDriftDetectedError) as exc: + # Review the current definitions and findings before explicitly approving. + print(client.last_scan_report) + # After human review: tools = await client.approve_current_tools() +``` + +`server_id` and `pin_store_path` are required together when pinning is enabled. The scanner gate works with or without pinning. High-severity findings block registration and do not overwrite saved pins. Medium findings are reported but do not block. The gate scans the definitions it will register and re-scans the newly fetched definitions on approval. A scan rejection during initial connection closes the session/transport; an approval or drift exception retains it so the caller can inspect and resolve the review flow. Use `await client.close()` when finished. + +## Standalone reports + +```python +from synapsekit.mcp import scan_tools +from synapsekit.mcp.pinning import make_tool_definition + +snapshot = make_tool_definition( + "lookup", + "Search public records", + {"type": "object", "properties": {}}, +) +report = await scan_tools([snapshot]) +for finding in report.findings: + print(finding.tool_name, finding.fingerprint, finding.severity, finding.rule) +``` + +Findings include tool name, original definition fingerprint, severity, rule ID and a short explanation; description text is not copied into the report. If a description is missing or empty, the scanner checks the adapter's effective fallback text (`MCP tool: {name}`). Tool names come from the server; escape them before logging or terminal output. + +Rules flag patterns associated with instruction overrides, concealment, system/developer role spoofing, possible secret exfiltration, remote shell-script execution, and invisible/bidirectional characters. These are narrow heuristics, not a comprehensive scanner. A clean report does not prove the server or tool is safe. + +## Resource limits and security boundaries + +```python +from synapsekit.mcp import ToolScanLimitError, scan_tools + +try: + await scan_tools(oversized_or_untrusted_tool_set) +except ToolScanLimitError: + # Reject input as a whole; scan_tools never returns a partial report. + raise +``` + +The gate accepts at most 256 tools, 16,384 Unicode characters per description or individual schema string, and 262,144 combined description and schema characters. It also limits schema traversal to 16,384 nodes and depth 64, bounds tool names separately, and rejects invalid JSON-like values. Exceeding a limit raises `ToolScanLimitError` and fails closed; no partial report is returned. Normalization and pattern matching run in a worker thread, while pre-snapshot validation runs on the event loop. Limits do not bound the transport response before the MCP SDK decodes it. + +The scanner examines effective descriptions and input-schema strings, not manifests, server code, tool outputs, transport behavior, or names when a nonempty description is present. It may miss encoded, paraphrased, or cross-field attacks. A server can change behavior without changing its definition or fingerprint. Pinning detects definition changes; it does not prove safety or enforce server-side behavior. Review the server, restrict its permissions and network access, isolate credentials, and monitor tool calls. Calls already in flight are not cancelled when a generation is revoked. diff --git a/docs/agents/mcp.md b/docs/agents/mcp.md index f4570a134..297b16397 100644 --- a/docs/agents/mcp.md +++ b/docs/agents/mcp.md @@ -8,7 +8,7 @@ SynapseKit supports the [Model Context Protocol](https://modelcontextprotocol.io ## MCPClient -Connect to an MCP server to discover and call remote tools. +Connect to an MCP server. `connect_stdio()` and `connect_sse()` return a list of ready-to-use `BaseTool` adapters. `MCPClient` does not expose public `list_tools()` or `call_tool()` methods; pass the returned tools to an agent, as in the example below. ### Stdio transport @@ -16,47 +16,66 @@ Connect to an MCP server to discover and call remote tools. from synapsekit import MCPClient client = MCPClient() -await client.connect_stdio("npx", ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]) - -# List available tools -tools = await client.list_tools() -for t in tools: - print(t.name, t.description) +tools = await client.connect_stdio( + "npx", ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"] +) +for tool in tools: + print(tool.name, tool.description) -# Call a tool -result = await client.call_tool("read_file", {"path": "/tmp/hello.txt"}) -print(result) +await client.close() ``` ### SSE transport ```python client = MCPClient() -await client.connect_sse("http://localhost:8080/sse") +tools = await client.connect_sse("http://localhost:8080/sse") +for tool in tools: + print(tool.name, tool.description) -tools = await client.list_tools() -result = await client.call_tool("search", {"query": "hello"}) +await client.close() ``` ## MCPToolAdapter -Wrap MCP tools as `BaseTool` instances so they work with any SynapseKit agent: +`connect_stdio()` and `connect_sse()` create `MCPToolAdapter` instances for every server tool and return them as `BaseTool` values. Use those returned adapters directly; there is no `MCPToolAdapter.from_client()` factory. ```python -from synapsekit import MCPClient, MCPToolAdapter, FunctionCallingAgent +from synapsekit import FunctionCallingAgent, MCPClient, MCPToolAdapter -client = MCPClient() -await client.connect_stdio("npx", ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]) +async with MCPClient() as client: + tools = await client.connect_stdio( + "npx", ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"] + ) + assert all(isinstance(tool, MCPToolAdapter) for tool in tools) + + agent = FunctionCallingAgent(llm=llm, tools=tools) + result = await agent.run("List files in /tmp") + print(result) +``` -# Wrap all MCP tools as BaseTool instances -tools = await MCPToolAdapter.from_client(client) +Each wrapped tool preserves the server-provided name, description, and parameter schema. The adapter handles serialization and deserialization automatically. Keep the client connected while the agent uses its tools; leaving the `async with` block closes the session. -# Use with any agent -agent = FunctionCallingAgent(llm=llm, tools=tools) -result = await agent.run("List files in /tmp") +## Tool-description scanning and pinning + +MCP tool descriptions come from an external server. `MCPClient` can apply a local heuristic scanner before registering tools: + +```python +from synapsekit.mcp import MCPClient, ToolScanBlockedError + +client = MCPClient(block_on_high_severity=True) # opt-in; default is False +try: + tools = await client.connect_stdio("example-mcp-server") +except ToolScanBlockedError as exc: + for finding in exc.report.findings: + print(finding.tool_name, finding.severity, finding.rule) ``` -Each wrapped tool preserves the original name, description, and parameter schema from the MCP server. The adapter handles serialization and deserialization automatically. +The scanner reports patterns associated with instruction overrides, role spoofing, concealment, secret transfer, remote script execution, and hidden characters. High-severity findings block the whole registration; medium findings are reported but do not block. When enabled, the scanner also checks the exact definitions again during approval and blocks registration before writing pins. A blocked initial connection is closed. `ToolApprovalRequiredError` and `ToolDriftDetectedError` retain the connection for review; inspect the pending definitions and `client.last_scan_report` before calling `approve_current_tools()`. + +For persistent definition pins, configure both `server_id` and `pin_store_path`; pins detect changes but do not determine whether a definition is malicious. The scan covers effective descriptions and input-schema string keys and values, including nested descriptions. It limits tools, text size, schema nodes and depth. Limit violations fail closed. Pattern matching runs off the event loop, but limits do not bound the MCP transport response before decoding. + +This is heuristic analysis of tool text—not a full manifest, server-code, or runtime audit. A clean scan or matching pin does not prove safety, and server behavior can change without its definition changing. Review the server, restrict its permissions and network access, isolate credentials, and monitor calls. See [scanner behavior and limitations](./mcp-tool-scanning) for rule details. ## MCPServer diff --git a/docs/api/evaluation.md b/docs/api/evaluation.md index e771e6b51..ca3a77c26 100644 --- a/docs/api/evaluation.md +++ b/docs/api/evaluation.md @@ -226,6 +226,12 @@ sk eval --tag rag --threshold 0.8 --- +## Evaluation helpers + +The API also exports `RulerGroup`, `RulerTrajectory`, `RulerScorer`, and `LLMRulerJudge` for relative scoring of same-task rollout groups; see [Relative trajectory rewards](../evaluation/ruler-rewards). Calibration utilities include the diagnostic `calibrate()` report and the opt-in `fit_calibration()` isotonic model. A scorer test fixture is not evidence of real-model performance. + +For provider-free multi-turn testing, `SimulationHarness`, `BookingEnvironment`, `BookingAction`, and `Reward` are exported here. See [Seeded user simulation](../evaluation/simulation) for shared-state episodes and policy-based rewards. + ## See also - [Evaluation overview](../evaluation/overview) diff --git a/docs/cookbook/agent-patterns.md b/docs/cookbook/agent-patterns.md index b77464bca..e42df7863 100644 --- a/docs/cookbook/agent-patterns.md +++ b/docs/cookbook/agent-patterns.md @@ -326,25 +326,37 @@ print(result.output) Connect your agent to an external tool server using the Model Context Protocol. ```python +import asyncio +import os + from synapsekit.agents import FunctionCallingAgent -from synapsekit.agents.mcp import MCPClient -from synapsekit.llms.anthropic import AnthropicLLM +from synapsekit.llm.openai import OpenAILLM +from synapsekit.llm.base import LLMConfig +from synapsekit.mcp import MCPClient + + +async def main(): + llm = OpenAILLM( + LLMConfig( + model="gpt-5.4-mini", + api_key=os.environ["OPENAI_API_KEY"], + provider="openai", + ) + ) -# Connect to a local or remote MCP server -mcp = MCPClient(server_url="http://localhost:3000/mcp") -await mcp.connect() + # Start an SSE MCP server at this address. + async with MCPClient() as mcp: + tools = await mcp.connect_sse("http://localhost:8080/sse") + agent = FunctionCallingAgent( + llm=llm, + tools=tools, + max_iterations=10, + ) + result = await agent.run("List all open GitHub issues labeled 'bug'") + print(result) -tools = await mcp.list_tools() # discover available tools -agent = FunctionCallingAgent( - llm=AnthropicLLM(model="claude-3-5-sonnet-20241022"), - tools=tools, - max_steps=10, -) - -result = await agent.run("List all open GitHub issues labeled 'bug'") -print(result.output) -await mcp.disconnect() +asyncio.run(main()) ``` --- diff --git a/docs/evaluation/ruler-rewards.md b/docs/evaluation/ruler-rewards.md new file mode 100644 index 000000000..f3bacc02e --- /dev/null +++ b/docs/evaluation/ruler-rewards.md @@ -0,0 +1,64 @@ +--- +sidebar_position: 3 +title: "Relative trajectory rewards — SynapseKit Evaluation" +--- + +# Relative trajectory rewards + +`RulerScorer` compares several rollouts for the same task in one judge call. It returns one validated 0–1 score per trajectory. The API is RULER-style, inspired by [OpenPipe RULER](https://art.openpipe.ai/fundamentals/ruler/); it does not implement ART's API or guarantee training improvements. + +## Score a group + +```python +from synapsekit.evaluation import ( + LLMRulerJudge, + RulerGroup, + RulerMessage, + RulerScorer, + RulerTrajectory, +) + +# llm is a configured async synapsekit BaseLLM instance. +shared = RulerMessage("user", "Explain 2 + 2.") +group = RulerGroup( + task="Answer accurately and explain briefly", + trajectories=( + RulerTrajectory("attempt-1", (shared, RulerMessage("assistant", "4: two pairs."))), + RulerTrajectory("attempt-2", (shared, RulerMessage("assistant", "5"))), + ), +) +scores = await RulerScorer(LLMRulerJudge(llm)).score(group) +for score in scores: + print(score.id, score.score) +``` + +A group contains 2–16 unique trajectory IDs from one task. Messages are immutable `RulerMessage` values with `system`, `user`, `assistant`, or `tool` roles. Limits are 100 messages per trajectory, 20,000 characters per task or message, 128 characters per ID, and 200,000 total task-plus-message characters per group. The shared leading message prefix is sent once; distinct suffixes and IDs are preserved. These are character limits, not model token limits; the provider context limit may be lower. + +`LLMRulerJudge` uses the existing async `BaseLLM.generate` interface. A custom async judge callable can be injected for tests or other judge providers. The response must contain exactly one finite numeric score in [0, 1] for every trajectory ID; missing, duplicate, unknown or malformed entries raise `ValueError`. Provider errors propagate; no score is fabricated on failure. + +Task and trajectory contents are untrusted input. The prompt labels them as data, but that is not a security boundary—an LLM judge may still follow instructions embedded in a rollout. Do not send secrets or sensitive traces to a provider without authorization. Validate the judge on adversarial examples before relying on the score. + +## Diagnose and fit calibration + +`calibrate(scores, gold)` reports mean absolute error and pairwise accuracy against a matching labeled set. Ties in gold are excluded; a predicted tie on a non-tied gold pair counts as incorrect. This function is diagnostic, not a fitted transform. + +For an optional isotonic transform, fit on one labeled calibration split and measure on independent held-out tasks: + +```python +from synapsekit.evaluation import calibrate, fit_calibration + +calibration = fit_calibration(calibration_scores, calibration_gold) +calibrated = calibration.apply(held_out_scores) +report = calibrate(calibrated, held_out_gold) +print(calibration.metadata, report) +``` + +A fitted transform can overfit small samples and does not turn relative scores into calibrated probabilities or guarantee comparability across task groups. Data-split independence, label quality, repeated-run variability and model/prompt versioning are caller responsibilities. + +## Ablation and evidence + +The repository's `benchmarks/ruler_ablation.py` has a deterministic offline fixture with manually supplied scores. It exercises the scorer and baseline wiring only; its result is **not** evidence that an LLM judge beats a handcrafted reward. + +An opt-in `--real` mode runs one labeled group with a pinned OpenAI model and requires an API key. It may incur charges and sends the task and rollouts to the provider. Only run it with explicit authorization and suitable data. A meaningful conclusion requires representative groups, separate calibration and held-out tasks, repeated runs, a strong baseline, model/prompt metadata, uncertainty, and costs. No real-model performance or training benefit is claimed by the offline fixture. + +See [Evaluation API Reference](../api/evaluation) and [Evaluation overview](./overview). diff --git a/docs/evaluation/simulation.md b/docs/evaluation/simulation.md new file mode 100644 index 000000000..0c47e7ff9 --- /dev/null +++ b/docs/evaluation/simulation.md @@ -0,0 +1,57 @@ +--- +sidebar_position: 4 +title: "Seeded user simulation — SynapseKit Evaluation" +--- + +# Seeded multi-turn user simulation + +`SimulationHarness` exercises an async user policy and an async agent against the same mutable environment. It is provider-free by default: the harness does not call a model or network service unless a callback does so. + +## Run a booking episode + +```python +import asyncio +import random + +from synapsekit.evaluation import ( + BookingAction, + BookingEnvironment, + BookingObservation, + SimulationHarness, +) + +async def simulated_user(obs: BookingObservation, rng: random.Random) -> BookingAction: + if obs.requested_slot is None: + return BookingAction("request", slot=rng.choice(obs.available_slots)) + if not obs.consented: + return BookingAction("consent") + return BookingAction("wait") + +async def support_agent(obs: BookingObservation, rng: random.Random) -> BookingAction: + if not obs.consented: + return BookingAction("message", message="May I book this support appointment?") + if obs.booked_slot is None: + return BookingAction("book", slot=obs.requested_slot) + return BookingAction("finish", message="Your appointment is booked.") + +async def main() -> None: + harness = SimulationHarness(BookingEnvironment(), simulated_user, support_agent) + result = await harness.run(seed=19) + print(result.reason, result.reward.value, result.reward.violations) + +asyncio.run(main()) +``` + +The user can request a slot, consent, cancel or wait; the agent can message, book, finish or wait. Both receive observations of the shared booking state. Reward is calculated from recorded actions and final state: the booking policy returns 1.0 only for a completed, consented matching booking with no violations. The agent cannot set its own score by claiming success. + +## Harness contract + +- `SimulationHarness(environment, user, agent, *, max_turns=20, error_policy="raise")` alternates from the user. `max_turns` counts individual actions by either participant. +- `await harness.run(seed=...)` calls `environment.reset(seed)` before the episode and supplies separate deterministic `random.Random` streams to the two callbacks. +- An environment implements async `reset(seed)`, `observe(actor)`, `apply(actor, action) -> bool`, and `reward() -> Reward`. Return `True` from `apply` when the episode is complete. +- `InvalidActionError` propagates by default. With `error_policy="terminate"`, the invalid action is recorded and the episode ends with reason `invalid_action`; the environment still supplies the reward. +- Observations and actions are deep-copied for the recorded transcript before being passed to callbacks or `apply`, so mutation by an actor or environment does not rewrite prior turns. Values must support independent `copy.deepcopy`; copy errors propagate. + +A seed alone does not guarantee reproducibility if callbacks use unseeded randomness, external state, or nondeterministic services. Reusing a harness resets its environment but not mutable state retained by callbacks. Create separate environments and actors for concurrent runs; the harness does not serialize concurrent episodes. The booking domain is an in-memory example, not a production scheduler or a security boundary. + +Run the runnable example from a SynapseKit source checkout with `PYTHONPATH=src python examples/user_simulation.py`. Its deterministic transcript should end with `reason=completed`, reward `1.0`, and no violations. See [Evaluation API Reference](../api/evaluation). diff --git a/docs/llms/deliberation.md b/docs/llms/deliberation.md new file mode 100644 index 000000000..47b726366 --- /dev/null +++ b/docs/llms/deliberation.md @@ -0,0 +1,49 @@ +--- +sidebar_position: 41 +title: "Parallel deliberation — SynapseKit LLMs" +--- + +# Parallel-N deliberation + +`deliberate` asks a bounded adapter for N independent short answers, then aggregates exact, whitespace-trimmed answer matches using model-reported confidence as vote weight. Confidence is not a calibrated probability. Different wording is treated as a different answer. + +## OpenAI adapter example + +```python +from openai import AsyncOpenAI +from synapsekit.llm import OpenAIChatAdapter, deliberate + +client = AsyncOpenAI(max_retries=0) +adapter = OpenAIChatAdapter(client, model="YOUR_SUPPORTED_MODEL") +try: + result = await deliberate( + adapter, + "What is 2 + 2?", + n=3, + max_output_tokens=128, + total_output_budget=384, + early_exit_confidence=0.9, + ) + print(result.answer, result.confidence) + print(result.total_input_tokens, result.total_output_tokens, result.total_cost) +finally: + await client.close() +``` + +Use only a model/provider that honors `max_completion_tokens` for all generated output, including reasoning. The cap is enforced by the adapter at the request; the orchestrator rejects output reported above the cap. It reserves `n * max_output_tokens` before launch, so early exit does not make an undersized budget acceptable. This is an output-token cap, not a total input-token or monetary budget. + +The adapter can calculate a cost estimate from caller-supplied input/output per-token rates. The estimate is not an invoice and may omit cached-input discounts, fees or provider-specific pricing. Any unknown usage makes the corresponding total `None`, not zero. Cancellation cannot ensure that a remote provider stopped billing. + +## Early exit and limitations + +When enabled, early exit requires two matching answers above the confidence threshold and a strict weighted-score lead that no pending vote (at maximum confidence 1.0) can overturn. This is a bound over the requested votes, not a correctness guarantee. All tasks in the observed completion batch are included before the decision. Outstanding tasks are cancelled and drained; an adapter that suppresses cancellation can delay cleanup indefinitely. + +Each adapter must implement `complete(prompt, *, max_output_tokens)` and return a `Completion` with per-request usage where available. Do not wrap arbitrary `BaseLLM.generate` implementations as bounded adapters unless the provider honors the cap and usage is accurately per request. Retries must be disabled or fully accounted for. + +## Evaluation + +The repository provides `benchmarks/deliberation_eval.py`, a paired comparison harness for the pinned short-answer fixture and a separately prompted, bounded reasoning baseline. It uses the same tasks and exact-answer scoring. Configuration and fixture entries are validated before loading an adapter factory or making requests. Early exit is disabled by default; `--early-exit-confidence 0.9` enables its evaluation and reports launched and cancelled traces. Cancellation does not establish provider-side savings, and unknown usage remains unknown. + +No real-model quality or cost improvement has been verified; mock-adapter tests demonstrate orchestration, not efficacy. A real run may incur charges and share prompts with the configured provider, so use explicit authorization and non-sensitive tasks. + +See [LLM Overview](./overview) and [LLM configuration API](../api/llm). diff --git a/docs/llms/overview.md b/docs/llms/overview.md index 6036b89b2..62c8a4ca6 100644 --- a/docs/llms/overview.md +++ b/docs/llms/overview.md @@ -156,5 +156,6 @@ The `TokenTracer` in `RAGPipeline` aggregates this across all calls. - [vLLM](./vllm) — high-throughput self-hosted inference via vLLM's OpenAI-compatible API - [Replicate](./replicate) — hosted open models (Llama, Mistral, SDXL, etc.) via the Replicate REST API - [Caching & Retries](./caching-retries) — LRU caching, exponential backoff, rate limiting +- [Parallel deliberation](./deliberation) — bounded parallel-N answer aggregation with model confidence and early exit - [CostRouter & FallbackChain](./cost-router) — route to cheapest model or cascade on failure - [Cost Tracker](../observability/cost-tracker) — attribute and budget LLM spending diff --git a/docs/patterns/agent-patterns.md b/docs/patterns/agent-patterns.md index e9d33b9ef..4e966a3a0 100644 --- a/docs/patterns/agent-patterns.md +++ b/docs/patterns/agent-patterns.md @@ -326,25 +326,37 @@ print(result.output) Connect your agent to an external tool server using the Model Context Protocol. ```python +import asyncio +import os + from synapsekit.agents import FunctionCallingAgent -from synapsekit.agents.mcp import MCPClient -from synapsekit.llms.anthropic import AnthropicLLM +from synapsekit.llm.openai import OpenAILLM +from synapsekit.llm.base import LLMConfig +from synapsekit.mcp import MCPClient + + +async def main(): + llm = OpenAILLM( + LLMConfig( + model="gpt-5.4-mini", + api_key=os.environ["OPENAI_API_KEY"], + provider="openai", + ) + ) -# Connect to a local or remote MCP server -mcp = MCPClient(server_url="http://localhost:3000/mcp") -await mcp.connect() + # Start an SSE MCP server at this address. + async with MCPClient() as mcp: + tools = await mcp.connect_sse("http://localhost:8080/sse") + agent = FunctionCallingAgent( + llm=llm, + tools=tools, + max_iterations=10, + ) + result = await agent.run("List all open GitHub issues labeled 'bug'") + print(result) -tools = await mcp.list_tools() # discover available tools -agent = FunctionCallingAgent( - llm=AnthropicLLM(model="claude-3-5-sonnet-20241022"), - tools=tools, - max_steps=10, -) - -result = await agent.run("List all open GitHub issues labeled 'bug'") -print(result.output) -await mcp.disconnect() +asyncio.run(main()) ``` --- diff --git a/sidebars.ts b/sidebars.ts index 57cef7470..48164d7bc 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -190,6 +190,7 @@ const sidebars: SidebarsConfig = { 'llms/vllm', 'llms/replicate', 'llms/caching-retries', + 'llms/deliberation', 'llms/cost-router', ], }, @@ -209,6 +210,7 @@ const sidebars: SidebarsConfig = { 'agents/tools', 'agents/executor', 'agents/mcp', + 'agents/mcp-tool-scanning', 'agents/cookbook', 'agents/tool-authoring', 'agents/streaming-steps', @@ -234,7 +236,7 @@ const sidebars: SidebarsConfig = { type: 'category', label: 'Evaluation', link: { type: 'doc', id: 'evaluation/index' }, - items: ['evaluation/overview', 'evaluation/rag-evaluator'], + items: ['evaluation/overview', 'evaluation/rag-evaluator', 'evaluation/ruler-rewards', 'evaluation/simulation'], }, { type: 'category',