GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Add integration examples for OpenAI, Anthropic, LangChain, FastAPI, a… · runcycles/cycles-client-python@42270d4

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • README.md
  • examples
    • README.md
    • anthropic_integration.py
    • fastapi_integration.py
    • langchain_integration.py
    • openai_integration.py
    • streaming_usage.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎README.md‎

Copy file name to clipboardExpand all lines: README.md
+17Lines changed: 17 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,23 @@ def overdraft_func() -> str:
301301
- **Response metadata**: Access `request_id`, `rate_limit_remaining`, and `rate_limit_reset` on every response
302302
- **Environment config**: `CyclesConfig.from_env()` for 12-factor apps
303303

304+
## Examples
305+
306+
The [`examples/`](examples/) directory contains runnable integration examples:
307+
308+
| Example | Description |
309+
|---------|-------------|
310+
| [basic_usage.py](examples/basic_usage.py) | Programmatic reserve → commit lifecycle |
311+
| [decorator_usage.py](examples/decorator_usage.py) | `@cycles` decorator with estimates, caps, and metrics |
312+
| [async_usage.py](examples/async_usage.py) | Async client and async decorator |
313+
| [openai_integration.py](examples/openai_integration.py) | Guard OpenAI chat completions with budget checks |
314+
| [anthropic_integration.py](examples/anthropic_integration.py) | Guard Anthropic messages with per-tool budget tracking |
315+
| [streaming_usage.py](examples/streaming_usage.py) | Budget-managed streaming with token accumulation |
316+
| [fastapi_integration.py](examples/fastapi_integration.py) | FastAPI middleware, dependency injection, per-tenant budgets |
317+
| [langchain_integration.py](examples/langchain_integration.py) | LangChain callback handler for budget-aware agents |
318+
319+
See [examples/README.md](examples/README.md) for setup instructions.
320+
304321
## Development
305322

306323
```bash
Collapse file

‎examples/README.md‎

Copy file name to clipboard
+58Lines changed: 58 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Cycles Python Client Examples
2+
3+
Runnable examples demonstrating how to integrate the `runcycles` client into real-world Python applications.
4+
5+
## Prerequisites
6+
7+
1. A running Cycles server (see [Deploy the Full Stack](https://runcycles.github.io/docs/quickstart/deploying-the-full-cycles-stack))
8+
2. Set environment variables:
9+
10+
```bash
11+
export CYCLES_BASE_URL="http://localhost:7878"
12+
export CYCLES_API_KEY="your-api-key"
13+
export CYCLES_TENANT="acme"
14+
```
15+
16+
3. Install the client:
17+
18+
```bash
19+
pip install runcycles
20+
```
21+
22+
## Examples
23+
24+
| File | Description | Extra Dependencies |
25+
|------|-------------|-------------------|
26+
| [basic_usage.py](basic_usage.py) | Programmatic reserve → commit lifecycle | — |
27+
| [decorator_usage.py](decorator_usage.py) | `@cycles` decorator with estimates, caps, and metrics | — |
28+
| [async_usage.py](async_usage.py) | Async client and async decorator | — |
29+
| [openai_integration.py](openai_integration.py) | Guard OpenAI chat completions with budget checks | `openai` |
30+
| [anthropic_integration.py](anthropic_integration.py) | Guard Anthropic messages with per-tool budget tracking | `anthropic` |
31+
| [streaming_usage.py](streaming_usage.py) | Budget-managed streaming with token accumulation | `openai` |
32+
| [fastapi_integration.py](fastapi_integration.py) | FastAPI middleware, dependency injection, per-tenant budgets | `fastapi`, `uvicorn` |
33+
| [langchain_integration.py](langchain_integration.py) | LangChain callback handler for budget-aware agents | `langchain`, `langchain-openai` |
34+
35+
## Running
36+
37+
```bash
38+
# Basic examples (only need a Cycles server)
39+
python examples/basic_usage.py
40+
python examples/decorator_usage.py
41+
python examples/async_usage.py
42+
43+
# Integration examples (need additional API keys)
44+
export OPENAI_API_KEY="sk-..."
45+
python examples/openai_integration.py
46+
python examples/streaming_usage.py
47+
48+
export ANTHROPIC_API_KEY="sk-ant-..."
49+
python examples/anthropic_integration.py
50+
51+
# FastAPI (starts a server on port 8000)
52+
pip install fastapi uvicorn
53+
python examples/fastapi_integration.py
54+
55+
# LangChain
56+
pip install langchain langchain-openai
57+
python examples/langchain_integration.py
58+
```
Collapse file

‎examples/anthropic_integration.py‎

Copy file name to clipboard
+236Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
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()

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.