The platform for continuously improving AI agents.
from datetime import timedelta
from django.db import transaction
from django.utils import timezone
from overbae.core.errors import InputValidationError
from overbae.core.llms import effective_max_tokens
from overbae.innermind import generation, replay
from overbae.models import (
BillingService,
PredictionAttempt,
PredictionRow,
PredictionSet,
Project,
ResearchAssignment,
)
from overbae.services import (
billing_ledger,
context_graph,
execution_mandates,
experiment_assets,
experiment_components,
model_catalog,
model_meter,
research,
research_context_authorship,
research_continuity,
)
from overbae.services.datasets import rows, use
from overbae.services.transcripts import chatml
ACTIVE = {"pending", "running"}
def authorized(assignment, *, continuation=False):
try:
authorize = (
execution_mandates.require_continuation if continuation else execution_mandates.require
)
authorize(assignment, "evaluate")
except InputValidationError:
return False
return True
def describe(predictions):
counts = {}
for state in predictions.rows.values_list("state", flat=True):
counts[state] = counts.get(state, 0) + 1
return {
"id": str(predictions.pk),
"state": predictions.state,
"candidate": str(predictions.candidate_id),
"cell": str(predictions.cell_id),
"fingerprint": predictions.fingerprint,
"rows": counts,
}
def get(project, identifier):
found = (
PredictionSet.objects.select_related("candidate", "cell__dataset", "project")
.filter(project=project, pk=identifier)
.first()
)
if found is None:
raise InputValidationError("Select a prediction set in this project")
return found
@transaction.atomic
def create(assignment, candidate_id, cell_id, request_key):
from overbae.services.research_tools import (
source_cell, # Native tools call prediction admission.
)
Project.objects.select_for_update().get(pk=assignment.project_id)
assignment.refresh_from_db()
if not authorized(assignment):
raise InputValidationError("This assignment no longer has prediction authority")
candidate = experiment_assets.get(assignment.project, candidate_id, "candidate")
cell = source_cell(assignment, cell_id)
if candidate.definition["kind"] == "native_predictions":
raise InputValidationError(
"This asset retains native prediction evidence; it cannot start inference"
)
if candidate.definition["kind"] == "checkpoint":
raise InputValidationError(
"Selected checkpoints execute through native benchmark.run; Predict supports catalogue, agent and component candidates"
)
identity = context_graph.fingerprint(
{"candidate": candidate.fingerprint, "cell": str(cell.pk), "data": cell.fingerprint}
)
existing = PredictionSet.objects.filter(
project=assignment.project, request_key=request_key
).first()
if existing:
if existing.fingerprint != identity:
raise InputValidationError("This request key identifies different prediction inputs")
transaction.on_commit(lambda: dispatch(existing.pk))
return existing
research_context_authorship.require_asset(assignment, candidate)
rows.verify(cell)
prepared = []
for row in rows.iter_rows(cell):
row = generation.prepared(row)
seed = generation.row_seed(row)
value = row.input
if chatml.parse_messages(value):
value = {"messages": seed.messages, "tools": seed.tool_defs}
experiment_assets.check_schema(candidate.definition["input_schema"], value, validate=True)
request = {
"value": value,
"messages": seed.messages,
"tools": seed.tool_defs,
"recorded_calls": seed.provider.recorded_calls,
}
prepared.append(
PredictionRow(
index=row.index, input=request, input_digest=context_graph.fingerprint(request)
)
)
if not prepared:
raise InputValidationError("The selected prediction input is empty")
use.freeze(cell)
predictions = PredictionSet.objects.create(
project=assignment.project,
assignment=assignment,
candidate=candidate,
cell=cell,
request_key=request_key,
fingerprint=identity,
)
for row in prepared:
row.prediction_set = predictions
PredictionRow.objects.bulk_create(prepared, batch_size=500)
transaction.on_commit(lambda: dispatch(predictions.pk))
return predictions
@transaction.atomic
def dispatch(identifier):
from overbae.tasks.research import predict_row # Tasks call this service on settlement.
project_id = PredictionSet.objects.values_list("project_id", flat=True).get(pk=identifier)
Project.objects.select_for_update().get(pk=project_id)
predictions = (
PredictionSet.objects.select_for_update(of=("self",))
.select_related("assignment__created_by")
.get(pk=identifier)
)
if predictions.state not in ACTIVE:
return
if predictions.assignment_id and not authorized(predictions.assignment, continuation=True):
cancel(predictions)
return
now = timezone.now()
for attempt in PredictionAttempt.objects.select_for_update().filter(
row__prediction_set=predictions, state__in=["queued", "running"], expires_at__lte=now
):
if attempt.state == "queued":
attempt.state, attempt.completed_at = "expired", now
attempt.save(update_fields=["state", "completed_at"])
PredictionRow.objects.filter(pk=attempt.row_id).update(state="pending")
continue
attempt.state, attempt.error, attempt.completed_at = (
"unknown",
"Execution outcome unknown after its deadline; not replayed",
now,
)
attempt.save(update_fields=["state", "error", "completed_at"])
PredictionRow.objects.filter(pk=attempt.row_id).update(state="unknown", error=attempt.error)
for identifier in predictions.rows.filter(
state="queued",
attempts__state="queued",
attempts__started_at__lt=now - timedelta(seconds=60),
).values_list("attempts__pk", flat=True):
transaction.on_commit(
lambda identifier=str(identifier): predict_row.delay(identifier), robust=True
)
active = predictions.rows.filter(state__in=["queued", "running"]).count()
project_active = PredictionRow.objects.filter(
prediction_set__project_id=project_id, state__in=["queued", "running"]
).count()
for row in predictions.rows.filter(state="pending").order_by("index")[
: max(0, min(4 - active, 8 - project_active))
]:
attempt = PredictionAttempt.objects.create(
row=row, state="queued", expires_at=now + timedelta(minutes=30)
)
row.state = "queued"
row.save(update_fields=["state"])
transaction.on_commit(
lambda identifier=str(attempt.pk): predict_row.delay(identifier), robust=True
)
states = set(predictions.rows.values_list("state", flat=True))
predictions.state = (
"running"
if states & {"pending", "queued", "running"}
else "completed"
if states == {"completed"}
else "failed"
)
predictions.completed_at = now if predictions.state not in ACTIVE else None
predictions.save(update_fields=["state", "completed_at"])
if predictions.assignment_id and predictions.state not in ACTIVE:
from overbae.services.research_wakes import (
request, # Wakes inspect native prediction state.
)
request(predictions.assignment_id)
def active(attempt):
return PredictionAttempt.objects.filter(
pk=attempt.pk,
state="running",
expires_at__gt=timezone.now(),
row__prediction_set__state="running",
).exists() and (
not attempt.row.prediction_set.assignment_id
or authorized(
ResearchAssignment.objects.get(pk=attempt.row.prediction_set.assignment_id),
continuation=True,
)
)
def ensure_active(attempt):
if not active(attempt):
raise generation.GenerationStoppedError("Prediction attempt is no longer active")
def execute(attempt_id):
with transaction.atomic():
attempt = PredictionAttempt.objects.select_related(
"row__prediction_set__candidate", "row__prediction_set__project"
).get(pk=attempt_id)
predictions = PredictionSet.objects.select_for_update().get(
pk=attempt.row.prediction_set_id
)
if predictions.state != "running" or not PredictionAttempt.objects.filter(
pk=attempt.pk, state="queued", expires_at__gt=timezone.now()
).update(state="running", expires_at=timezone.now() + timedelta(minutes=23)):
return
attempt.state = "running"
PredictionRow.objects.filter(pk=attempt.row_id).update(state="running")
definition, row = attempt.row.prediction_set.candidate.definition, attempt.row
receipt, usage, trace, output, error, state = {}, {}, {}, None, "", "completed"
ledger = {}
agent = predictions.assignment.agents.get(parent__isnull=True)
def before_call(step, messages, tools):
ensure_active(attempt)
research_context_authorship.require_asset(
predictions.assignment, attempt.row.prediction_set.candidate
)
quote = model_catalog.estimate_cost(
definition["model"],
int(research_continuity.token_count(messages, tools) * 1.25) + 1024,
effective_max_tokens(definition["model"], definition["max_tokens"]),
)
if quote is None:
raise InputValidationError("Candidate model pricing is unavailable")
entry = research.claim(
agent,
f"prediction:{attempt.pk}:{step}",
"prediction_model",
{
"attempt": str(attempt.pk),
"step": step,
"model": definition["model"],
"request_fingerprint": context_graph.fingerprint([messages, tools]),
"max_tokens": definition["max_tokens"],
},
reservation=quote * 1.1,
effect=attempt,
)
if entry.state == "denied":
raise InputValidationError(entry.result["error"])
ledger[step] = entry
receipt["model_actions"] = [str(item.pk) for item in ledger.values()]
if not progress():
research.complete(
entry, {"error": "Prediction cancelled before submission"}, state="failed", cost=0
)
raise generation.GenerationStoppedError("Prediction cancelled before submission")
def after_call(step, stats):
research.complete(
ledger[step],
{"attempt": str(attempt.pk), "step": step},
cost=stats.get("response_cost"),
usage=stats,
)
def progress():
PredictionAttempt.objects.filter(pk=attempt.pk).update(receipt=receipt)
return active(attempt)
try:
ensure_active(attempt)
research_context_authorship.require_asset(
predictions.assignment, attempt.row.prediction_set.candidate
)
if definition["kind"] == "component":
component = experiment_assets.get(
predictions.project, definition["component"], "component"
)
if component.fingerprint != definition["component_fingerprint"]:
raise InputValidationError("The retained component identity changed")
output = experiment_components.execute(
component,
{"input": row.input["value"]},
definition["parameters"],
receipt=receipt,
progress=progress,
assignment=predictions.assignment,
source_asset=attempt.row.prediction_set.candidate,
)["output"]
trace = {"runtime": receipt}
else:
if definition["runtime"] != experiment_assets.runtime_identity():
raise InputValidationError(
"The pinned prediction runtime is unavailable; publish a new candidate revision"
)
messages = (
[message for message in row.input["messages"] if message.get("role") != "system"]
if definition["system_prompt"]
else row.input["messages"]
)
common = {
"input_messages": messages,
"model": definition["model"],
"system_prompt": definition["system_prompt"] or None,
"reasoning_effort": definition["reasoning_effort"],
"project_id": str(predictions.project_id),
"max_tokens": definition["max_tokens"],
"before_call": before_call,
"after_call": after_call,
}
provider = replay.ReplayToolProvider(
tool_defs=row.input["tools"], recorded_calls=row.input["recorded_calls"]
)
with model_meter.billed(
billing_ledger.cause(
predictions.project_id,
BillingService.RESEARCH,
"prediction_attempt",
attempt.pk,
actor=predictions.assignment.created_by_id,
)
):
result = (
replay.generate_decision(tool_provider=provider, **common)
if definition["strategy"] == "single_completion"
else replay.run_capability(
tool_provider=provider,
max_steps=definition["max_steps"],
check_active=lambda: ensure_active(attempt),
**common,
)
)
output = generation.output_of(result.output_messages)
trace = {
"messages": result.output_messages,
"steps": result.steps,
"finish_reasons": result.finish_reasons,
"context_checks": result.context_checks,
}
usage = {
"cost_usd": sum(item["response_cost"] for item in result.usage)
if result.usage
and not result.error
and all(item.get("response_cost") is not None for item in result.usage)
else None,
"attempts": result.usage,
"prompt_tokens": result.prompt_tokens or None,
"completion_tokens": result.completion_tokens or None,
"latency_ms": result.latency_ms or None,
}
if result.error:
raise RuntimeError(result.error)
if reason := generation.degradation(result, output):
raise InputValidationError(reason)
experiment_assets.check_schema(definition["output_schema"], output, validate=True)
except generation.GenerationStoppedError as exc:
state, error = "cancelled", str(exc)
except InputValidationError as exc:
state, error = "failed", str(exc)
except Exception as exc:
state = "failed" if receipt.get("submission_rejected") else "unknown"
error = f"Unconfirmed execution: {type(exc).__name__}: {exc}"
for entry in ledger.values():
if entry.state == "pending":
research.complete(
entry, {"error": error or "Provider outcome unconfirmed"}, state="unknown"
)
with transaction.atomic():
PredictionSet.objects.select_for_update().get(pk=predictions.pk)
PredictionAttempt.objects.filter(pk=attempt.pk).update(
receipt=receipt, output=output, trace=trace, usage=usage
)
if not active(attempt):
if predictions.assignment_id and not authorized(
predictions.assignment, continuation=True
):
cancel(predictions)
return
PredictionAttempt.objects.filter(pk=attempt.pk).update(
state=state, receipt=receipt, error=error, completed_at=timezone.now()
)
PredictionRow.objects.filter(pk=row.pk).update(
state=state, output=output, trace=trace, usage=usage, error=error
)
transaction.on_commit(lambda: dispatch(predictions.pk))
@transaction.atomic
def cancel(predictions):
predictions = PredictionSet.objects.select_for_update().get(pk=predictions.pk)
if predictions.state in ACTIVE:
predictions.state, predictions.completed_at = "cancelled", timezone.now()
predictions.save(update_fields=["state", "completed_at"])
predictions.rows.filter(state__in=["pending", "queued", "running"]).update(
state="cancelled"
)
PredictionAttempt.objects.filter(
row__prediction_set=predictions, state__in=["queued", "running"]
).update(state="cancelled", completed_at=timezone.now())
return describe(predictions)
@transaction.atomic
def resume(predictions):
predictions = (
PredictionSet.objects.select_for_update(of=("self",))
.select_related("assignment__created_by")
.get(pk=predictions.pk)
)
if predictions.assignment_id and not authorized(predictions.assignment):
raise InputValidationError("This assignment no longer has prediction authority")
if predictions.rows.filter(state__in=["unknown", "cancelled"]).exists():
raise InputValidationError(
"Unconfirmed or cancelled predictions are not replayed; create an explicit new prediction set"
)
if predictions.state == "failed":
predictions.rows.filter(state="failed").update(state="pending", error="")
predictions.state, predictions.completed_at = "pending", None
predictions.save(update_fields=["state", "completed_at"])
transaction.on_commit(lambda: dispatch(predictions.pk))
return describe(predictions)
def reconcile(assignment):
for identifier in PredictionSet.objects.filter(
assignment=assignment, state__in=ACTIVE
).values_list("pk", flat=True):
dispatch(identifier)
def observations(assignment):
return [
describe(item)
for item in PredictionSet.objects.filter(assignment=assignment).order_by("pk")
]