citadel-predict
Pre-execution token budget and cost predictor client for AI agents.
citadel-predict is a lightweight, pure HTTP Python client and CLI for the Citadel Predict API. It allows developers, CI pipelines, and autonomous agent loops to estimate LLM token consumption and cost ranges before initiating expensive agent runs.
Installation
pip install citadel-predict
Quickstart (3 Lines of Code)
from citadel_predict import predict_cost
result = predict_cost(
task_text="Research competitor pricing across 3 sources and draft report",
tools=["web_search", "draft_document"]
)
print(f"Expected: {result['expected_tokens']:,} tokens (Range: {result['low_tokens']:,} – {result['high_tokens']:,})")
Output:
Expected: 3,200 tokens (Range: 1,500 – 5,800)
CLI Usage
citadel-predict includes a full-featured CLI for terminal workflows and CI/CD cost checks:
# Pretty terminal card output
citadel-predict --task "Audit repository and write migration guide" --tools list_files,read_document,draft_document
# Scripting / CI mode (JSON output)
citadel-predict --task "Calculate statistical metrics" --tools calculator --json
# Override API key or URL
citadel-predict --task "..." --api-key "cp_live_12345" --api-url "https://api.citadel.dev"
CLI Exit Codes
0: Success2: Validation Error / Bad Request (HTTP 400 / 422 or missing task)3: Authentication Failure (HTTP 401)4: Rate Limit Exceeded (HTTP 429)5: Server Error (HTTP 5xx)6: Network / Timeout Error
Real Agent Integration: Pre-Execution Guardrails
Existing agent governance tools (e.g., Portkey, Langfuse, LiteLLM) are reactive—they record costs during or after an execution. citadel-predict is predictive—enabling pre-flight budget checks and dynamic routing before running reasoning loops.
LangGraph / CrewAI Pre-Flight Cost Guardrail Example
from typing import TypedDict, List
from citadel_predict import predict_cost, CitadelError
class AgentState(TypedDict):
task: str
tools: List[str]
budget_tokens: int
approved: bool
def pre_flight_budget_guardrail(state: AgentState) -> AgentState:
"""
Evaluates token budget before dispatching tools or multi-agent loops.
"""
try:
prediction = predict_cost(
task_text=state["task"],
tools=state["tools"],
model_id="claude-sonnet"
)
except CitadelError as e:
print(f"Cost prediction unavailable: {e}. Falling back to default budget.")
return state
expected = prediction["expected_tokens"]
high = prediction["high_tokens"]
is_ood = prediction["out_of_distribution"]
print(f"Pre-flight estimate: ~{expected:,} tokens (Upper bound: {high:,})")
if is_ood:
print(f"Warning: Out-of-Distribution task ({prediction['ood_reasons']})")
# Guardrail Policy: Escalate if upper bound exceeds budget
if high > state["budget_tokens"]:
print(f"[BLOCKED] High-estimate ({high:,}) exceeds budget ({state['budget_tokens']:,})")
# In a real agent: switch to smaller model, ask human for approval, or prune tool access
state["approved"] = False
else:
state["approved"] = True
return state
# Example usage in workflow
initial_state: AgentState = {
"task": "Perform exhaustive market research across 20 industry filings",
"tools": ["web_search", "fetch_url", "draft_document"],
"budget_tokens": 10000,
"approved": False
}
state = pre_flight_budget_guardrail(initial_state)
if not state["approved"]:
print("Action required: Human-in-the-loop approval or task reformulation needed.")
Authentication & Configuration
The client resolves your API key and base URL according to the following priority:
- Explicit argument:
predict_cost(..., api_key="...", api_url="...")or CLI--api-key/--api-url - Environment variables:
CITADEL_API_KEYandCITADEL_API_URL - Configuration file:
~/.citadel/config.toml
Example ~/.citadel/config.toml
api_key = "cp_live_your_api_key_here"
api_url = "https://api.citadel.dev"
Error Handling
citadel-predict surfaces typed, catchable exceptions:
from citadel_predict import (
predict_cost,
CitadelAuthError,
CitadelRateLimitError,
CitadelValidationError,
CitadelServerError,
CitadelNetworkError,
)
try:
result = predict_cost("Analyze dataset", tools=["calculator"])
except CitadelAuthError:
# 401: Missing or invalid API key
...
except CitadelRateLimitError as e:
# 429: Rate limited; check e.retry_after
print(f"Retry after {e.retry_after} seconds")
except CitadelValidationError as e:
# 422: Input validation bounds exceeded (e.g. task > 4000 chars)
...
except CitadelNetworkError as e:
# Timeout or connection failure
...
Honest Limitations
citadel-predict is a thin client wrapping the hosted calibration model. It directly inherits the current system characteristics:
- Single-Model Calibration: Calibration is currently tuned specifically for Claude Sonnet (
claude-sonnet). Future releases will introduce multi-model support viamodel_id. - Calibration Dataset Scale: Calibrated on $N=20$ diverse task archetypes across 80 benchmarked runs.
- Synthetic Tool Sizing: Ground-truth data was collected using deterministic mock tool outputs with representative context expansion. Real-world tools with unbounded payload returns (e.g., massive scraped DOMs) may exhibit higher variance.
- Pre-execution Estimation: Token predictions represent calibrated statistical ranges $[low, expected, high]$, not runtime guarantees against infinite loops or divergent agent reasoning.
License
MIT
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file citadel_predict-0.1.1.tar.gz.
File metadata
- Download URL: citadel_predict-0.1.1.tar.gz
- Upload date:
- Size: 13.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via:
twine/7.0.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
302d893cbde85b84abb899fe932b157c8a91b7884099d40bc1b83dae33aa3eef
|
|
| MD5 |
bc297562c6858013781274e751933c65
|
|
| BLAKE2b-256 |
4f328c34b5af2c0543447110d2d9fd976fc585611b2c52d0c365d2f4d5eeb14b
|
File details
Details for the file citadel_predict-0.1.1-py3-none-any.whl.
File metadata
- Download URL: citadel_predict-0.1.1-py3-none-any.whl
- Upload date:
- Size: 11.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via:
twine/7.0.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dbe0e15b983352d53c316a65340cadcf4e84d924f1da07b6da90a29fe4061841
|
|
| MD5 |
1c91368bffe46a57e49ececbfa9eda52
|
|
| BLAKE2b-256 |
c85f4937b5ec1e90c3c47fe436b10dd8d83cc38bfdd6a43fc153a98fdc4ad6ce
|