-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
176 lines (139 loc) · 5.01 KB
/
Copy pathexample.py
File metadata and controls
176 lines (139 loc) · 5.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
"""
Minimal usage examples for claude_code_runner.
Each function below demonstrates one mode. Pick the pattern that matches
how you want the agent to interact with your orchestrator and the user.
Run any of them directly:
python example.py piped
python example.py windowed
python example.py parallel
"""
import sys
import uuid
from pathlib import Path
from claude_code_runner import run_claude_task
HERE = Path(__file__).parent
OUTPUT = HERE / "example_output"
OUTPUT.mkdir(exist_ok=True)
def example_piped():
"""Quiet capture — agent runs headless, you get the result back."""
result_file = OUTPUT / "piped_result.json"
prompt = f"""
Pick three random adjectives and three random nouns. Combine them
into three made-up product names. Write JSON to {result_file}
with this shape:
{{
"products": [
{{"name": "...", "adjective": "...", "noun": "..."}}
]
}}
"""
result = run_claude_task(
prompt=prompt,
result_file=result_file,
timeout=300,
log_dir=OUTPUT / "sessions",
task_id="piped_demo",
)
if result["success"]:
print(f"Success in {result['elapsed']:.1f}s")
for p in result["result"]["products"]:
print(f" - {p['name']}")
else:
print(f"Failed: {result['error']}")
def example_windowed():
"""Visible console — watch the agent work in real time."""
result_file = OUTPUT / "windowed_result.json"
prompt = f"""
Read the Python file at {Path(__file__).resolve()} and write a
one-paragraph summary of what it does. Output JSON to
{result_file} with one key:
{{"summary": "..."}}
"""
result = run_claude_task(
prompt=prompt,
result_file=result_file,
timeout=600,
windowed=True,
log_dir=OUTPUT / "sessions",
task_id="windowed_demo",
title="Claude Code Runner — Demo",
)
if result["success"]:
print(f"Summary: {result['result']['summary']}")
else:
print(f"Failed: {result['error']}")
def example_parallel():
"""Run several agents at once, each on its own result file."""
from concurrent.futures import ThreadPoolExecutor
topics = ["caching", "concurrency", "error handling"]
def one_agent(topic):
result_file = OUTPUT / f"parallel_{topic.replace(' ', '_')}.json"
prompt = f"""
Write three best-practice tips about {topic} in Python.
Output JSON to {result_file}:
{{"topic": "{topic}", "tips": ["...", "...", "..."]}}
"""
return run_claude_task(
prompt=prompt,
result_file=result_file,
timeout=300,
log_dir=OUTPUT / "sessions",
task_id=f"parallel_{topic.replace(' ', '_')}",
)
with ThreadPoolExecutor(max_workers=3) as pool:
results = list(pool.map(one_agent, topics))
for r in results:
if r["success"]:
data = r["result"]
print(f"\n{data['topic']} ({r['elapsed']:.1f}s):")
for tip in data["tips"]:
print(f" - {tip}")
else:
print(f"Failed: {r['error']}")
def example_resume():
"""Spawn a session the user can take over later via resume mode.
The orchestrator picks the UUID up front and saves it. Later (could
be in the same process or a different run), you can reopen the same
session in a new window for the user to interact with.
"""
session_id = str(uuid.uuid4())
result_file = OUTPUT / f"resume_{session_id}.json"
print(f"Spawning session {session_id} (fire-and-forget)...")
spawn = run_claude_task(
prompt=f"""
Start exploring the directory at {HERE.resolve()}. When you have
a sense of the structure, write a short JSON summary to
{result_file}:
{{"top_level_items": ["..."], "notes": "..."}}
Then wait for further instructions from the user.
""",
result_file=result_file,
windowed=True,
wait_for_result=False,
session_id=session_id,
log_dir=OUTPUT / "sessions",
task_id=f"resume_demo_{session_id[:8]}",
)
print(f"Spawn status: {spawn['status']}, session: {spawn['session_id']}")
input("Press Enter once the agent has written its summary, "
"to reopen the session for you...")
print(f"Reopening session {session_id} in a new window...")
reopen = run_claude_task(
session_id=session_id,
windowed=True,
resume=True,
log_dir=OUTPUT / "sessions",
task_id=f"resume_demo_{session_id[:8]}",
)
print(f"Reopen status: {reopen['status']}")
EXAMPLES = {
"piped": example_piped,
"windowed": example_windowed,
"parallel": example_parallel,
"resume": example_resume,
}
if __name__ == "__main__":
if len(sys.argv) != 2 or sys.argv[1] not in EXAMPLES:
print(f"Usage: python example.py [{' | '.join(EXAMPLES)}]")
sys.exit(1)
EXAMPLES[sys.argv[1]]()