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 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
| package main
import ( "bufio" "context" "errors" "fmt" "os" "strings" "sync"
"react_agent/pkg/model"
einomodel "github.com/cloudwego/eino/components/model" "github.com/cloudwego/eino/components/prompt" "github.com/cloudwego/eino/compose" "github.com/cloudwego/eino/schema" )
type Ticket struct { ID string Amount int Reason string Level string Approved bool Note string }
type PendingTicket struct { Ticket Ticket }
type AskInfo struct { Question string Ticket Ticket }
type Reply struct { Approved bool Note string }
func init() { schema.Register[Ticket]() schema.Register[PendingTicket]() schema.Register[Reply]() schema.Register[AskInfo]() }
type MemStore struct { mu sync.Mutex m map[string][]byte }
func NewMemStore() *MemStore { return &MemStore{m: make(map[string][]byte)} }
func (s *MemStore) Get(_ context.Context, id string) ([]byte, bool, error) { s.mu.Lock() defer s.mu.Unlock() v, ok := s.m[id] return v, ok, nil }
func (s *MemStore) Set(_ context.Context, id string, cp []byte) error { s.mu.Lock() defer s.mu.Unlock() s.m[id] = append([]byte(nil), cp...) return nil }
func (s *MemStore) Delete(_ context.Context, id string) error { s.mu.Lock() defer s.mu.Unlock() delete(s.m, id) return nil }
func humanConfirm(ctx context.Context, t Ticket) (Ticket, error) { wasInterrupted, hasState, state := compose.GetInterruptState[*PendingTicket](ctx) if !wasInterrupted { return Ticket{}, compose.StatefulInterrupt(ctx, AskInfo{ Question: fmt.Sprintf("工单 %s:%d 元,事由「%s」,风险 %s,是否批准?(y/n) 备注可选", t.ID, t.Amount, t.Reason, t.Level), Ticket: t, }, &PendingTicket{Ticket: t}, ) } if !hasState { return Ticket{}, errors.New("恢复时没取到之前保存的工单状态") } t = state.Ticket
isResume, hasData, reply := compose.GetResumeContext[*Reply](ctx) if !isResume || !hasData { return Ticket{}, compose.StatefulInterrupt(ctx, AskInfo{Question: "还没等到你的答复", Ticket: t}, state) }
t.Approved, t.Note = reply.Approved, reply.Note fmt.Printf(" [人工输入] approved=%v 备注=%q\n", t.Approved, t.Note) return t, nil }
func buildGraph(chatModel einomodel.BaseChatModel) *compose.Graph[Ticket, string] { g := compose.NewGraph[Ticket, string]()
_ = g.AddLambdaNode("risk", compose.InvokableLambda( func(ctx context.Context, t Ticket) (Ticket, error) { switch { case t.Amount >= 10000: t.Level = "high" case t.Amount >= 1000: t.Level = "mid" default: t.Level = "low" } return t, nil }), compose.WithNodeName("风险分级"))
_ = g.AddLambdaNode("human_confirm", compose.InvokableLambda(humanConfirm), compose.WithNodeName("人工确认"))
_ = g.AddLambdaNode("rejected", compose.InvokableLambda( func(ctx context.Context, t Ticket) (string, error) { return fmt.Sprintf("工单 %s 已驳回:%s", t.ID, t.Note), nil }), compose.WithNodeName("驳回结论"))
_ = g.AddLambdaNode("report_vars", compose.InvokableLambda( func(ctx context.Context, t Ticket) (map[string]any, error) { return map[string]any{"id": t.ID, "amount": t.Amount, "note": t.Note}, nil }), compose.WithNodeName("构造变量")) _ = g.AddChatTemplateNode("report_tpl", prompt.FromMessages(schema.GoTemplate, schema.SystemMessage("用一句中文告知用户退款已通过审核,语气专业。"), schema.UserMessage("工单号 {{.id}},金额 {{.amount}} 元,审核备注:{{.note}}"))) _ = g.AddChatModelNode("report_model", chatModel) _ = g.AddLambdaNode("report_out", compose.InvokableLambda( func(ctx context.Context, m *schema.Message) (string, error) { return strings.TrimSpace(m.Content), nil }), compose.WithNodeName("取正文"))
_ = g.AddBranch("risk", compose.NewGraphBranch( func(ctx context.Context, t Ticket) (string, error) { if t.Level == "low" { return "report_vars", nil } return "human_confirm", nil }, map[string]bool{"report_vars": true, "human_confirm": true}))
_ = g.AddBranch("human_confirm", compose.NewGraphBranch( func(ctx context.Context, t Ticket) (string, error) { if t.Approved { return "report_vars", nil } return "rejected", nil }, map[string]bool{"report_vars": true, "rejected": true}))
_ = g.AddEdge(compose.START, "risk") _ = g.AddEdge("human_confirm", "report_vars") _ = g.AddEdge("report_vars", "report_tpl") _ = g.AddEdge("report_tpl", "report_model") _ = g.AddEdge("report_model", "report_out") _ = g.AddEdge("report_out", compose.END) _ = g.AddEdge("rejected", compose.END)
return g }
func runTicket(ctx context.Context, r compose.Runnable[Ticket, string], ckptID string, in Ticket, ask func(AskInfo) (Reply, error)) (string, error) { out, err := r.Invoke(ctx, in, compose.WithCheckPointID(ckptID)) base := ctx for { if err == nil { return out, nil } info, ok := compose.ExtractInterruptInfo(err) if !ok || len(info.InterruptContexts) == 0 { return "", err } point := rootCause(info.InterruptContexts) askInfo, ok := point.Info.(AskInfo) if !ok { return "", fmt.Errorf("中断信息类型不对: %T", point.Info) }
reply, askErr := ask(askInfo) if askErr != nil { return "", askErr }
resumeCtx := compose.ResumeWithData(base, point.ID, &reply) out, err = r.Invoke(resumeCtx, Ticket{}, compose.WithCheckPointID(ckptID)) } }
func rootCause(ctxs []*compose.InterruptCtx) *compose.InterruptCtx { for _, c := range ctxs { if c.IsRootCause { return c } } return ctxs[0] }
func main() { ctx := context.Background() chatModel, err := model.NewDefaultChatModel(ctx) if err != nil { panic(err) }
store := NewMemStore() r, err := buildGraph(chatModel).Compile(ctx, compose.WithGraphName("hitl_refund"), compose.WithCheckPointStore(store)) if err != nil { panic(err) }
scanner := bufio.NewScanner(os.Stdin) ask := func(a AskInfo) (Reply, error) { fmt.Printf("\n需要人工确认:%s\n> ", a.Question) if !scanner.Scan() { return Reply{}, errors.New("没读到人工输入") } fields := strings.Fields(scanner.Text()) reply := Reply{Approved: len(fields) > 0 && strings.EqualFold(fields[0], "y"), Note: strings.Join(fields[1:], " ")} if !reply.Approved && reply.Note == "" { reply.Note = "人工驳回,理由未填写" } return reply, nil }
for _, t := range []Ticket{ {ID: "R-1001", Amount: 30, Reason: "买重复了"}, {ID: "R-1002", Amount: 2800, Reason: "商品与描述不符"}, } { fmt.Printf("\n=== 工单 %s(%d 元)===\n", t.ID, t.Amount) answer, err := runTicket(ctx, r, t.ID, t, ask) if err != nil { fmt.Printf("失败: %v\n", err) continue } fmt.Printf("答复: %s\n", answer) _ = store.Delete(ctx, t.ID) } }
|