|
| 1 | +"""Integrating Cycles with the Anthropic Python SDK. |
| 2 | +
|
| 3 | +Guards Anthropic Messages API calls with budget reservations and |
| 4 | +demonstrates per-tool-call budget tracking for agentic workflows. |
| 5 | +
|
| 6 | +Requirements: |
| 7 | + pip install runcycles anthropic |
| 8 | +
|
| 9 | +Environment variables: |
| 10 | + CYCLES_BASE_URL - Cycles server URL (default: http://localhost:7878) |
| 11 | + CYCLES_API_KEY - Cycles API key |
| 12 | + CYCLES_TENANT - Tenant identifier |
| 13 | + ANTHROPIC_API_KEY - Anthropic API key |
| 14 | +""" |
| 15 | + |
| 16 | +import os |
| 17 | +import uuid |
| 18 | + |
| 19 | +from anthropic import Anthropic |
| 20 | + |
| 21 | +from runcycles import ( |
| 22 | + Action, |
| 23 | + Amount, |
| 24 | + BudgetExceededError, |
| 25 | + CommitRequest, |
| 26 | + CyclesClient, |
| 27 | + CyclesConfig, |
| 28 | + CyclesMetrics, |
| 29 | + ReservationCreateRequest, |
| 30 | + Subject, |
| 31 | + Unit, |
| 32 | + cycles, |
| 33 | + get_cycles_context, |
| 34 | + set_default_client, |
| 35 | +) |
| 36 | + |
| 37 | +# --------------------------------------------------------------------------- |
| 38 | +# 1. Configure clients |
| 39 | +# --------------------------------------------------------------------------- |
| 40 | +config = CyclesConfig( |
| 41 | + base_url=os.environ.get("CYCLES_BASE_URL", "http://localhost:7878"), |
| 42 | + api_key=os.environ.get("CYCLES_API_KEY", "your-api-key"), |
| 43 | + tenant=os.environ.get("CYCLES_TENANT", "acme"), |
| 44 | + app="anthropic-example", |
| 45 | +) |
| 46 | +cycles_client = CyclesClient(config) |
| 47 | +set_default_client(cycles_client) |
| 48 | + |
| 49 | +anthropic_client = Anthropic() # reads ANTHROPIC_API_KEY from env |
| 50 | + |
| 51 | +# Pricing in USD microcents (1 USD = 100_000_000 microcents). |
| 52 | +PRICE_PER_INPUT_TOKEN = 300 # $3.00 / 1M tokens |
| 53 | +PRICE_PER_OUTPUT_TOKEN = 1_500 # $15.00 / 1M tokens |
| 54 | + |
| 55 | + |
| 56 | +# --------------------------------------------------------------------------- |
| 57 | +# 2. Simple decorator-based integration |
| 58 | +# --------------------------------------------------------------------------- |
| 59 | +@cycles( |
| 60 | + estimate=lambda prompt, **kw: ( |
| 61 | + len(prompt.split()) * 2 * PRICE_PER_INPUT_TOKEN |
| 62 | + + kw.get("max_tokens", 1024) * PRICE_PER_OUTPUT_TOKEN |
| 63 | + ), |
| 64 | + actual=lambda result: ( |
| 65 | + result["usage"]["input_tokens"] * PRICE_PER_INPUT_TOKEN |
| 66 | + + result["usage"]["output_tokens"] * PRICE_PER_OUTPUT_TOKEN |
| 67 | + ), |
| 68 | + action_kind="llm.completion", |
| 69 | + action_name="claude-sonnet-4-20250514", |
| 70 | + unit="USD_MICROCENTS", |
| 71 | + ttl_ms=60_000, |
| 72 | +) |
| 73 | +def send_message(prompt: str, max_tokens: int = 1024) -> dict: |
| 74 | + """Send a message to Claude with budget protection.""" |
| 75 | + ctx = get_cycles_context() |
| 76 | + |
| 77 | + # Respect caps |
| 78 | + if ctx and ctx.has_caps() and ctx.caps.max_tokens: |
| 79 | + max_tokens = min(max_tokens, ctx.caps.max_tokens) |
| 80 | + |
| 81 | + response = anthropic_client.messages.create( |
| 82 | + model="claude-sonnet-4-20250514", |
| 83 | + max_tokens=max_tokens, |
| 84 | + messages=[{"role": "user", "content": prompt}], |
| 85 | + ) |
| 86 | + |
| 87 | + if ctx: |
| 88 | + ctx.metrics = CyclesMetrics( |
| 89 | + tokens_input=response.usage.input_tokens, |
| 90 | + tokens_output=response.usage.output_tokens, |
| 91 | + model_version=response.model, |
| 92 | + ) |
| 93 | + |
| 94 | + return { |
| 95 | + "content": response.content[0].text, |
| 96 | + "usage": { |
| 97 | + "input_tokens": response.usage.input_tokens, |
| 98 | + "output_tokens": response.usage.output_tokens, |
| 99 | + }, |
| 100 | + } |
| 101 | + |
| 102 | + |
| 103 | +# --------------------------------------------------------------------------- |
| 104 | +# 3. Per-tool-call budget tracking (programmatic) |
| 105 | +# --------------------------------------------------------------------------- |
| 106 | +TOOLS = [ |
| 107 | + { |
| 108 | + "name": "get_weather", |
| 109 | + "description": "Get current weather for a location.", |
| 110 | + "input_schema": { |
| 111 | + "type": "object", |
| 112 | + "properties": {"location": {"type": "string"}}, |
| 113 | + "required": ["location"], |
| 114 | + }, |
| 115 | + } |
| 116 | +] |
| 117 | + |
| 118 | + |
| 119 | +def handle_tool_call(tool_name: str, tool_input: dict) -> str: |
| 120 | + """Simulate executing a tool.""" |
| 121 | + if tool_name == "get_weather": |
| 122 | + return f"72°F and sunny in {tool_input.get('location', 'unknown')}" |
| 123 | + return "Unknown tool" |
| 124 | + |
| 125 | + |
| 126 | +def chat_with_tools(prompt: str) -> str: |
| 127 | + """Multi-turn conversation with tool use, each LLM call budget-guarded.""" |
| 128 | + messages = [{"role": "user", "content": prompt}] |
| 129 | + turn = 0 |
| 130 | + |
| 131 | + while True: |
| 132 | + turn += 1 |
| 133 | + idempotency_key = f"tool-chat-{uuid.uuid4()}" |
| 134 | + |
| 135 | + # Reserve budget for this turn |
| 136 | + reserve_response = cycles_client.create_reservation( |
| 137 | + ReservationCreateRequest( |
| 138 | + idempotency_key=idempotency_key, |
| 139 | + subject=Subject( |
| 140 | + tenant=config.tenant, |
| 141 | + agent="tool-agent", |
| 142 | + toolset="weather-tools", |
| 143 | + ), |
| 144 | + action=Action( |
| 145 | + kind="llm.completion", |
| 146 | + name="claude-sonnet-4-20250514", |
| 147 | + tags=[f"turn-{turn}"], |
| 148 | + ), |
| 149 | + estimate=Amount(unit=Unit.USD_MICROCENTS, amount=2_000_000), |
| 150 | + ttl_ms=30_000, |
| 151 | + ) |
| 152 | + ) |
| 153 | + |
| 154 | + if not reserve_response.is_success: |
| 155 | + error_resp = reserve_response.get_error_response() |
| 156 | + if error_resp and error_resp.error_code == "BUDGET_EXCEEDED": |
| 157 | + return "Budget exhausted — cannot continue conversation." |
| 158 | + return f"Reservation failed: {reserve_response.error_message}" |
| 159 | + |
| 160 | + reservation_id = reserve_response.get_body_attribute("reservation_id") |
| 161 | + |
| 162 | + # Call Claude |
| 163 | + response = anthropic_client.messages.create( |
| 164 | + model="claude-sonnet-4-20250514", |
| 165 | + max_tokens=1024, |
| 166 | + tools=TOOLS, |
| 167 | + messages=messages, |
| 168 | + ) |
| 169 | + |
| 170 | + # Commit actual cost |
| 171 | + actual_cost = ( |
| 172 | + response.usage.input_tokens * PRICE_PER_INPUT_TOKEN |
| 173 | + + response.usage.output_tokens * PRICE_PER_OUTPUT_TOKEN |
| 174 | + ) |
| 175 | + cycles_client.commit_reservation( |
| 176 | + reservation_id, |
| 177 | + CommitRequest( |
| 178 | + idempotency_key=f"commit-{idempotency_key}", |
| 179 | + actual=Amount(unit=Unit.USD_MICROCENTS, amount=actual_cost), |
| 180 | + metrics=CyclesMetrics( |
| 181 | + tokens_input=response.usage.input_tokens, |
| 182 | + tokens_output=response.usage.output_tokens, |
| 183 | + model_version=response.model, |
| 184 | + custom={"turn": turn, "tool_use": response.stop_reason == "tool_use"}, |
| 185 | + ), |
| 186 | + ), |
| 187 | + ) |
| 188 | + |
| 189 | + # Process response |
| 190 | + if response.stop_reason == "end_turn": |
| 191 | + # Final text response |
| 192 | + for block in response.content: |
| 193 | + if block.type == "text": |
| 194 | + return block.text |
| 195 | + return "" |
| 196 | + |
| 197 | + if response.stop_reason == "tool_use": |
| 198 | + # Extract tool calls and execute them |
| 199 | + messages.append({"role": "assistant", "content": response.content}) |
| 200 | + tool_results = [] |
| 201 | + for block in response.content: |
| 202 | + if block.type == "tool_use": |
| 203 | + result = handle_tool_call(block.name, block.input) |
| 204 | + tool_results.append({ |
| 205 | + "type": "tool_result", |
| 206 | + "tool_use_id": block.id, |
| 207 | + "content": result, |
| 208 | + }) |
| 209 | + messages.append({"role": "user", "content": tool_results}) |
| 210 | + else: |
| 211 | + # Unexpected stop reason |
| 212 | + return f"Stopped with reason: {response.stop_reason}" |
| 213 | + |
| 214 | + if turn >= 5: |
| 215 | + return "Maximum turns reached." |
| 216 | + |
| 217 | + |
| 218 | +# --------------------------------------------------------------------------- |
| 219 | +# 4. Run it |
| 220 | +# --------------------------------------------------------------------------- |
| 221 | +def main() -> None: |
| 222 | + print("=== Simple message ===") |
| 223 | + try: |
| 224 | + result = send_message("What is budget authority in one sentence?") |
| 225 | + print(f"Response: {result['content']}") |
| 226 | + print(f"Tokens: {result['usage']}") |
| 227 | + except BudgetExceededError: |
| 228 | + print("Budget exhausted.") |
| 229 | + |
| 230 | + print("\n=== Tool-use conversation ===") |
| 231 | + answer = chat_with_tools("What's the weather like in San Francisco?") |
| 232 | + print(f"Answer: {answer}") |
| 233 | + |
| 234 | + |
| 235 | +if __name__ == "__main__": |
| 236 | + main() |