A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
feat: add AI Debate Agent using LangGraph, Orq.ai and Gradio
Tiioluwani4cb39cd09a41
diff --git a/ai_agents/ai_debate_agent/.env.example b/ai_agents/ai_debate_agent/.env.examplenew file mode 100644index 0000000..f494813--- /dev/null+++ b/ai_agents/ai_debate_agent/.env.example@@ -0,0 +1,17 @@+# All three agents are routed through the Orq.ai OpenAI-compatible router.+# Get a key at https://orq.ai/+ORQ_API_KEY=your-orq-api-key-here++# ---- Optional model overrides (sensible defaults are used if unset) ----++# Debater A (For)+# DEBATER_A_MODEL=google-ai/gemini-3-flash-preview++# Debater B (Against)+# DEBATER_B_MODEL=mistral/mistral-small-latest++# Judge+# JUDGE_MODEL=moonshotai/kimi-k2.6++# Temperature for all Orq chat calls (some models only allow 1)+# ORQ_TEMPERATURE=1diff --git a/ai_agents/ai_debate_agent/README.md b/ai_agents/ai_debate_agent/README.mdnew file mode 100644index 0000000..3636244--- /dev/null+++ b/ai_agents/ai_debate_agent/README.md@@ -0,0 +1,184 @@+# AI Debate Agent++> Two LLM debaters argue opposing sides of any topic you choose; a judge scores every turn and declares a winner.++## Overview++AI Debate Agent is a multi-agent application that runs structured debates between two language models and an impartial judge. You supply a topic and round count (1 to 5); Debater A argues for, Debater B argues against, and they alternate while responding to each other's latest points. When rounds finish, a judge reviews the full transcript, scores each argument on logic, evidence, and persuasiveness, and returns a winner with a written verdict. The Gradio interface streams the transcript live as each agent speaks.++## Demo++++## Features++- **Dual debaters** with fixed roles: Debater A (For) and Debater B (Against)+- **Configurable rounds** from 1 to 5, with each round consisting of one turn per debater+- **Context-aware rebuttals** where each debater sees the full transcript before speaking+- **Impartial judge** that scores every argument and declares a winner with reasoning+- **Live streaming UI** that updates the transcript and status after each agent turn+- **Single API key** for all models via the [Orq.ai](https://orq.ai/) router+- **Optional connectivity test** (`test_orq.py`) to verify models before launching the app++## Tech Stack++**Frameworks & Libraries:**++- [LangGraph](https://langchain-ai.github.io/langgraph/) for multi-agent orchestration+- [LangChain Core](https://python.langchain.com/) for graph state typing+- [OpenAI Python SDK](https://github.com/openai/openai-python) (Orq.ai-compatible client)+- [Gradio](https://www.gradio.app/) for the web UI+- [python-dotenv](https://github.com/theskumar/python-dotenv) for environment configuration++**Additional Tools:**++- **Orchestration:** LangGraph+- **Web Framework:** Gradio+- **Model routing:** [Orq.ai](https://orq.ai/) AI Router (`https://api.orq.ai/v3/router`)++| Agent | Role | Default model (Orq.ai) |+|-------|------|-------------------------|+| Debater A | For | `google-ai/gemini-3-flash-preview` |+| Debater B | Against | `mistral/mistral-small-latest` |+| Judge | Scoring and verdict | `moonshotai/kimi-k2.6` |++## Prerequisites++- Python 3.10 or higher+- API keys for:+ - **Orq.ai** (`ORQ_API_KEY`) from the [Orq.ai dashboard](https://orq.ai/)+- **Orq.ai provider setup:** In AI Router, connect the providers you use (for example Google AI, Mistral, and Moonshot AI) and add the underlying provider API keys so routed models can run.++## Installation++### 1. Clone the Repository++```bash+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git+cd Hands-On-AI-Engineering/ai_agents/ai_debate_agent+```++### 2. Create Virtual Environment (Recommended)++```bash+python -m venv venv+```++**Windows:**++```bash+venv\Scripts\activate+```++**macOS/Linux:**++```bash+source venv/bin/activate+```++### 3. Install Dependencies++```bash+pip install -r requirements.txt+```++### 4. Set Up Environment Variables++```bash+cp .env.example .env+```++Edit `.env` and set your Orq.ai API key:++```env+ORQ_API_KEY=your-orq-api-key-here+```++Optional overrides:++| Variable | Description |+|----------|-------------|+| `DEBATER_A_MODEL` | For-side model (default: `google-ai/gemini-3-flash-preview`) |+| `DEBATER_B_MODEL` | Against-side model (default: `mistral/mistral-small-latest`) |+| `JUDGE_MODEL` | Judge model (default: `moonshotai/kimi-k2.6`) |+| `ORQ_TEMPERATURE` | Sampling temperature for all agents (default: `1`; required by some models) |++Verify connectivity (optional):++```bash+py test_orq.py+```++## Usage++### Running the Application++```bash+gradio app.py+```++You can also run:++```bash+python app.py+```++Open the local URL shown in the terminal (typically `http://127.0.0.1:7860`). Enter a debate topic, select the number of rounds (1 to 5), and click **Start Debate**.++### Example Usage++| Debate topic | Rounds | What you get |+|--------------|--------|--------------|+| Social media does more harm than good | 3 | Alternating For/Against arguments across 3 rounds, then a judge verdict with per-argument scores and a declared winner |+| Remote work is better than working in an office | 2 | Two rounds of rebuttals, streamed transcript, and a scored breakdown (logic, evidence, persuasiveness) |+| Artificial intelligence should be heavily regulated | 3 | Full debate transcript with live updates, total scores per debater, and written judge reasoning |+| Space exploration is worth the cost | 2 | Concise two-round debate ending in a winner (Debater A, Debater B, or Tie) and comments per argument |++**Typical output sections:**++1. **Debate transcript** (markdown): each round labeled with Debater A (For) or Debater B (Against)+2. **Judge's verdict**: score table, totals, winner, and short explanation++## Project Structure++```+ai_debate_agent/+├── app.py # Gradio UI and streaming debate handler+├── debate.py # LangGraph graph (Debater A, Debater B, Judge)+├── test_orq.py # Smoke test for Orq.ai model connectivity+├── requirements.txt # Python dependencies+├── .env.example # Environment variable template+├── .gitignore+├── README.md+└── assets/+ └── demo.png # Demo screenshot for the README+```++## How It Works++1. **Topic input**+ The user enters a topic and round count in Gradio. `debate_handler` in `app.py` calls `run_debate()` in `debate.py`.++2. **Graph setup**+ LangGraph builds a stateful graph with shared `DebateState`: topic, `max_rounds`, `round_num`, `transcript`, and `verdict`. All three agents use one Orq.ai client (`OpenAI` SDK with base URL `https://api.orq.ai/v3/router`).++3. **Debater A (For)**+ The first node calls `google-ai/gemini-3-flash-preview` with the topic and an empty transcript. The model returns the opening argument for the For side.++4. **Debater B (Against)**+ The second node calls `mistral/mistral-small-latest` with the transcript including Debater A's latest turn. It returns the Against argument and increments `round_num`.++5. **Round loop**+ A conditional edge checks `round_num <= max_rounds`. If more rounds remain, control returns to Debater A with the updated transcript. Each debater is prompted to rebut the opponent's most recent point. If rounds are complete, the graph routes to the judge.++6. **Judge**+ The judge node sends the full transcript to `moonshotai/kimi-k2.6` with a structured JSON scoring prompt. Each argument receives scores (1 to 10) for logic, evidence, and persuasiveness. The app parses the response, recomputes totals, and sets the winner and verdict text.++7. **Streaming to the UI**+ The graph runs with `stream_mode="values"`. After every node, `run_debate` yields the current state. Gradio renders the transcript and verdict panels incrementally until the debate completes.++**Graph flow:**++```+START -> debater_a -> debater_b -> (more rounds? -> debater_a : judge) -> END+```diff --git a/ai_agents/ai_debate_agent/app.py b/ai_agents/ai_debate_agent/app.pynew file mode 100644index 0000000..5024c14--- /dev/null+++ b/ai_agents/ai_debate_agent/app.py@@ -0,0 +1,180 @@+"""Gradio UI for the AI Debate Agent.++Two LLM agents argue opposing sides of a user-defined topic for a configurable+number of rounds, and a judge agent scores each argument and declares a winner.+The transcript streams in live as each agent takes its turn.+"""++from __future__ import annotations++import gradio as gr++from debate import (+ AGAINST,+ DEBATER_A,+ DEBATER_A_MODEL,+ DEBATER_B,+ DEBATER_B_MODEL,+ FOR,+ JUDGE_MODEL,+ run_debate,+)+++def _render_transcript(transcript: list[dict]) -> str:+ """Format the running transcript as markdown."""+ if not transcript:+ return "_The debate will appear here…_"+ blocks = []+ for arg in transcript:+ if arg["speaker"] == DEBATER_A:+ badge = f"🟦 **{DEBATER_A} · {FOR}**"+ else:+ badge = f"🟥 **{DEBATER_B} · {AGAINST}**"+ blocks.append(+ f"### Round {arg['round']} — {badge}\n\n{arg['content']}"+ )+ return "\n\n---\n\n".join(blocks)+++def _render_verdict(verdict: dict) -> str:+ """Format the judge's verdict as markdown."""+ if not verdict:+ return "_Awaiting the judge's verdict…_"++ totals = verdict.get("totals", {})+ a_total = totals.get(DEBATER_A, 0)+ b_total = totals.get(DEBATER_B, 0)+ winner = verdict.get("winner", "Tie")++ if winner == DEBATER_A:+ headline = f"🏆 Winner: **{DEBATER_A} ({FOR})**"+ elif winner == DEBATER_B:+ headline = f"🏆 Winner: **{DEBATER_B} ({AGAINST})**"+ else:+ headline = "🤝 Result: **Tie**"++ lines = [+ f"## ⚖️ Judge's Verdict ({JUDGE_MODEL})",+ "",+ headline,+ "",+ f"**Total scores** — {DEBATER_A} (For): `{a_total}` · {DEBATER_B} (Against): `{b_total}`",+ "",+ ]++ args = verdict.get("arguments", [])+ if args:+ lines.append("### Score breakdown")+ lines.append("")+ lines.append("| Round | Debater | Logic | Evidence | Persuasion | Notes |")+ lines.append("|:-----:|:--------|:-----:|:--------:|:----------:|:------|")+ for a in args:+ lines.append(+ f"| {a.get('round', '-')} | {a.get('speaker', '-')} "+ f"| {a.get('logic', '-')} | {a.get('evidence', '-')} "+ f"| {a.get('persuasiveness', '-')} | {a.get('comment', '')} |"+ )+ lines.append("")++ if verdict.get("verdict"):+ lines.append("### Reasoning")+ lines.append("")+ lines.append(verdict["verdict"])++ return "\n".join(lines)+++def debate_handler(topic: str, rounds: int):+ """Gradio streaming callback: yields (status, transcript_md, verdict_md)."""+ if not (topic or "").strip():+ yield "⚠️ Please enter a debate topic.", "", ""+ return++ yield "🚀 Starting debate…", "_The debate will appear here…_", ""++ try:+ for state in run_debate(topic, rounds):+ transcript = state.get("transcript", [])+ verdict = state.get("verdict", {})++ if verdict:+ status = "✅ Debate complete — verdict delivered."+ elif transcript:+ latest = transcript[-1]+ status = (+ f"🗣️ Round {latest['round']}: {latest['speaker']} "+ f"({latest['position']}) just argued…"+ )+ else:+ status = "🚀 Starting debate…"++ yield status, _render_transcript(transcript), _render_verdict(verdict)+ except Exception as exc: # surface configuration / API errors in the UI+ detail = str(exc).strip() or type(exc).__name__+ cause = exc.__cause__+ if cause and str(cause) not in detail:+ detail = f"{detail} — {cause}"+ yield f"❌ Error: {detail}", "", ""+++def build_ui() -> gr.Blocks:+ with gr.Blocks(title="AI Debate Agent") as demo:+ gr.Markdown(+ f"""+ # 🎙️ AI Debate Agent+ Two LLM agents argue opposing sides of your topic; a judge scores every+ argument and declares a winner.++ - 🟦 **Debater A — For** · `{DEBATER_A_MODEL}`+ - 🟥 **Debater B — Against** · `{DEBATER_B_MODEL}`+ - ⚖️ **Judge** · `{JUDGE_MODEL}`++ All three agents are routed through [Orq.ai](https://orq.ai/).+ """+ )++ with gr.Row():+ with gr.Column(scale=2):+ topic = gr.Textbox(+ label="Debate topic",+ placeholder="e.g. Social media does more harm than good",+ lines=2,+ )+ with gr.Column(scale=1):+ rounds = gr.Slider(+ label="Number of rounds",+ minimum=1,+ maximum=5,+ step=1,+ value=3,+ )++ run_btn = gr.Button("Start Debate", variant="primary")++ status = gr.Markdown("_Ready when you are._")++ with gr.Row():+ with gr.Column():+ gr.Markdown("## 🗣️ Debate transcript")+ transcript_out = gr.Markdown("_The debate will appear here…_")+ with gr.Column():+ gr.Markdown("## 🏆 Result")+ verdict_out = gr.Markdown("_Awaiting the judge's verdict…_")++ run_btn.click(+ fn=debate_handler,+ inputs=[topic, rounds],+ outputs=[status, transcript_out, verdict_out],+ )+ topic.submit(+ fn=debate_handler,+ inputs=[topic, rounds],+ outputs=[status, transcript_out, verdict_out],+ )++ return demo+++if __name__ == "__main__":+ build_ui().launch(theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="rose"))diff --git a/ai_agents/ai_debate_agent/assets/demo.png b/ai_agents/ai_debate_agent/assets/demo.pngnew file mode 100644index 0000000..c855fd4Binary files /dev/null and b/ai_agents/ai_debate_agent/assets/demo.png differdiff --git a/ai_agents/ai_debate_agent/debate.py b/ai_agents/ai_debate_agent/debate.pynew file mode 100644index 0000000..4b373fc--- /dev/null+++ b/ai_agents/ai_debate_agent/debate.py@@ -0,0 +1,306 @@+"""LangGraph multi-agent debate graph.++Three agents collaborate on a single graph:++* **Debater A** — argues the "for" position (gemini-3.0-flash via Orq.ai).+* **Debater B** — argues the "against" position (mistral-small-latest via Orq.ai).+* **Judge** — scores every argument and declares a winner (kimi-k2.6 via Orq.ai).++All three agents are routed through the Orq.ai OpenAI-compatible router.++The graph alternates A -> B for a configurable number of rounds, then routes to the+judge. ``run_debate`` is a generator so the UI can stream the debate as it unfolds.+"""++from __future__ import annotations++import json+import os+import re+from typing import Iterator, List, Optional, TypedDict++from dotenv import load_dotenv+from langgraph.graph import END, START, StateGraph++load_dotenv()++# Position labels used throughout the transcript and prompts.+FOR = "For"+AGAINST = "Against"+DEBATER_A = "Debater A"+DEBATER_B = "Debater B"+++class Argument(TypedDict):+ """A single turn in the debate."""++ speaker: str # "Debater A" or "Debater B"+ position: str # "For" or "Against"+ round: int+ content: str+++class DebateState(TypedDict, total=False):+ """Shared state passed between every node in the graph."""++ topic: str+ max_rounds: int+ round_num: int+ transcript: List[Argument]+ verdict: dict+++# --------------------------------------------------------------------------- #+# Model factory+# --------------------------------------------------------------------------- #+# All three agents are routed through Orq.ai via the OpenAI-compatible SDK:+# * Debater A -> google-ai/gemini-3-flash-preview+# * Debater B -> mistral/mistral-small-latest+# * Judge -> moonshotai/kimi-k2.6+DEBATER_A_MODEL = os.getenv("DEBATER_A_MODEL", "google-ai/gemini-3-flash-preview")+DEBATER_B_MODEL = os.getenv("DEBATER_B_MODEL", "mistral/mistral-small-latest")+JUDGE_MODEL = os.getenv("JUDGE_MODEL", "moonshotai/kimi-k2.6")++# Some Orq-routed models (e.g. gemini-3-flash-preview, kimi-k2.6) reject temperature != 1.+ORQ_TEMPERATURE = float(os.getenv("ORQ_TEMPERATURE", "1"))+++def _orq_client():+ """Shared Orq.ai router client used by every agent."""+ from openai import OpenAI++ api_key = os.getenv("ORQ_API_KEY")+ if not api_key:+ raise RuntimeError(+ "ORQ_API_KEY is not set. Copy .env.example to .env and add your key."+ )+ return OpenAI(+ base_url="https://api.orq.ai/v3/router",+ api_key=api_key,+ )+++# --------------------------------------------------------------------------- #+# Prompt helpers+# --------------------------------------------------------------------------- #+def _history_block(transcript: List[Argument]) -> str:+ """Render the debate so far as plain text for the next debater."""+ if not transcript:+ return "(No arguments yet — you are opening the debate.)"+ lines = []+ for arg in transcript:+ lines.append(f"[Round {arg['round']}] {arg['speaker']} ({arg['position']}):\n{arg['content']}")+ return "\n\n".join(lines)+++def _debater_system_prompt(position: str, topic: str) -> str:+ return (+ f"You are a sharp, persuasive debater arguing the **{position.upper()}** position "+ f'on the topic: "{topic}".\n'+ "Make a focused, well-structured case. Use clear logic, concrete evidence or "+ "examples, and rhetorical persuasion. Directly rebut your opponent's most recent "+ "point when one exists. Stay on your assigned side at all times. Keep each turn to "+ "roughly 120-180 words and do not break character or mention that you are an AI."+ )+++def _debater_user_prompt(position: str, round_num: int, transcript: List[Argument]) -> str:+ return (+ f"Debate so far:\n\n{_history_block(transcript)}\n\n"+ f"It is now round {round_num}. Deliver your {position} argument."+ )+++# --------------------------------------------------------------------------- #+# Graph nodes+# --------------------------------------------------------------------------- #+def _debater_a_node(state: DebateState) -> DebateState:+ client = _orq_client()+ round_num = state["round_num"]+ messages = [+ {"role": "system", "content": _debater_system_prompt(FOR, state["topic"])},+ {"role": "user", "content": _debater_user_prompt(FOR, round_num, state["transcript"])},+ ]+ response = client.chat.completions.create(+ model=DEBATER_A_MODEL,+ messages=messages,+ temperature=ORQ_TEMPERATURE,+ )+ argument: Argument = {+ "speaker": DEBATER_A,+ "position": FOR,+ "round": round_num,+ "content": (response.choices[0].message.content or "").strip(),+ }+ return {"transcript": state["transcript"] + [argument]}+++def _debater_b_node(state: DebateState) -> DebateState:+ client = _orq_client()+ round_num = state["round_num"]+ messages = [+ {"role": "system", "content": _debater_system_prompt(AGAINST, state["topic"])},+ {"role": "user", "content": _debater_user_prompt(AGAINST, round_num, state["transcript"])},+ ]+ response = client.chat.completions.create(+ model=DEBATER_B_MODEL,+ messages=messages,+ temperature=ORQ_TEMPERATURE,+ )+ argument: Argument = {+ "speaker": DEBATER_B,+ "position": AGAINST,+ "round": round_num,+ "content": (response.choices[0].message.content or "").strip(),+ }+ return {+ "transcript": state["transcript"] + [argument],+ "round_num": round_num + 1,+ }+++def _route_after_b(state: DebateState) -> str:+ """Loop back for another round, or hand off to the judge."""+ if state["round_num"] <= state["max_rounds"]:+ return "continue"+ return "judge"+++_JUDGE_SYSTEM = (+ "You are an impartial debate judge. Score every argument on three criteria, each from "+ "1 to 10: logic, evidence, and persuasiveness. Be fair and consistent. After scoring, "+ "tally totals for each debater, declare a single winner, and write a concise verdict.\n\n"+ "Respond with ONLY valid JSON in exactly this shape (no markdown, no extra text):\n"+ "{\n"+ ' "arguments": [\n'+ ' {"speaker": "Debater A", "round": 1, "logic": 8, "evidence": 7, '+ '"persuasiveness": 9, "comment": "..."}\n'+ " ],\n"+ ' "totals": {"Debater A": 0, "Debater B": 0},\n'+ ' "winner": "Debater A" | "Debater B" | "Tie",\n'+ ' "verdict": "A few sentences explaining the decision."\n'+ "}"+)+++def _judge_node(state: DebateState) -> DebateState:+ client = _orq_client()+ transcript_text = _history_block(state["transcript"])+ messages = [+ {"role": "system", "content": _JUDGE_SYSTEM},+ {+ "role": "user",+ "content": (+ f'Topic: "{state["topic"]}"\n'+ f"Debater A argued FOR; Debater B argued AGAINST.\n\n"+ f"Full transcript:\n\n{transcript_text}\n\n"+ "Score each argument and declare the winner now."+ ),+ },+ ]+ response = client.chat.completions.create(+ model=JUDGE_MODEL,+ messages=messages,+ temperature=ORQ_TEMPERATURE,+ )+ content = response.choices[0].message.content or ""+ return {"verdict": _parse_verdict(content, state["transcript"])}+++# --------------------------------------------------------------------------- #+# Verdict parsing+# --------------------------------------------------------------------------- #+def _parse_verdict(raw: str, transcript: List[Argument]) -> dict:+ """Best-effort extraction of the judge's JSON, with graceful fallbacks."""+ parsed: Optional[dict] = None+ match = re.search(r"\{.*\}", raw, re.DOTALL)+ if match:+ try:+ parsed = json.loads(match.group(0))+ except json.JSONDecodeError:+ parsed = None++ if not isinstance(parsed, dict):+ return {+ "arguments": [],+ "totals": {DEBATER_A: 0, DEBATER_B: 0},+ "winner": "Tie",+ "verdict": raw.strip() or "The judge did not return a parsable verdict.",+ "raw": raw.strip(),+ }++ # Recompute totals from per-argument scores when possible (more reliable than the LLM's math).+ totals = {DEBATER_A: 0, DEBATER_B: 0}+ for arg in parsed.get("arguments", []):+ speaker = arg.get("speaker")+ if speaker in totals:+ totals[speaker] += (+ int(arg.get("logic", 0))+ + int(arg.get("evidence", 0))+ + int(arg.get("persuasiveness", 0))+ )+ if any(totals.values()):+ parsed["totals"] = totals+ if totals[DEBATER_A] > totals[DEBATER_B]:+ parsed.setdefault("winner", DEBATER_A)+ elif totals[DEBATER_B] > totals[DEBATER_A]:+ parsed.setdefault("winner", DEBATER_B)++ parsed.setdefault("totals", totals)+ parsed.setdefault("winner", "Tie")+ parsed.setdefault("verdict", "")+ parsed.setdefault("arguments", [])+ return parsed+++# --------------------------------------------------------------------------- #+# Graph assembly+# --------------------------------------------------------------------------- #+def build_graph():+ """Construct and compile the debate graph."""+ graph = StateGraph(DebateState)+ graph.add_node("debater_a", _debater_a_node)+ graph.add_node("debater_b", _debater_b_node)+ graph.add_node("judge", _judge_node)++ graph.add_edge(START, "debater_a")+ graph.add_edge("debater_a", "debater_b")+ graph.add_conditional_edges(+ "debater_b",+ _route_after_b,+ {"continue": "debater_a", "judge": "judge"},+ )+ graph.add_edge("judge", END)+ return graph.compile()+++# --------------------------------------------------------------------------- #+# Public API+# --------------------------------------------------------------------------- #+def run_debate(topic: str, rounds: int) -> Iterator[DebateState]:+ """Run the debate, yielding the full state after each agent turn.++ Args:+ topic: The debate topic supplied by the user.+ rounds: Number of rounds (1-5). Each round is one A turn + one B turn.++ Yields:+ The accumulated :class:`DebateState` after every node, ending with a+ state that contains the judge's ``verdict``.+ """+ topic = (topic or "").strip()+ if not topic:+ raise ValueError("Please enter a debate topic.")+ rounds = max(1, min(5, int(rounds)))++ app = build_graph()+ initial: DebateState = {+ "topic": topic,+ "max_rounds": rounds,+ "round_num": 1,+ "transcript": [],+ "verdict": {},+ }+ # stream_mode="values" emits the full state snapshot after each node runs.+ for state in app.stream(initial, stream_mode="values"):+ yield statediff --git a/ai_agents/ai_debate_agent/requirements.txt b/ai_agents/ai_debate_agent/requirements.txtnew file mode 100644index 0000000..bf65d17--- /dev/null+++ b/ai_agents/ai_debate_agent/requirements.txt@@ -0,0 +1,5 @@+gradio>=6.0.0+langgraph>=0.2.40+langchain-core>=0.3.0+openai>=1.40.0+python-dotenv>=1.0.1diff --git a/ai_agents/ai_debate_agent/test_orq.py b/ai_agents/ai_debate_agent/test_orq.pynew file mode 100644index 0000000..609d90d--- /dev/null+++ b/ai_agents/ai_debate_agent/test_orq.py@@ -0,0 +1,69 @@+"""Quick check that Orq.ai is reachable and all three debate models respond.++Run from the project folder (with venv activated):++ py test_orq.py+"""++import os+import sys++from dotenv import load_dotenv++load_dotenv()++MODELS = [+ ("Debater A", os.getenv("DEBATER_A_MODEL", "google-ai/gemini-3-flash-preview")),+ ("Debater B", os.getenv("DEBATER_B_MODEL", "mistral/mistral-small-latest")),+ ("Judge", os.getenv("JUDGE_MODEL", "moonshotai/kimi-k2.6")),+]+++def main() -> int:+ api_key = os.getenv("ORQ_API_KEY", "").strip()+ if not api_key or api_key.startswith("your-orq"):+ print("FAIL: Set a real ORQ_API_KEY in .env (copy from .env.example if needed).")+ return 1++ try:+ from openai import OpenAI+ except ImportError:+ print("FAIL: Install dependencies: pip install -r requirements.txt")+ return 1++ client = OpenAI(+ base_url="https://api.orq.ai/v3/router",+ api_key=api_key,+ )++ print("Testing Orq.ai router at https://api.orq.ai/v3/router\n")+ failures = 0++ for label, model in MODELS:+ try:+ response = client.chat.completions.create(+ model=model,+ messages=[{"role": "user", "content": "Reply with exactly: ok"}],+ max_tokens=10,+ )+ text = (response.choices[0].message.content or "").strip()+ print(f"OK {label}: {model}")+ print(f" -> {text[:80]}\n")+ except Exception as exc:+ failures += 1+ detail = str(exc).strip() or type(exc).__name__+ if exc.__cause__ and str(exc.__cause__) not in detail:+ detail = f"{detail} — {exc.__cause__}"+ print(f"FAIL {label}: {model}")+ print(f" -> {type(exc).__name__}: {detail}\n")++ if failures:+ print(f"{failures} model(s) failed. Check ORQ_API_KEY and AI Router → Providers in Orq.")+ return 1++ print("All three models responded. You can run: py app.py")+ return 0+++if __name__ == "__main__":+ sys.exit(main())