-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path04_skills_docgen.py
More file actions
142 lines (119 loc) · 4.43 KB
/
Copy path04_skills_docgen.py
File metadata and controls
142 lines (119 loc) · 4.43 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
#!/usr/bin/env python3
"""Document Generation using GitHub Copilot SDK Skills (SKILL.md).
See the tutorial for learning goals, prerequisites, and usage:
docs/copilot_sdk_tutorial/tutorials/04_skills.md (English)
docs/copilot_sdk_tutorial/tutorials/04_skills.ja.md (日本語)
"""
import argparse
import asyncio
import sys
from pathlib import Path
from _telemetry import add_telemetry_arguments, apply_telemetry_arguments, make_client
from copilot.generated.rpc import PermissionDecisionApproveOnce
from copilot.generated.session_events import (
SessionEventType,
PermissionRequest,
)
from copilot.session import (
PermissionRequestResult,
SystemMessageReplaceConfig,
)
# ---------------------------------------------------------------------------
# Sample Python code that needs docstrings generated
# ---------------------------------------------------------------------------
SAMPLE_CODE = """\
def calculate_discount(price: float, discount_pct: float) -> float:
if discount_pct < 0 or discount_pct > 100:
raise ValueError("discount_pct must be between 0 and 100")
return price * (1 - discount_pct / 100)
def batch_process(items: list[str], handler) -> list[str]:
results = []
for item in items:
try:
results.append(handler(item))
except Exception as exc:
results.append(f"ERROR: {exc}")
return results
"""
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Document Generation using GitHub Copilot SDK Skills",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
parser.add_argument(
"--skills-dir",
"-s",
default=str(Path(__file__).parent / "skills"),
help="Path to the skills directory containing SKILL.md files",
)
parser.add_argument(
"--cli-url",
"-c",
default=None,
help=(
"Optional Copilot CLI server URL (e.g. localhost:3000). "
"When omitted, the SDK launches the copilot CLI over stdio."
),
)
add_telemetry_arguments(parser)
return parser.parse_args()
async def run(cli_url: str | None, skills_dir: str) -> None:
skills_path = Path(skills_dir)
if not skills_path.exists():
print(
f"[Warning] Skills directory not found: {skills_dir}. "
"Running without skills.",
file=sys.stderr,
)
resolved_skills_dir: str | None = None
else:
resolved_skills_dir = str(skills_path.resolve())
print(f"[Info] Loading skills from: {resolved_skills_dir}")
def approve_all(
request: PermissionRequest,
context: dict,
) -> PermissionRequestResult:
return PermissionDecisionApproveOnce()
client = make_client(cli_url)
await client.start()
session_config: dict = {
"on_permission_request": approve_all,
"tools": [],
"streaming": True,
"system_message": SystemMessageReplaceConfig(
mode="replace",
content=(
"You are a Python documentation specialist. "
"Generate clear, complete Google-style docstrings for all functions "
"in the provided code. Return only the updated code with docstrings added."
),
),
}
if resolved_skills_dir:
session_config["skill_directories"] = [resolved_skills_dir]
session = await client.create_session(**session_config)
print("=== Generating Documentation ===\n")
def on_event(event) -> None: # noqa: ANN001
if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
print(event.data.delta_content, end="", flush=True)
elif event.type == SessionEventType.TOOL_EXECUTION_START:
print(f"\n[Skill] Running: {event.data.tool_name}", file=sys.stderr)
elif event.type == SessionEventType.SESSION_ERROR:
print(f"\n[Error] {event.data.message}", file=sys.stderr)
session.on(on_event)
prompt = (
f"Please add Google-style docstrings to all functions in the following code:\n\n"
f"```python\n{SAMPLE_CODE}\n```"
)
await session.send_and_wait(prompt, timeout=300)
print("\n\n=== Done ===")
def main() -> None:
args = parse_args()
apply_telemetry_arguments(args)
try:
asyncio.run(run(args.cli_url, args.skills_dir))
except KeyboardInterrupt:
print("\nBye!")
if __name__ == "__main__":
main()