-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path01_chat_bot.py
More file actions
148 lines (123 loc) · 4.22 KB
/
Copy path01_chat_bot.py
File metadata and controls
148 lines (123 loc) · 4.22 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
#!/usr/bin/env python3
"""CLI Chatbot using the GitHub Copilot SDK.
See the tutorial for learning goals, prerequisites, and usage:
docs/copilot_sdk_tutorial/tutorials/01_chat_bot.md (English)
docs/copilot_sdk_tutorial/tutorials/01_chat_bot.ja.md (日本語)
"""
import argparse
import asyncio
import sys
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,
SystemMessageAppendConfig,
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="CLI Chatbot using the GitHub Copilot SDK",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
parser.add_argument(
"--prompt",
"-p",
default="Hello, Copilot! What can you do?",
help="Prompt to send (single-shot mode)",
)
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."
),
)
parser.add_argument(
"--loop",
"-l",
action="store_true",
help="Run in interactive chat loop mode (Ctrl+C to exit)",
)
add_telemetry_arguments(parser)
return parser.parse_args()
async def run_single(cli_url: str | None, prompt: str) -> None:
"""Send a single prompt and print the response."""
def approve_all(
request: PermissionRequest,
context: dict,
) -> PermissionRequestResult:
return PermissionDecisionApproveOnce()
client = make_client(cli_url)
await client.start()
session = await client.create_session(
on_permission_request=approve_all,
tools=[],
streaming=True,
system_message=SystemMessageAppendConfig(
content="You are a helpful assistant."
),
)
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.SESSION_ERROR:
print(f"\n[Error] {event.data.message}", file=sys.stderr)
session.on(on_event)
reply = await session.send_and_wait(prompt, timeout=300)
content = getattr(reply.data, "content", None) if reply else None
# Ensure a newline after streaming output
print()
if not content:
print("(no response)", file=sys.stderr)
async def run_loop(cli_url: str | None) -> None:
"""Run an interactive chat loop."""
def approve_all(
request: PermissionRequest,
context: dict,
) -> PermissionRequestResult:
return PermissionDecisionApproveOnce()
client = make_client(cli_url)
await client.start()
session = await client.create_session(
on_permission_request=approve_all,
tools=[],
streaming=True,
system_message=SystemMessageAppendConfig(
content="You are a helpful assistant."
),
)
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.SESSION_ERROR:
print(f"\n[Error] {event.data.message}", file=sys.stderr)
session.on(on_event)
print("Chat with Copilot — type your message and press Enter (Ctrl+C to quit)\n")
while True:
try:
user_input = input("You: ").strip()
except EOFError:
break
if not user_input:
continue
print("Copilot: ", end="")
await session.send_and_wait(user_input, timeout=300)
print()
def main() -> None:
args = parse_args()
apply_telemetry_arguments(args)
try:
if args.loop:
asyncio.run(run_loop(args.cli_url))
else:
asyncio.run(run_single(args.cli_url, args.prompt))
except KeyboardInterrupt:
print("\nBye!")
if __name__ == "__main__":
main()