docs: update go sdk examples (#1393)

Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
This commit is contained in:
Carlos Alexandro Becker
2026-04-14 20:50:39 -03:00
committed by GitHub
parent 66a60afe70
commit aaf86f6055
16 changed files with 122 additions and 156 deletions

View File

@@ -1,6 +0,0 @@
github.com/github/copilot-sdk/go v0.1.18 h1:S1ocOfTKxiNGtj+/qp4z+RZeOr9hniqy3UqIIYZxsuQ=
github.com/github/copilot-sdk/go v0.1.18/go.mod h1:0SYT+64k347IDT0Trn4JHVFlUhPtGSE6ab479tU/+tY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=

View File

@@ -75,13 +75,12 @@ func main() {
}
defer client.Stop()
streaming := true
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "claude-opus-4.6",
Streaming: &streaming,
McpServers: map[string]interface{}{
"playwright": map[string]interface{}{
Streaming: true,
MCPServers: map[string]copilot.MCPServerConfig{
"playwright": {
"type": "local",
"command": "npx",
"args": []string{"@playwright/mcp@latest"},
@@ -92,26 +91,22 @@ func main() {
if err != nil {
log.Fatal(err)
}
defer session.Destroy()
defer session.Disconnect()
// Set up streaming event handling
done := make(chan struct{}, 1)
session.On(func(event copilot.SessionEvent) {
switch event.Type {
case "assistant.message.delta":
if event.Data.DeltaContent != nil {
fmt.Print(*event.Data.DeltaContent)
}
case "session.idle":
switch d := event.Data.(type) {
case *copilot.AssistantMessageDeltaData:
fmt.Print(d.DeltaContent)
case *copilot.SessionIdleData:
select {
case done <- struct{}{}:
default:
}
case "session.error":
if event.Data.Message != nil {
fmt.Printf("\nError: %s\n", *event.Data.Message)
}
case *copilot.SessionErrorData:
fmt.Printf("\nError: %s\n", d.Message)
select {
case done <- struct{}{}:
default:
@@ -202,7 +197,7 @@ func main() {
## How it works
1. **Playwright MCP server**: Configures a local MCP server running `@playwright/mcp` to provide browser automation tools
2. **Streaming output**: Uses `Streaming: &streaming` and `assistant.message.delta` events for real-time token-by-token output
2. **Streaming output**: Uses `Streaming: true` and `AssistantMessageDeltaData` events for real-time token-by-token output
3. **Accessibility snapshot**: Playwright's `browser_snapshot` tool captures the full accessibility tree of the page
4. **Structured report**: The prompt engineers a consistent WCAG-aligned report format with emoji severity indicators
5. **Test generation**: Optionally detects the project language and generates Playwright accessibility tests
@@ -216,8 +211,8 @@ The recipe configures a local MCP server that runs alongside the session:
```go
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
McpServers: map[string]interface{}{
"playwright": map[string]interface{}{
MCPServers: map[string]copilot.MCPServerConfig{
"playwright": {
"type": "local",
"command": "npx",
"args": []string{"@playwright/mcp@latest"},
@@ -235,12 +230,10 @@ Unlike `SendAndWait`, this recipe uses streaming for real-time output:
```go
session.On(func(event copilot.SessionEvent) {
switch event.Type {
case "assistant.message.delta":
if event.Data.DeltaContent != nil {
fmt.Print(*event.Data.DeltaContent)
}
case "session.idle":
switch d := event.Data.(type) {
case *copilot.AssistantMessageDeltaData:
fmt.Print(d.DeltaContent)
case *copilot.SessionIdleData:
done <- struct{}{}
}
})

View File

@@ -35,12 +35,12 @@ func main() {
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Model: "gpt-5.4",
})
if err != nil {
log.Fatalf("Failed to create session: %v", err)
}
defer session.Destroy()
defer session.Disconnect()
result, err := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Hello!"})
if err != nil {
@@ -48,8 +48,10 @@ func main() {
return
}
if result != nil && result.Data.Content != nil {
fmt.Println(*result.Data.Content)
if result != nil {
if d, ok := result.Data.(*copilot.AssistantMessageData); ok {
fmt.Println(d.Content)
}
}
}
```
@@ -180,12 +182,12 @@ func doWork() error {
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Model: "gpt-5.4",
})
if err != nil {
return fmt.Errorf("failed to create session: %w", err)
}
defer session.Destroy()
defer session.Disconnect()
// ... do work ...

View File

@@ -39,28 +39,22 @@ func main() {
// Create session
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Model: "gpt-5.4",
})
if err != nil {
log.Fatal(err)
}
defer session.Destroy()
defer session.Disconnect()
// Event handler
session.On(func(event copilot.SessionEvent) {
switch event.Type {
case "assistant.message":
if event.Data.Content != nil {
fmt.Printf("\nCopilot: %s\n", *event.Data.Content)
}
case "tool.execution_start":
if event.Data.ToolName != nil {
fmt.Printf(" → Running: %s\n", *event.Data.ToolName)
}
case "tool.execution_complete":
if event.Data.ToolName != nil {
fmt.Printf(" ✓ Completed: %s\n", *event.Data.ToolName)
}
switch d := event.Data.(type) {
case *copilot.AssistantMessageData:
fmt.Printf("\nCopilot: %s\n", d.Content)
case *copilot.ToolExecutionStartData:
fmt.Printf(" → Running: %s\n", d.ToolName)
case *copilot.ToolExecutionCompleteData:
fmt.Printf(" ✓ Completed (success=%v)\n", d.Success)
}
})

View File

@@ -36,30 +36,30 @@ func main() {
// Create multiple independent sessions
session1, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Model: "gpt-5.4",
})
if err != nil {
log.Fatal(err)
}
defer session1.Destroy()
defer session1.Disconnect()
session2, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Model: "gpt-5.4",
})
if err != nil {
log.Fatal(err)
}
defer session2.Destroy()
defer session2.Disconnect()
session3, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "claude-sonnet-4.5",
Model: "claude-sonnet-4.6",
})
if err != nil {
log.Fatal(err)
}
defer session3.Destroy()
defer session3.Disconnect()
// Each session maintains its own conversation history
session1.Send(ctx, copilot.MessageOptions{Prompt: "You are helping with a Python project"})
@@ -81,7 +81,7 @@ Use custom IDs for easier tracking:
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
SessionID: "user-123-chat",
Model: "gpt-5",
Model: "gpt-5.4",
})
if err != nil {
log.Fatal(err)
@@ -93,7 +93,7 @@ fmt.Println(session.SessionID) // "user-123-chat"
## Listing sessions
```go
sessions, err := client.ListSessions(ctx)
sessions, err := client.ListSessions(ctx, nil)
if err != nil {
log.Fatal(err)
}

View File

@@ -34,7 +34,7 @@ func main() {
session, _ := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
SessionID: "user-123-conversation",
Model: "gpt-5",
Model: "gpt-5.4",
})
session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Let's discuss TypeScript generics"})
@@ -42,8 +42,8 @@ func main() {
// Session ID is preserved
fmt.Println(session.SessionID)
// Destroy session but keep data on disk
session.Destroy()
// Disconnect session but keep data on disk
session.Disconnect()
}
```
@@ -61,13 +61,13 @@ session, _ := client.ResumeSession(ctx, "user-123-conversation", &copilot.Resume
// Previous context is restored
session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "What were we discussing?"})
session.Destroy()
session.Disconnect()
```
### Listing available sessions
```go
sessions, _ := client.ListSessions(ctx)
sessions, _ := client.ListSessions(ctx, nil)
for _, s := range sessions {
fmt.Println("Session:", s.SessionID)
}
@@ -85,8 +85,8 @@ client.DeleteSession(ctx, "user-123-conversation")
```go
messages, _ := session.GetMessages(ctx)
for _, msg := range messages {
if msg.Data.Content != nil {
fmt.Printf("[%s] %s\n", msg.Type, *msg.Data.Content)
if d, ok := msg.Data.(*copilot.AssistantMessageData); ok {
fmt.Printf("[assistant.message] %s\n", d.Content)
}
}
```

View File

@@ -139,7 +139,7 @@ func main() {
cwd, _ := os.Getwd()
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Model: "gpt-5.4",
SystemMessage: &copilot.SystemMessageConfig{
Content: fmt.Sprintf(`
<context>
@@ -159,19 +159,15 @@ The current working directory is: %s
if err != nil {
log.Fatal(err)
}
defer session.Destroy()
defer session.Disconnect()
// Set up event handling
session.On(func(event copilot.SessionEvent) {
switch event.Type {
case "assistant.message":
if event.Data.Content != nil {
fmt.Printf("\n🤖 %s\n\n", *event.Data.Content)
}
case "tool.execution_start":
if event.Data.ToolName != nil {
fmt.Printf(" ⚙️ %s\n", *event.Data.ToolName)
}
switch d := event.Data.(type) {
case *copilot.AssistantMessageData:
fmt.Printf("\n🤖 %s\n\n", d.Content)
case *copilot.ToolExecutionStartData:
fmt.Printf(" ⚙️ %s\n", d.ToolName)
}
})

View File

@@ -71,7 +71,7 @@ func ralphLoop(ctx context.Context, promptFile string, maxIterations int) error
// Fresh session each iteration — context isolation is the point
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5.1-codex-mini",
Model: "gpt-5.3-codex",
})
if err != nil {
return err
@@ -80,7 +80,7 @@ func ralphLoop(ctx context.Context, promptFile string, maxIterations int) error
_, err = session.SendAndWait(ctx, copilot.MessageOptions{
Prompt: string(prompt),
})
session.Destroy()
session.Disconnect()
if err != nil {
return err
}
@@ -146,10 +146,10 @@ func ralphLoop(ctx context.Context, mode string, maxIterations int) error {
fmt.Printf("\n=== Iteration %d/%d ===\n", i, maxIterations)
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
Model: "gpt-5.1-codex-mini",
Model: "gpt-5.3-codex",
WorkingDirectory: cwd,
OnPermissionRequest: func(_ copilot.PermissionRequest, _ map[string]string) copilot.PermissionRequestResult {
return copilot.PermissionRequestResult{Kind: "approved"}
OnPermissionRequest: func(_ copilot.PermissionRequest, _ copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
return copilot.PermissionRequestResult{Kind: "approved"}, nil
},
})
if err != nil {
@@ -157,16 +157,16 @@ func ralphLoop(ctx context.Context, mode string, maxIterations int) error {
}
// Log tool usage for visibility
session.On(func(event copilot.Event) {
if toolExecution, ok := event.(copilot.ToolExecutionStartEvent); ok {
fmt.Printf(" ⚙ %s\n", toolExecution.Data.ToolName)
session.On(func(event copilot.SessionEvent) {
if d, ok := event.Data.(*copilot.ToolExecutionStartData); ok {
fmt.Printf(" ⚙ %s\n", d.ToolName)
}
})
_, err = session.SendAndWait(ctx, copilot.MessageOptions{
Prompt: string(prompt),
})
session.Destroy()
session.Disconnect()
if err != nil {
return err
}

View File

@@ -43,13 +43,12 @@ func main() {
}
defer client.Stop()
streaming := true
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "claude-opus-4.6",
Streaming: &streaming,
McpServers: map[string]interface{}{
"playwright": map[string]interface{}{
Model: "claude-opus-4.6",
Streaming: true,
MCPServers: map[string]copilot.MCPServerConfig{
"playwright": {
"type": "local",
"command": "npx",
"args": []string{"@playwright/mcp@latest"},
@@ -60,26 +59,22 @@ func main() {
if err != nil {
log.Fatal(err)
}
defer session.Destroy()
defer session.Disconnect()
// Set up streaming event handling
done := make(chan struct{}, 1)
session.On(func(event copilot.SessionEvent) {
switch event.Type {
case "assistant.message.delta":
if event.Data.DeltaContent != nil {
fmt.Print(*event.Data.DeltaContent)
}
case "session.idle":
switch d := event.Data.(type) {
case *copilot.AssistantMessageDeltaData:
fmt.Print(d.DeltaContent)
case *copilot.SessionIdleData:
select {
case done <- struct{}{}:
default:
}
case "session.error":
if event.Data.Message != nil {
fmt.Printf("\nError: %s\n", *event.Data.Message)
}
case *copilot.SessionErrorData:
fmt.Printf("\nError: %s\n", d.Message)
select {
case done <- struct{}{}:
default:

View File

@@ -19,12 +19,12 @@ func main() {
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Model: "gpt-5.4",
})
if err != nil {
log.Fatalf("Failed to create session: %v", err)
}
defer session.Destroy()
defer session.Disconnect()
result, err := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Hello!"})
if err != nil {
@@ -32,7 +32,9 @@ func main() {
return
}
if result != nil && result.Data.Content != nil {
fmt.Println(*result.Data.Content)
if result != nil {
if d, ok := result.Data.(*copilot.AssistantMessageData); ok {
fmt.Println(d.Content)
}
}
}

View File

@@ -23,28 +23,22 @@ func main() {
// Create session
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Model: "gpt-5.4",
})
if err != nil {
log.Fatal(err)
}
defer session.Destroy()
defer session.Disconnect()
// Event handler
session.On(func(event copilot.SessionEvent) {
switch event.Type {
case "assistant.message":
if event.Data.Content != nil {
fmt.Printf("\nCopilot: %s\n", *event.Data.Content)
}
case "tool.execution_start":
if event.Data.ToolName != nil {
fmt.Printf(" → Running: %s\n", *event.Data.ToolName)
}
case "tool.execution_complete":
if event.Data.ToolName != nil {
fmt.Printf(" ✓ Completed: %s\n", *event.Data.ToolName)
}
switch d := event.Data.(type) {
case *copilot.AssistantMessageData:
fmt.Printf("\nCopilot: %s\n", d.Content)
case *copilot.ToolExecutionStartData:
fmt.Printf(" → Running: %s\n", d.ToolName)
case *copilot.ToolExecutionCompleteData:
fmt.Printf(" ✓ Completed (success=%v)\n", d.Success)
}
})

View File

@@ -20,30 +20,30 @@ func main() {
// Create multiple independent sessions
session1, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Model: "gpt-5.4",
})
if err != nil {
log.Fatal(err)
}
defer session1.Destroy()
defer session1.Disconnect()
session2, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Model: "gpt-5.4",
})
if err != nil {
log.Fatal(err)
}
defer session2.Destroy()
defer session2.Disconnect()
session3, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "claude-sonnet-4.5",
Model: "claude-sonnet-4.6",
})
if err != nil {
log.Fatal(err)
}
defer session3.Destroy()
defer session3.Disconnect()
fmt.Println("Created 3 independent sessions")
@@ -60,5 +60,5 @@ func main() {
session3.Send(ctx, copilot.MessageOptions{Prompt: "How do I initialize a module?"})
fmt.Println("Sent follow-up questions to each session")
fmt.Println("All sessions will be destroyed on exit")
fmt.Println("All sessions will be disconnected on exit")
}

View File

@@ -19,8 +19,8 @@ func main() {
// Create session with a memorable ID
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
SessionID: "user-123-conversation",
Model: "gpt-5",
SessionID: "user-123-conversation",
Model: "gpt-5.4",
})
if err != nil {
log.Fatal(err)
@@ -32,9 +32,9 @@ func main() {
}
fmt.Printf("Session created: %s\n", session.SessionID)
// Destroy session but keep data on disk
session.Destroy()
fmt.Println("Session destroyed (state persisted)")
// Disconnect session but keep data on disk
session.Disconnect()
fmt.Println("Session disconnected (state persisted)")
// Resume the previous session
resumed, err := client.ResumeSession(ctx, "user-123-conversation", &copilot.ResumeSessionConfig{OnPermissionRequest: copilot.PermissionHandler.ApproveAll})
@@ -49,7 +49,7 @@ func main() {
}
// List sessions
sessions, err := client.ListSessions(ctx)
sessions, err := client.ListSessions(ctx, nil)
if err != nil {
log.Fatal(err)
}
@@ -65,5 +65,5 @@ func main() {
}
fmt.Println("Session deleted")
resumed.Destroy()
resumed.Disconnect()
}

View File

@@ -103,7 +103,7 @@ func main() {
cwd, _ := os.Getwd()
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
Model: "gpt-5.4",
SystemMessage: &copilot.SystemMessageConfig{
Content: fmt.Sprintf(`
<context>
@@ -123,19 +123,15 @@ The current working directory is: %s
if err != nil {
log.Fatal(err)
}
defer session.Destroy()
defer session.Disconnect()
// Set up event handling
session.On(func(event copilot.SessionEvent) {
switch event.Type {
case "assistant.message":
if event.Data.Content != nil {
fmt.Printf("\n🤖 %s\n\n", *event.Data.Content)
}
case "tool.execution_start":
if event.Data.ToolName != nil {
fmt.Printf(" ⚙️ %s\n", *event.Data.ToolName)
}
switch d := event.Data.(type) {
case *copilot.AssistantMessageData:
fmt.Printf("\n🤖 %s\n\n", d.Content)
case *copilot.ToolExecutionStartData:
fmt.Printf(" ⚙️ %s\n", d.ToolName)
}
})

View File

@@ -59,10 +59,10 @@ func ralphLoop(ctx context.Context, mode string, maxIterations int) error {
fmt.Printf("\n=== Iteration %d/%d ===\n", i, maxIterations)
session, err := client.CreateSession(ctx, &copilot.SessionConfig{
Model: "gpt-5.1-codex-mini",
Model: "gpt-5.3-codex",
WorkingDirectory: cwd,
OnPermissionRequest: func(_ copilot.PermissionRequest, _ map[string]string) copilot.PermissionRequestResult {
return copilot.PermissionRequestResult{Kind: "approved"}
OnPermissionRequest: func(_ copilot.PermissionRequest, _ copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
return copilot.PermissionRequestResult{Kind: "approved"}, nil
},
})
if err != nil {
@@ -70,17 +70,17 @@ func ralphLoop(ctx context.Context, mode string, maxIterations int) error {
}
// Log tool usage for visibility
session.On(func(event copilot.Event) {
if toolExecution, ok := event.(copilot.ToolExecutionStartEvent); ok {
fmt.Printf(" ⚙ %s\n", toolExecution.Data.ToolName)
session.On(func(event copilot.SessionEvent) {
if d, ok := event.Data.(*copilot.ToolExecutionStartData); ok {
fmt.Printf(" ⚙ %s\n", d.ToolName)
}
})
_, err = session.SendAndWait(ctx, copilot.MessageOptions{
Prompt: string(prompt),
})
if destroyErr := session.Destroy(); destroyErr != nil {
log.Printf("failed to destroy session on iteration %d: %v", i, destroyErr)
if destroyErr := session.Disconnect(); destroyErr != nil {
log.Printf("failed to disconnect session on iteration %d: %v", i, destroyErr)
}
if err != nil {
return fmt.Errorf("send failed on iteration %d: %w", i, err)