convez.ai
Skill
zrui9861-dev

dual-agent-sdk

zrui9861-dev/dual-agent-sdk

Ver no GitHub
BomPluginScore · de 0 a 100

Two AIs, one writes, one reviews — they debate until they agree. No infinite loops. Python/TS SDK + one-command Claude Code skill.

Instalação

$npx convez-ai zrui9861-dev/dual-agent-sdk

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
1
Forks
0
Acompanhando
0
Saúde
85%
Último commit
há 5 meses
Versão
v1.1.0
Issues abertas
0
Contribuidores
1

README

A tradução para o português deste README ainda está na fila.

Dual Agent SDK


⚡ One-Command Install

macOS / Linux

curl -fsSL https://raw.githubusercontent.com/zrui9861-dev/dual-agent-sdk/main/install.sh | bash

Windows (PowerShell)

Invoke-WebRequest -Uri https://raw.githubusercontent.com/zrui9861-dev/dual-agent-sdk/main/install.ps1 | Invoke-Expression

That's it. Then set your API key and start using:

export DEEPSEEK_API_KEY="sk-..."   # pick your provider
/dual-review "你的任务"                     # self-review (free)
/dual-review --dual "审查这份代码"           # dual-model
/dual-review --dual --discuss "架构设计"    # discussion
ModeCommandSetupBest for
Self-review/dual-reviewNoneDaily work
Dual-model--dualAPI keyImportant output
Discussion--dual --discussAPI keyArchitecture, security

Supported second models: DeepSeek, Qwen, Moonshot, GLM, OpenAI, Anthropic — any OpenAI-compatible API.

What it looks like

/dual-review --dual --discuss "设计 API 限流方案"

💬 R1 Generate → [Claude 方案]
🔍 R1 Critique [DeepSeek] → 2 disputes, Score 0.55

💬 R2 Discuss
| 令牌桶vs滑动窗口 | 🤝 达成共识 |
| 分布式一致性     | 🔴 仍有分歧 |

💬 R3 Discuss
| 分布式一致性 | ✅ 解决 (10%超限+熔断) |

✅ Converged — Agreement 0.40→0.85

📦 SDK — For Building Your Own Agents

Single-agent AI systems have fundamental weaknesses that make them unreliable for production workloads:

ProblemReal-World Impact
Hallucinations — no second pair of eyesIncorrect code, fabricated facts, broken logic
No self-correction — models rarely catch their own mistakesBugs and vulnerabilities ship to production
Infinite loops — agents debate without convergingWasted tokens, hung pipelines, timeout failures

Dual Agent SDK solves all three with a Generator-Critic pattern backed by a 6-layer anti-loop convergence protocol. One agent creates. Another reviews. A structured orchestrator guarantees the loop terminates -- every time.

flowchart TD
    U[User Task] --> G[Generator Agent]
    G --> A[Artifact + Reasoning]
    A --> C[Critic Agent]
    C --> V[Verdict with Issues]
    V --> O{Orchestrator<br/>6-Layer Check}
    O -->|L1: Max Rounds| ACCEPT
    O -->|L2: Quality ≥ Threshold| ACCEPT
    O -->|L3: Score Converged| ACCEPT
    O -->|L4: Issues Decaying| ACCEPT
    O -->|L5: Diminishing ROI| ACCEPT
    O -->|L6: Semantic Loop?| ESCALATE
    ESCALATE --> M[Meta-Judge Resolution]
    O -->|Continue| G
    ACCEPT --> R[Final Verified Output]
    M --> R

Features

🧠 Generator-Critic PatternOne model creates with structured reasoning; another rigorously reviews with severity-ranked issues
🛡️ 6-Layer Anti-Loop ProtocolChain of Responsibility pattern. Each layer checks for convergence independently. Guaranteed termination
🔌 Multi-Provider ReadyAnthropic and OpenAI adapters built-in. Bring your own adapter with a 3-method interface
📊 Structured OutputPydantic models (Python) and Zod schemas (TypeScript) validate every agent response
🌐 Dual EcosystemFirst-class Python and TypeScript packages with identical APIs and behavior
⚖️ Escalation ProtocolSemantic loop detection triggers a meta-judge to resolve deadlocks with a final binding decision
📈 ObservableFull round-by-round audit trail: artifacts, verdicts, issues, confidence scores, and convergence decisions

Quick Start

Python

pip install dual-agent-sdk
import asyncio
from dual_agent_sdk import (
    DualAgentOrchestrator,
    AnthropicAdapter,
    OpenAIAdapter,
    AgentConfig,
)

async def main():
    orchestrator = DualAgentOrchestrator(
        generator=AnthropicAdapter(model="claude-sonnet-4-6"),
        critic=OpenAIAdapter(model="gpt-4o"),
    )

    result = await orchestrator.run(
        "Write a secure authentication middleware for FastAPI with JWT verification"
    )

    print(f"✅ Final result (confidence: {result.confidence:.2f})")
    print(f"   Rounds: {len(result.rounds)}")
    print(f"   Decision: {result.decision}")
    print(f"\n{result.content}")

asyncio.run(main())

TypeScript

npm install dual-agent-sdk
import {
  DualAgentOrchestrator,
  AnthropicAdapter,
  OpenAIAdapter,
} from 'dual-agent-sdk';

