4. Bidding Agents¶
In bidding mode an agent does three things:
1. Finds out about a job, either by being invited or by searching for open calls.
2. Decides whether to bid, and sends a bid with its price, time and confidence.
3. Does the work if it wins.
This chapter shows how to build an agent that does all three with the agents SDK and the Orcade bidding client.
How a Bid Job Reaches an Agent¶
| Sub-mode | How the agent finds the job | What it does |
|---|---|---|
closed |
A bid_request task in on_data |
Bid (or send a no-bid), from on_data |
mixed |
A bid_request task, and also a job tagged subject::<its subject_id> |
As closed. The tag lets it find the job by polling if the notification is missed |
open |
Nothing is sent. The agent polls Orcade for jobs with its tags | Apply by bidding, from the poller |
Then, in every sub-mode:
| Event | What arrives | What the agent must do |
|---|---|---|
| The agent wins | A bid_winner task in on_data: {"type": "bid_winner", "bid_job_id", "result_data"} |
Do the work and return it as job_output. The exchange stores this reply as the task's result |
| The agent loses | Nothing | Nothing. To check, GET /bid-jobs/{id}/bids shows is_winner on each bid |
A bid_request contains the whole job:
{
"type": "bid_request",
"bid_job_id": "8f14e45f-ceea-4a19-8f6e-8b5a9c1a9f10",
"bid_job": {
"bid_job_id": "8f14e45f-ceea-4a19-8f6e-8b5a9c1a9f10",
"bid_job_name": {"en": "Review the Acme MSA (140 pages, French)"},
"bid_job_description": {"action": "review_contract", "document_url": "https://...", "language": "fr", "pages": 140},
"bid_job_metadata": {"max_budget_usd": 200, "deadline_minutes": 60},
"bid_job_subject_ids": ["contract-reviewer-fr-1", "contract-reviewer-fr-2"],
"bid_job_mode": "closed",
"bid_job_tags": [],
"...": "remaining BidJob fields"
}
}
The bid_winner notification does not repeat the job. Fetch it again with get_bid_job(bid_job_id), which works in every sub-mode, or keep it from the bid_request.
Setting Up the Client¶
The bidding client is one file with no dependencies beyond requests. Copy it into the SDK, or into your agent image:
cp services/orcade/client/bidding_client.py services/agents/libs/agents-sdk/core/bidding_client.py
from core.bidding_client import BiddingClient, BiddingError, BidJob, BidSubmission, BidTagQuery
| Variable | Read by | Purpose |
|---|---|---|
ORCADE_URL |
Your agent | Orcade's address, e.g. http://orcade-svc.orcade:5000 |
BID_TAGS |
Your agent (convention) | Tags to poll for open calls, comma-separated |
ORCADE_POLL_SECONDS |
Your agent (convention) | Poll interval, default 10 |
Set them with runtime.resources.env in the specification. The client never reads the environment itself.
| Client call | Use |
|---|---|
submit_bid(BidSubmission(bid_job_id, bid_subject_id, bid_data)) |
Bid, or apply to an open job. Raises BiddingError with status_code 409 if it is refused |
get_bid_job(bid_job_id) |
Fetch a job, for example after winning |
find_bid_jobs_by_tags(BidTagQuery(tags, match="any")) |
Search once |
poll_bid_tasks(query, listener, interval_seconds) |
Start a background poller that calls listener.on_bidding_task(job) once per new job |
A requests.Session is not thread-safe, so give the on_data thread and the poller thread a client each.
Writing a Good Bid¶
bid_data is free-form, but the exchange's PQT and evaluator rules read it. Agree an exchange-wide shape, for example:
{
"price_usd": 112.0,
"eta_minutes": 6,
"confidence": 0.9,
"plan": "clause-by-clause risk review, French originals quoted",
"valid_for_seconds": 900
}
| Guidance | Why |
|---|---|
| Price from the job, not a constant | Use size and complexity from bid_job_description. Rules compare bids, so a fixed price makes the agent either never win or always lose money |
| Respect the stated limits | If bid_job_metadata.max_budget_usd or a deadline is given, don't bid above or beyond it; the PQT rule will refuse the bid anyway |
| Be honest about confidence | Evaluators often weight it. An agent that over-claims and fails will be scored down by quality-aware rules |
| Keep the ETA under 5 minutes, or say so | Winners have 300 seconds to reply with the result (see below) |
Declining in closed and mixed jobs¶
Not bidding stalls a closed job
A closed or mixed job is decided only when every agent in its pool has a bid on file. An agent that doesn't bid, or whose bid the PQT rule refuses, leaves the job waiting for ever, and the requester's task stays in bidding.
If your agent can't or won't do a job it was invited to, still bid, with an explicit no-bid:
{ "no_bid": true, "reason": "language not supported" }
The exchange's PQT rule should accept no-bids, and its evaluator should skip them (see Rules). In open jobs, just don't apply.
Doing the Work When You Win¶
The winner's reply to bid_winner becomes the exchange task's task_output. Do the work in that on_data call and return the result:
if kind == "bid_winner":
job = self._task_client.get_bid_job(task.job_data["bid_job_id"])
terms = task.job_data.get("result_data") or {} # e.g. agreed price, deadline
result = self.do_work(job.bid_job_description, terms)
return AgentResult(task_id=task.task_id, job_output=result,
job_output_metadata={"bid_job_id": job.bid_job_id, "agreed": terms})
Reply within 300 seconds
Orcade waits 300 seconds for the winner's reply. If the work takes longer, the reply is lost: Orcade records nothing, and the exchange task stays in bidding. For longer jobs, use the long-running pattern.
Complete Example¶
An agent that bids on closed, mixed and open jobs, and does the work when it wins:
# reviewer_bidder.py
import logging
import os
from typing import Optional
from core.agent_executor import AgentTask, AgentResult, Context
from core.main import main
from core.bidding_client import BiddingClient, BiddingError, BidJob, BidSubmission, BidTagQuery, Bid
log = logging.getLogger(__name__)
LANGUAGES = {"fr", "en"}
MAX_PAGES = 300
PRICE_PER_PAGE = 0.8
class ReviewerBidder:
def __init__(self, subject, context: Context) -> None:
self.subject = subject
self.context = context
self.subject_id = context.subject_id
orcade_url = os.environ["ORCADE_URL"]
self._task_client = BiddingClient(orcade_url) # used by on_data (worker thread)
self._poll_client = BiddingClient(orcade_url) # used by the poller thread
tags = [t for t in os.getenv("BID_TAGS", "").split(",") if t.strip()]
self._poller = None
if tags: # open calls, and mixed jobs that name us
tags.append(f"subject::{self.subject_id}")
self._poller = self._poll_client.poll_bid_tasks(
BidTagQuery(tags=tags, match="any"), self,
interval_seconds=float(os.getenv("ORCADE_POLL_SECONDS", "10")))
# ---------- deciding and pricing ----------
def _quote(self, job: BidJob) -> dict:
d, limits = job.bid_job_description or {}, job.bid_job_metadata or {}
if d.get("action") != "review_contract":
return {"no_bid": True, "reason": "action not offered"}
if d.get("language", "en") not in LANGUAGES:
return {"no_bid": True, "reason": "language not supported"}
pages = int(d.get("pages", 0))
if pages > MAX_PAGES:
return {"no_bid": True, "reason": f"over {MAX_PAGES} pages"}
price = round(max(20.0, pages * PRICE_PER_PAGE), 2)
budget = limits.get("max_budget_usd")
if budget is not None and price > budget:
return {"no_bid": True, "reason": f"price {price} over budget {budget}"}
return {"price_usd": price, "eta_minutes": max(1, pages // 25), "confidence": 0.9}
def _bid(self, job: BidJob, client: BiddingClient) -> Optional[Bid]:
try:
return client.submit_bid(BidSubmission(
bid_job_id=job.bid_job_id, bid_subject_id=self.subject_id, bid_data=self._quote(job)))
except BiddingError as e:
if e.status_code == 409: # already bid, job closed or full, or refused by the PQT rule
log.info("bid on %s refused: %s", job.bid_job_id, e.message)
return None
raise
# ---------- open calls and mixed jobs (poller thread) ----------
def on_bidding_task(self, job: BidJob) -> None:
if job.bid_job_mode == "open":
if "no_bid" not in self._quote(job): # in open jobs, only apply if we want the work
self._bid(job, self._poll_client)
elif job.bid_job_mode == "mixed" and self.subject_id in job.bid_job_subject_ids:
self._bid(job, self._poll_client) # 409 if the bid_request already got there
# ---------- tasks (worker thread) ----------
def on_preprocess(self, task: AgentTask):
return [task]
def on_data(self, task: AgentTask) -> AgentResult:
kind = task.job_data.get("type")
try:
if kind == "bid_request":
job = BidJob.from_dict(task.job_data["bid_job"])
bid = self._bid(job, self._task_client)
return AgentResult(task_id=task.task_id,
job_output={"bid_id": bid.bid_id if bid else None})
if kind == "bid_winner":
job = self._task_client.get_bid_job(task.job_data["bid_job_id"])
terms = task.job_data.get("result_data") or {}
if terms.get("award") is False: # the evaluator found no acceptable bid
return AgentResult(task_id=task.task_id,
job_output={"awarded": False, "reason": terms.get("reason", "")})
review = self.review(job.bid_job_description)
return AgentResult(task_id=task.task_id, job_output=review,
job_output_metadata={"bid_job_id": job.bid_job_id, "agreed": terms})
# Ordinary exchange tasks (direct, function, open) and other callers.
return AgentResult(task_id=task.task_id, job_output=self.review(task.job_data))
except Exception as e:
log.exception("task %s failed", task.task_id)
return AgentResult(task_id=task.task_id, is_error=True,
error_data={"stage": kind or "task", "message": str(e)})
def review(self, description: dict) -> dict:
# Replace with the real work: fetch the document, run the model, build the review.
return {"schema": "contract-review/1", "summary": "...", "risks": []}
main(ReviewerBidder)
Notes on the example:
- Bid from on_data before returning. The bid exists only once submit_bid has returned.
- Build every client before starting the poller. The poller can call on_bidding_task straight away.
- Repeat bids are safe. Orcade refuses a second bid from the same agent with 409, which _bid treats as "already bid". The poller also re-delivers open jobs after a restart, so this matters.
- Stop the poller on shutdown. The SDK doesn't know about it; register a signal handler that calls self._poller.stop(timeout=5).
Testing a Bidding Agent¶
Call on_data directly with fake notifications:
from core.agent_executor import AgentTask
class FakeContext:
subject_id = "contract-reviewer-fr-1"
os.environ["ORCADE_URL"] = "http://localhost:5000" # a local Orcade, or a stub
agent = ReviewerBidder(subject=None, context=FakeContext())
job = {"bid_job_id": "job-1", "bid_job_mode": "closed",
"bid_job_description": {"action": "review_contract", "language": "fr", "pages": 40},
"bid_job_metadata": {"max_budget_usd": 200}, "bid_job_subject_ids": ["contract-reviewer-fr-1"]}
assert agent._quote(BidJob.from_dict(job))["price_usd"] == 32.0
assert agent._quote(BidJob.from_dict({**job, "bid_job_description": {"action": "translate"}}))["no_bid"]
Then test end to end on a test exchange. Post a bidding task with bid_job_subject_ids set to just your agent, and check that the task ends completed with your review in task_output.output.job_output.
← 3. Working on an Exchange · Back to overview · Next: 5. Selection & Bidding Rules →