Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 37 additions & 77 deletions cookbook/copilot-sdk/python/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,41 +16,36 @@ You need to handle various error conditions like connection failures, timeouts,
## Basic try-except

```python
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())
```

## Handling specific error types

```python
import subprocess

try:
client.start()
await client.start()
except FileNotFoundError:
print("Copilot CLI not found. Please install it first.")
except ConnectionError:
Expand All @@ -62,31 +57,14 @@ except Exception as e:
## Timeout handling

```python
import signal
from contextlib import contextmanager

@contextmanager
def timeout(seconds):
def timeout_handler(signum, frame):
raise TimeoutError("Request timed out")

old_handler = signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
signal.signal(signal.SIGALRM, old_handler)

session = client.create_session(model="gpt-5")
session = await client.create_session(SessionConfig(model="gpt-5"))

try:
session.send(prompt="Complex question...")

# Wait with timeout (30 seconds)
with timeout(30):
session.wait_for_idle()

# send_and_wait accepts an optional timeout in seconds
response = await session.send_and_wait(
MessageOptions(prompt="Complex question..."),
timeout=30.0
)
print("Response received")
except TimeoutError:
print("Request timed out")
Expand All @@ -95,21 +73,15 @@ except TimeoutError:
## Aborting a request

```python
import threading

session = client.create_session(model="gpt-5")
session = await client.create_session(SessionConfig(model="gpt-5"))

# Start a request
session.send(prompt="Write a very long story...")
# Start a request (non-blocking send)
await session.send(MessageOptions(prompt="Write a very long story..."))

# Abort it after some condition
def abort_later():
import time
time.sleep(5)
session.abort()
print("Request aborted")

threading.Thread(target=abort_later).start()
await asyncio.sleep(5)
await session.abort()
print("Request aborted")
```

## Graceful shutdown
Expand All @@ -120,31 +92,19 @@ import sys

def signal_handler(sig, frame):
print("\nShutting down...")
errors = client.stop()
if errors:
print(f"Cleanup errors: {errors}")
try:
loop = asyncio.get_running_loop()
loop.create_task(client.stop())
except RuntimeError:
asyncio.run(client.stop())
sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
```

## Context manager for automatic cleanup

```python
from copilot import CopilotClient

with CopilotClient() as client:
client.start()
session = client.create_session(model="gpt-5")

# ... do work ...

# client.stop() is automatically called when exiting context
```

## Best practices

1. **Always clean up**: Use try-finally or context managers to ensure `stop()` is called
1. **Always clean up**: Use try-finally to ensure `await client.stop()` is called
2. **Handle connection errors**: The CLI might not be installed or running
3. **Set appropriate timeouts**: Long-running requests should have timeouts
3. **Set appropriate timeouts**: Use the `timeout` parameter on `send_and_wait()`
4. **Log errors**: Capture error details for debugging
75 changes: 44 additions & 31 deletions cookbook/copilot-sdk/python/managing-local-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,31 +16,40 @@ You have a folder with many files and want to organize them into subfolders base
## Example code

```python
from copilot import CopilotClient
import asyncio
import os

# Create and start client
client = CopilotClient()
client.start()

# Create session
session = client.create_session(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']}")

session.on(handle_event)

# Ask Copilot to organize files
target_folder = os.path.expanduser("~/Downloads")

session.send(prompt=f"""
from copilot import (
CopilotClient, SessionConfig, MessageOptions,
SessionEvent, SessionEventType,
)

async def main():
# Create and start client
client = CopilotClient()
await client.start()

# Create session
session = await client.create_session(SessionConfig(model="gpt-5"))

done = asyncio.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()

session.on(handle_event)

# Ask Copilot to organize files
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
Expand All @@ -49,11 +58,15 @@ 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.
""")
"""))

await done.wait()

session.wait_for_idle()
await session.destroy()
await client.stop()

client.stop()
if __name__ == "__main__":
asyncio.run(main())
```

## Grouping strategies
Expand Down Expand Up @@ -90,26 +103,26 @@ client.stop()
For safety, you can ask Copilot to only preview changes:

```python
session.send(prompt=f"""
await session.send(MessageOptions(prompt=f"""
Analyze files in "{target_folder}" and show me how you would organize them
by file type. DO NOT move any files - just show me the plan.
""")
"""))
```

## Custom grouping with AI analysis

Let Copilot determine the best grouping based on file content:

```python
session.send(prompt=f"""
await session.send(MessageOptions(prompt=f"""
Look at the files in "{target_folder}" and suggest a logical organization.
Consider:
- File names and what they might contain
- File types and their typical uses
- Date patterns that might indicate projects or events

Propose folder names that are descriptive and useful.
""")
"""))
```

## Safety considerations
Expand Down
65 changes: 35 additions & 30 deletions cookbook/copilot-sdk/python/multiple-sessions.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,59 +16,64 @@ You need to run multiple conversations in parallel, each with its own context an
## Python

```python
from copilot import CopilotClient

client = CopilotClient()
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")

# 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")

# 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?")

# Clean up all sessions
session1.destroy()
session2.destroy()
session3.destroy()
client.stop()
import asyncio
from copilot import CopilotClient, SessionConfig, MessageOptions

async def main():
client = CopilotClient()
await client.start()

# 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"))

# 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"))

# 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?"))

# Clean up all sessions
await session1.destroy()
await session2.destroy()
await session3.destroy()
await client.stop()

if __name__ == "__main__":
asyncio.run(main())
```

## Custom session IDs

Use custom IDs for easier tracking:

```python
session = client.create_session(
session = await client.create_session(SessionConfig(
session_id="user-123-chat",
model="gpt-5"
)
))

print(session.session_id) # "user-123-chat"
```

## Listing sessions

```python
sessions = client.list_sessions()
sessions = await client.list_sessions()
for session_info in sessions:
print(f"Session: {session_info['sessionId']}")
print(f"Session: {session_info.session_id}")
```

## Deleting sessions

```python
# Delete a specific session
client.delete_session("user-123-chat")
await client.delete_session("user-123-chat")
```

## Use cases
Expand Down
Loading