async function main() {
  const orchestrator = new DualAgentOrchestrator(
    new AnthropicAdapter({ model: 'claude-sonnet-4-6' }),
    new OpenAIAdapter({ model: 'gpt-4o' }),
  );

  const result = await orchestrator.run(
    'Write a secure authentication middleware for Express with JWT verification',
  );

  console.log(`✅ Final result (confidence: ${result.confidence.toFixed(2)})`);
  console.log(`   Rounds: ${result.rounds.length}`);
  console.log(`   Decision: ${result.decision}`);
  console.log(`\n${result.content}`);
}

main();

How It Works

Each collaboration round follows a disciplined, fully-observable pipeline:

  1. Generate -- The Generator agent produces an Artifact containing the solution, a confidence score, and explicit reasoning.
  2. Critique -- The Critic agent reviews the artifact and returns a Verdict with issues ranked by severity (critical, major, minor, style).
  3. Converge -- The Orchestrator runs the verdict through six sequential checks (Chain of Responsibility):
    • L1 -- Hard Ceiling: Have we exceeded max_rounds? If so, accept the best artifact so far.
    • L2 -- Quality Threshold: Does the confidence score meet or exceed quality_threshold? If so, accept.
    • L3 -- Score Convergence: Is the score delta between rounds below convergence_threshold? If so, accept -- we are no longer meaningfully improving.
    • L4 -- Severity Decay: Are critical and major issues trending to zero? If so, accept.
    • L5 -- Diminishing ROI: Is this round's improvement less than 1/roi_decay_factor of the previous? If so, accept -- further rounds cost more than they are worth.
    • L6 -- Semantic Loop Detection: Are the last two artifacts semantically nearly identical (cosine similarity > loop_similarity_threshold)? If so, escalate to the meta-judge.
  4. Resolve -- The Orchestrator either accepts the artifact, continues with filtered feedback sent back to the Generator, or escalates a detected deadlock to the meta-judge for a final binding decision.

Configuration

Every convergence parameter is tunable:

ParameterTypeDefaultDescription
max_roundsint5Maximum Generator-Critic round trips
quality_thresholdfloat0.85Auto-accept when confidence >= this value
convergence_thresholdfloat0.02Accept when score delta between rounds < this
roi_decay_factorfloat2.0Each round must improve at least 1/factor of the prior
loop_similarity_thresholdfloat0.92Cosine similarity above this triggers escalation
enable_escalationbooltrueEnable meta-judge resolution on detected deadlocks
# Python: custom convergence tuning
orchestrator = DualAgentOrchestrator(
    generator=gen,
    critic=crit,
    config=AgentConfig(
        max_rounds=8,
        quality_threshold=0.90,
        convergence_threshold=0.01,
    ),
)
// TypeScript: custom convergence tuning
const orchestrator = new DualAgentOrchestrator(gen, crit, {
  maxRounds: 8,
  qualityThreshold: 0.9,
  convergenceThreshold: 0.01,
});

Bringing Your Own Adapter

The adapter interface is intentionally minimal. Implement three methods and you can orchestrate any LLM:

# Python
class MyAdapter(BaseAdapter):
    async def generate(self, prompt: str, system_prompt: str) -> str: ...
    def get_model_name(self) -> str: ...
    def get_provider_name(self) -> str: ...
// TypeScript
class MyAdapter extends BaseAdapter {
  async generate(prompt: string, systemPrompt: string): Promise<string> { ... }
  getModelName(): string { ... }
  getProviderName(): string { ... }
}

See the Custom Adapters guide for full examples with error handling, retries, and structured output support.

Project Structure

dual-agent-sdk/
├── python/                    # Python package
│   ├── src/dual_agent_sdk/
│   │   ├── __init__.py        # Public API exports
│   │   ├── orchestrator.py    # DualAgentOrchestrator
│   │   ├── convergence.py     # 6-layer ConvergenceEngine
│   │   ├── loop_detector.py   # SemanticLoopDetector
│   │   ├── models.py          # Pydantic models
│   │   ├── adapters/          # Anthropic, OpenAI, Base
│   │   └── prompts/           # System prompt templates
│   ├── tests/
│   └── pyproject.toml
├── typescript/                # TypeScript package
│   ├── src/
│   │   ├── index.ts           # Public API exports
│   │   ├── orchestrator.ts    # DualAgentOrchestrator
│   │   ├── convergence.ts     # 6-layer ConvergenceEngine
│   │   ├── loop-detector.ts   # SemanticLoopDetector
│   │   ├── models.ts          # Zod schemas + types
│   │   ├── adapters/          # Anthropic, OpenAI, Base
│   │   └── prompts/           # System prompt templates
│   ├── tests/
│   └── package.json
├── docs/
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
└── LICENSE

Documentation

DocumentDescription
Getting StartedInstallation, first run, basic configuration
ArchitectureDeep dive into the Generator-Critic pattern and component design
API ReferenceFull API docs for orchestrator, convergence engine, adapters, and models
Convergence ProtocolDetailed explanation of the 6-layer anti-loop protocol
Custom AdaptersHow to build and register custom LLM adapters

Contributing

We welcome contributions! Dual Agent SDK is built for the community.

All contributors are expected to follow our Code of Conduct.

License

MIT © 2026 Dual Agent SDK Contributors -- see LICENSE for full text.

Ver o original no GitHub

Bom para

Relacionados