Repository navigation
Expand file tree
/
Copy pathjev.go
More file actions
291 lines (262 loc) · 8.54 KB
/
Copy pathjev.go
File metadata and controls
291 lines (262 loc) · 8.54 KB
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package GoEventBus
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
)
var (
// ErrNilEventSelector is returned when a selector-aware operation is called
// without an EventSelector.
ErrNilEventSelector = errors.New("goeventbus: event selector is nil")
// ErrNoEventCandidates is returned when there are no event types to choose from.
ErrNoEventCandidates = errors.New("goeventbus: no event candidates")
// ErrInvalidEventCandidate is returned when a candidate has an empty or duplicate key.
ErrInvalidEventCandidate = errors.New("goeventbus: invalid event candidate")
// ErrUnknownEventChoice is returned when a selector returns a choice that was
// not present in the supplied candidate set.
ErrUnknownEventChoice = errors.New("goeventbus: selector returned unknown event choice")
)
// EventCandidate is a named event type that an EventSelector may choose.
//
// Key is the stable string exposed to the decision model. Projection is the
// actual GoEventBus dispatcher key, so callers can keep using typed struct
// projections. Description should explain when this event type is appropriate.
type EventCandidate struct {
Key string
Projection interface{}
Description string
}
// EventDecision is the structured result of event-type selection.
type EventDecision struct {
Choice string
Projection interface{}
Confidence float64
Probabilities map[string]float64
Model string
RequestID string
}
// EventSelector chooses one candidate event type from a fixed set.
type EventSelector interface {
SelectEvent(context.Context, any, []EventCandidate) (EventDecision, error)
}
func selectEvent(
ctx context.Context,
selector EventSelector,
state any,
event Event,
candidates []EventCandidate,
) (EventDecision, Event, error) {
if ctx == nil {
ctx = context.Background()
}
if selector == nil {
return EventDecision{}, Event{}, ErrNilEventSelector
}
if len(candidates) == 0 {
return EventDecision{}, Event{}, ErrNoEventCandidates
}
byKey := make(map[string]EventCandidate, len(candidates))
normalized := make([]EventCandidate, len(candidates))
for i, candidate := range candidates {
key := strings.TrimSpace(candidate.Key)
if key == "" {
return EventDecision{}, Event{}, fmt.Errorf("%w: empty key", ErrInvalidEventCandidate)
}
if _, exists := byKey[key]; exists {
return EventDecision{}, Event{}, fmt.Errorf("%w: duplicate key %q", ErrInvalidEventCandidate, key)
}
candidate.Key = key
normalized[i] = candidate
byKey[key] = candidate
}
decision, err := selector.SelectEvent(ctx, state, normalized)
if err != nil {
return EventDecision{}, Event{}, err
}
candidate, ok := byKey[decision.Choice]
if !ok {
return EventDecision{}, Event{}, fmt.Errorf("%w: %q", ErrUnknownEventChoice, decision.Choice)
}
event.Projection = candidate.Projection
decision.Projection = candidate.Projection
return decision, event, nil
}
// DecideAndSubscribe asks selector to choose the event type and assigns the
// chosen projection to event.
//
// Without a configured provider, the event is enqueued locally and dispatch
// follows the normal Subscribe -> Publish lifecycle. With WithRedis,
// WithRabbitMQ, or WithProvider, the selected event is published directly to
// the configured provider instead. A consumer can feed it back into an
// EventStore with Consume.
func (es *EventStore) DecideAndSubscribe(
ctx context.Context,
selector EventSelector,
state any,
event Event,
candidates []EventCandidate,
) (EventDecision, error) {
decision, selected, err := selectEvent(ctx, selector, state, event, candidates)
if err != nil {
return EventDecision{}, err
}
if ctx == nil {
ctx = context.Background()
}
if es.hasConfiguredProvider() {
if err := es.PublishToProvider(ctx, selected); err != nil {
return EventDecision{}, err
}
} else if err := es.Subscribe(ctx, selected); err != nil {
return EventDecision{}, err
}
return decision, nil
}
// JevSelector selects event types with TypeSafe Jev through OpenRouter's
// Decisions API.
type JevSelector struct {
APIKey string
Model string
Endpoint string
Instructions string
Client *http.Client
}
const (
defaultJevModel = "typesafe/jev-1.13"
defaultJevEndpoint = "https://openrouter.ai/api/alpha/decisions"
)
type jevDecisionRequest struct {
Model string `json:"model"`
State any `json:"state"`
Questions map[string]jevQuestion `json:"questions"`
}
type jevQuestion struct {
Type string `json:"type"`
Instructions string `json:"instructions"`
Criteria map[string]string `json:"criteria"`
}
type jevDecisionResponse struct {
Model string `json:"model"`
ID string `json:"id"`
Answers map[string]struct {
Type string `json:"type"`
Choice string `json:"choice"`
Probabilities map[string]float64 `json:"probabilities"`
Confidence float64 `json:"confidence"`
} `json:"answers"`
}
// SelectEvent sends one Jev choice question whose criteria are the available
// event types. It does not enqueue or execute anything itself.
func (s *JevSelector) SelectEvent(
ctx context.Context,
state any,
candidates []EventCandidate,
) (EventDecision, error) {
if ctx == nil {
ctx = context.Background()
}
if s == nil {
return EventDecision{}, ErrNilEventSelector
}
if strings.TrimSpace(s.APIKey) == "" {
return EventDecision{}, errors.New("goeventbus: Jev API key is empty")
}
if len(candidates) == 0 {
return EventDecision{}, ErrNoEventCandidates
}
criteria := make(map[string]string, len(candidates))
for _, candidate := range candidates {
key := strings.TrimSpace(candidate.Key)
if key == "" {
return EventDecision{}, fmt.Errorf("%w: empty key", ErrInvalidEventCandidate)
}
if _, exists := criteria[key]; exists {
return EventDecision{}, fmt.Errorf("%w: duplicate key %q", ErrInvalidEventCandidate, key)
}
description := strings.TrimSpace(candidate.Description)
if description == "" {
description = "Use when the input should be handled as " + key
}
criteria[key] = description
}
model := strings.TrimSpace(s.Model)
if model == "" {
model = defaultJevModel
}
endpoint := strings.TrimSpace(s.Endpoint)
if endpoint == "" {
endpoint = defaultJevEndpoint
}
instructions := strings.TrimSpace(s.Instructions)
if instructions == "" {
instructions = "Choose the single event type that best matches the supplied state."
}
payload := jevDecisionRequest{
Model: model,
State: state,
Questions: map[string]jevQuestion{
"event_type": {
Type: "choice",
Instructions: instructions,
Criteria: criteria,
},
},
}
body, err := json.Marshal(payload)
if err != nil {
return EventDecision{}, fmt.Errorf("goeventbus: encode Jev request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
if err != nil {
return EventDecision{}, fmt.Errorf("goeventbus: create Jev request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+s.APIKey)
req.Header.Set("Content-Type", "application/json")
client := s.Client
if client == nil {
client = &http.Client{Timeout: 5 * time.Second}
}
resp, err := client.Do(req)
if err != nil {
return EventDecision{}, fmt.Errorf("goeventbus: Jev request failed: %w", err)
}
defer resp.Body.Close()
responseBody, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return EventDecision{}, fmt.Errorf("goeventbus: read Jev response: %w", err)
}
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
message := strings.TrimSpace(string(responseBody))
if len(message) > 1024 {
message = message[:1024]
}
return EventDecision{}, fmt.Errorf("goeventbus: Jev returned %s: %s", resp.Status, message)
}
var decoded jevDecisionResponse
if err := json.Unmarshal(responseBody, &decoded); err != nil {
return EventDecision{}, fmt.Errorf("goeventbus: decode Jev response: %w", err)
}
answer, ok := decoded.Answers["event_type"]
if !ok {
return EventDecision{}, errors.New("goeventbus: Jev response missing event_type answer")
}
if answer.Type != "choice" {
return EventDecision{}, fmt.Errorf("goeventbus: Jev returned unexpected answer type %q", answer.Type)
}
if _, ok := criteria[answer.Choice]; !ok {
return EventDecision{}, fmt.Errorf("%w: %q", ErrUnknownEventChoice, answer.Choice)
}
return EventDecision{
Choice: answer.Choice,
Confidence: answer.Confidence,
Probabilities: answer.Probabilities,
Model: decoded.Model,
RequestID: decoded.ID,
}, nil
}