mirror of
https://github.com/github/awesome-copilot.git
synced 2026-02-21 19:05:13 +00:00
Fix Python cookbook recipes to use correct async SDK API
All 5 Python recipes and their markdown docs used a synchronous, kwargs-based API that doesn't match the real github-copilot-sdk: - client.start() -> await client.start() (all methods are async) - create_session(model=...) -> create_session(SessionConfig(model=...)) - session.send(prompt=...) -> session.send(MessageOptions(prompt=...)) - session.wait_for_idle() -> session.send_and_wait() (wait_for_idle doesn't exist) - event['type']/event['data']['content'] -> event.type/event.data.content - All code wrapped in async def main() + asyncio.run(main()) Verified all imports resolve against github-copilot-sdk.
This commit is contained in:
@@ -1,28 +1,25 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from copilot import CopilotClient
|
||||
import asyncio
|
||||
from copilot import CopilotClient, SessionConfig, MessageOptions
|
||||
|
||||
client = CopilotClient()
|
||||
async def main():
|
||||
client = CopilotClient()
|
||||
|
||||
try:
|
||||
client.start()
|
||||
session = client.create_session(model="gpt-5")
|
||||
try:
|
||||
await client.start()
|
||||
session = await client.create_session(SessionConfig(model="gpt-5"))
|
||||
|
||||
response = None
|
||||
def handle_message(event):
|
||||
nonlocal response
|
||||
if event["type"] == "assistant.message":
|
||||
response = event["data"]["content"]
|
||||
response = await session.send_and_wait(MessageOptions(prompt="Hello!"))
|
||||
|
||||
session.on(handle_message)
|
||||
session.send(prompt="Hello!")
|
||||
session.wait_for_idle()
|
||||
if response:
|
||||
print(response.data.content)
|
||||
|
||||
if response:
|
||||
print(response)
|
||||
await session.destroy()
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
finally:
|
||||
await client.stop()
|
||||
|
||||
session.destroy()
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
finally:
|
||||
client.stop()
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
||||
@@ -1,31 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from copilot import CopilotClient
|
||||
import asyncio
|
||||
import os
|
||||
from copilot import (
|
||||
CopilotClient, SessionConfig, MessageOptions,
|
||||
SessionEvent, SessionEventType,
|
||||
)
|
||||
|
||||
# Create and start client
|
||||
client = CopilotClient()
|
||||
client.start()
|
||||
async def main():
|
||||
# Create and start client
|
||||
client = CopilotClient()
|
||||
await client.start()
|
||||
|
||||
# Create session
|
||||
session = client.create_session(model="gpt-5")
|
||||
# Create session
|
||||
session = await client.create_session(SessionConfig(model="gpt-5"))
|
||||
|
||||
# Event handler
|
||||
def handle_event(event):
|
||||
if event["type"] == "assistant.message":
|
||||
print(f"\nCopilot: {event['data']['content']}")
|
||||
elif event["type"] == "tool.execution_start":
|
||||
print(f" → Running: {event['data']['toolName']}")
|
||||
elif event["type"] == "tool.execution_complete":
|
||||
print(f" ✓ Completed: {event['data']['toolCallId']}")
|
||||
done = asyncio.Event()
|
||||
|
||||
session.on(handle_event)
|
||||
# Event handler
|
||||
def handle_event(event: SessionEvent):
|
||||
if event.type == SessionEventType.ASSISTANT_MESSAGE:
|
||||
print(f"\nCopilot: {event.data.content}")
|
||||
elif event.type == SessionEventType.TOOL_EXECUTION_START:
|
||||
print(f" → Running: {event.data.tool_name}")
|
||||
elif event.type == SessionEventType.TOOL_EXECUTION_COMPLETE:
|
||||
print(f" ✓ Completed: {event.data.tool_call_id}")
|
||||
elif event.type.value == "session.idle":
|
||||
done.set()
|
||||
|
||||
# Ask Copilot to organize files
|
||||
# Change this to your target folder
|
||||
target_folder = os.path.expanduser("~/Downloads")
|
||||
session.on(handle_event)
|
||||
|
||||
session.send(prompt=f"""
|
||||
# Ask Copilot to organize files
|
||||
# Change this to your target folder
|
||||
target_folder = os.path.expanduser("~/Downloads")
|
||||
|
||||
await session.send(MessageOptions(prompt=f"""
|
||||
Analyze the files in "{target_folder}" and organize them into subfolders.
|
||||
|
||||
1. First, list all files and their metadata
|
||||
@@ -34,9 +43,12 @@ Analyze the files in "{target_folder}" and organize them into subfolders.
|
||||
4. Move each file to its appropriate subfolder
|
||||
|
||||
Please confirm before moving any files.
|
||||
""")
|
||||
"""))
|
||||
|
||||
session.wait_for_idle()
|
||||
await done.wait()
|
||||
|
||||
session.destroy()
|
||||
client.stop()
|
||||
await session.destroy()
|
||||
await client.stop()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
||||
@@ -1,35 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from copilot import CopilotClient
|
||||
import asyncio
|
||||
from copilot import CopilotClient, SessionConfig, MessageOptions
|
||||
|
||||
client = CopilotClient()
|
||||
client.start()
|
||||
async def main():
|
||||
client = CopilotClient()
|
||||
await client.start()
|
||||
|
||||
# Create multiple independent sessions
|
||||
session1 = client.create_session(model="gpt-5")
|
||||
session2 = client.create_session(model="gpt-5")
|
||||
session3 = client.create_session(model="claude-sonnet-4.5")
|
||||
# Create multiple independent sessions
|
||||
session1 = await client.create_session(SessionConfig(model="gpt-5"))
|
||||
session2 = await client.create_session(SessionConfig(model="gpt-5"))
|
||||
session3 = await client.create_session(SessionConfig(model="claude-sonnet-4.5"))
|
||||
|
||||
print("Created 3 independent sessions")
|
||||
print("Created 3 independent sessions")
|
||||
|
||||
# Each session maintains its own conversation history
|
||||
session1.send(prompt="You are helping with a Python project")
|
||||
session2.send(prompt="You are helping with a TypeScript project")
|
||||
session3.send(prompt="You are helping with a Go project")
|
||||
# Each session maintains its own conversation history
|
||||
await session1.send(MessageOptions(prompt="You are helping with a Python project"))
|
||||
await session2.send(MessageOptions(prompt="You are helping with a TypeScript project"))
|
||||
await session3.send(MessageOptions(prompt="You are helping with a Go project"))
|
||||
|
||||
print("Sent initial context to all sessions")
|
||||
print("Sent initial context to all sessions")
|
||||
|
||||
# Follow-up messages stay in their respective contexts
|
||||
session1.send(prompt="How do I create a virtual environment?")
|
||||
session2.send(prompt="How do I set up tsconfig?")
|
||||
session3.send(prompt="How do I initialize a module?")
|
||||
# Follow-up messages stay in their respective contexts
|
||||
await session1.send(MessageOptions(prompt="How do I create a virtual environment?"))
|
||||
await session2.send(MessageOptions(prompt="How do I set up tsconfig?"))
|
||||
await session3.send(MessageOptions(prompt="How do I initialize a module?"))
|
||||
|
||||
print("Sent follow-up questions to each session")
|
||||
print("Sent follow-up questions to each session")
|
||||
|
||||
# Clean up all sessions
|
||||
session1.destroy()
|
||||
session2.destroy()
|
||||
session3.destroy()
|
||||
client.stop()
|
||||
# Clean up all sessions
|
||||
await session1.destroy()
|
||||
await session2.destroy()
|
||||
await session3.destroy()
|
||||
await client.stop()
|
||||
|
||||
print("All sessions destroyed successfully")
|
||||
print("All sessions destroyed successfully")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
||||
@@ -1,36 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from copilot import CopilotClient
|
||||
import asyncio
|
||||
from copilot import CopilotClient, SessionConfig, MessageOptions
|
||||
|
||||
client = CopilotClient()
|
||||
client.start()
|
||||
async def main():
|
||||
client = CopilotClient()
|
||||
await client.start()
|
||||
|
||||
# Create session with a memorable ID
|
||||
session = client.create_session(
|
||||
session_id="user-123-conversation",
|
||||
model="gpt-5",
|
||||
)
|
||||
# Create session with a memorable ID
|
||||
session = await client.create_session(SessionConfig(
|
||||
session_id="user-123-conversation",
|
||||
model="gpt-5",
|
||||
))
|
||||
|
||||
session.send(prompt="Let's discuss TypeScript generics")
|
||||
print(f"Session created: {session.session_id}")
|
||||
await session.send_and_wait(MessageOptions(prompt="Let's discuss TypeScript generics"))
|
||||
print(f"Session created: {session.session_id}")
|
||||
|
||||
# Destroy session but keep data on disk
|
||||
session.destroy()
|
||||
print("Session destroyed (state persisted)")
|
||||
# Destroy session but keep data on disk
|
||||
await session.destroy()
|
||||
print("Session destroyed (state persisted)")
|
||||
|
||||
# Resume the previous session
|
||||
resumed = client.resume_session("user-123-conversation")
|
||||
print(f"Resumed: {resumed.session_id}")
|
||||
# Resume the previous session
|
||||
resumed = await client.resume_session("user-123-conversation")
|
||||
print(f"Resumed: {resumed.session_id}")
|
||||
|
||||
resumed.send(prompt="What were we discussing?")
|
||||
await resumed.send_and_wait(MessageOptions(prompt="What were we discussing?"))
|
||||
|
||||
# List sessions
|
||||
sessions = client.list_sessions()
|
||||
print("Sessions:", [s["sessionId"] for s in sessions])
|
||||
# List sessions
|
||||
sessions = await client.list_sessions()
|
||||
print("Sessions:", [s.session_id for s in sessions])
|
||||
|
||||
# Delete session permanently
|
||||
client.delete_session("user-123-conversation")
|
||||
print("Session deleted")
|
||||
# Delete session permanently
|
||||
await client.delete_session("user-123-conversation")
|
||||
print("Session deleted")
|
||||
|
||||
resumed.destroy()
|
||||
client.stop()
|
||||
await resumed.destroy()
|
||||
await client.stop()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import asyncio
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
import re
|
||||
from copilot import CopilotClient
|
||||
from copilot import (
|
||||
CopilotClient, SessionConfig, MessageOptions,
|
||||
SessionEvent, SessionEventType,
|
||||
)
|
||||
|
||||
# ============================================================================
|
||||
# Git & GitHub Detection
|
||||
@@ -60,7 +64,7 @@ def prompt_for_repo():
|
||||
# Main Application
|
||||
# ============================================================================
|
||||
|
||||
def main():
|
||||
async def main():
|
||||
print("🔍 PR Age Chart Generator\n")
|
||||
|
||||
# Determine the repository
|
||||
@@ -88,11 +92,11 @@ def main():
|
||||
|
||||
owner, repo_name = repo.split("/", 1)
|
||||
|
||||
# Create Copilot client - no custom tools needed!
|
||||
client = CopilotClient(log_level="error")
|
||||
client.start()
|
||||
# Create Copilot client
|
||||
client = CopilotClient()
|
||||
await client.start()
|
||||
|
||||
session = client.create_session(
|
||||
session = await client.create_session(SessionConfig(
|
||||
model="gpt-5",
|
||||
system_message={
|
||||
"content": f"""
|
||||
@@ -109,30 +113,34 @@ The current working directory is: {os.getcwd()}
|
||||
</instructions>
|
||||
"""
|
||||
}
|
||||
)
|
||||
))
|
||||
|
||||
done = asyncio.Event()
|
||||
|
||||
# Set up event handling
|
||||
def handle_event(event):
|
||||
if event["type"] == "assistant.message":
|
||||
print(f"\n🤖 {event['data']['content']}\n")
|
||||
elif event["type"] == "tool.execution_start":
|
||||
print(f" ⚙️ {event['data']['toolName']}")
|
||||
def handle_event(event: SessionEvent):
|
||||
if event.type == SessionEventType.ASSISTANT_MESSAGE:
|
||||
print(f"\n🤖 {event.data.content}\n")
|
||||
elif event.type == SessionEventType.TOOL_EXECUTION_START:
|
||||
print(f" ⚙️ {event.data.tool_name}")
|
||||
elif event.type.value == "session.idle":
|
||||
done.set()
|
||||
|
||||
session.on(handle_event)
|
||||
|
||||
# Initial prompt - let Copilot figure out the details
|
||||
print("\n📊 Starting analysis...\n")
|
||||
|
||||
session.send(prompt=f"""
|
||||
await session.send(MessageOptions(prompt=f"""
|
||||
Fetch the open pull requests for {owner}/{repo_name} from the last week.
|
||||
Calculate the age of each PR in days.
|
||||
Then generate a bar chart image showing the distribution of PR ages
|
||||
(group them into sensible buckets like <1 day, 1-3 days, etc.).
|
||||
Save the chart as "pr-age-chart.png" in the current directory.
|
||||
Finally, summarize the PR health - average age, oldest PR, and how many might be considered stale.
|
||||
""")
|
||||
"""))
|
||||
|
||||
session.wait_for_idle()
|
||||
await done.wait()
|
||||
|
||||
# Interactive loop
|
||||
print("\n💡 Ask follow-up questions or type \"exit\" to quit.\n")
|
||||
@@ -151,11 +159,12 @@ The current working directory is: {os.getcwd()}
|
||||
break
|
||||
|
||||
if user_input:
|
||||
session.send(prompt=user_input)
|
||||
session.wait_for_idle()
|
||||
done.clear()
|
||||
await session.send(MessageOptions(prompt=user_input))
|
||||
await done.wait()
|
||||
|
||||
session.destroy()
|
||||
client.stop()
|
||||
await session.destroy()
|
||||
await client.stop()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
asyncio.run(main())
|
||||
|
||||
Reference in New Issue
Block a user