-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
84 lines (73 loc) · 2.25 KB
/
main.go
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
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"github.com/coze-dev/coze-go"
)
// This examples describes how to use the workflow interface to stream chats.
func main() {
// Get an access_token through personal access token or oauth.
token := os.Getenv("COZE_API_TOKEN")
authCli := coze.NewTokenAuth(token)
// Init the Coze client through the access_token.
cozeCli := coze.NewCozeAPI(authCli, coze.WithBaseURL(os.Getenv("COZE_API_BASE")))
ctx := context.Background()
workflowID := os.Getenv("WORKFLOW_ID")
// if your workflow need input params, you can send them by map
data := map[string]interface{}{
"date": "param values",
}
req := &coze.RunWorkflowsReq{
WorkflowID: workflowID,
Parameters: data,
}
resp, err := cozeCli.Workflows.Runs.Stream(ctx, req)
if err != nil {
fmt.Println("Error starting stream:", err)
return
}
handleEvents(ctx, resp, cozeCli, workflowID)
}
// The stream interface will return an iterator of WorkflowEvent. Developers should iterate
// through this iterator to obtain WorkflowEvent and handle them separately according to
// the type of WorkflowEvent.
func handleEvents(ctx context.Context, resp coze.Stream[coze.WorkflowEvent], cozeCli coze.CozeAPI, workflowID string) {
defer resp.Close()
for {
event, err := resp.Recv()
if errors.Is(err, io.EOF) {
fmt.Println("Stream finished")
break
}
if err != nil {
fmt.Println("Error receiving event:", err)
break
}
switch event.Event {
case coze.WorkflowEventTypeMessage:
fmt.Println("Got message:", event.Message)
case coze.WorkflowEventTypeError:
fmt.Println("Got error:", event.Error)
case coze.WorkflowEventTypeDone:
fmt.Println("Got message:", event.Message)
case coze.WorkflowEventTypeInterrupt:
resumeReq := &coze.ResumeRunWorkflowsReq{
WorkflowID: workflowID,
EventID: event.Interrupt.InterruptData.EventID,
ResumeData: "your data",
InterruptType: event.Interrupt.InterruptData.Type,
}
newResp, err := cozeCli.Workflows.Runs.Resume(ctx, resumeReq)
if err != nil {
fmt.Println("Error resuming workflow:", err)
return
}
fmt.Println("start resume workflow")
handleEvents(ctx, newResp, cozeCli, workflowID)
}
}
fmt.Printf("done, log:%s\n", resp.Response().LogID())
}