forked from liushuangls/go-anthropic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
329 lines (274 loc) · 8.59 KB
/
message.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
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package anthropic
import (
"context"
"encoding/json"
"net/http"
)
type MessagesResponseType string
const (
MessagesResponseTypeMessage MessagesResponseType = "message"
MessagesResponseTypeError MessagesResponseType = "error"
)
type MessagesContentType string
const (
MessagesContentTypeText MessagesContentType = "text"
MessagesContentTypeTextDelta MessagesContentType = "text_delta"
MessagesContentTypeImage MessagesContentType = "image"
MessagesContentTypeToolResult MessagesContentType = "tool_result"
MessagesContentTypeToolUse MessagesContentType = "tool_use"
MessagesContentTypeInputJsonDelta MessagesContentType = "input_json_delta"
)
type MessagesStopReason string
const (
MessagesStopReasonEndTurn MessagesStopReason = "end_turn"
MessagesStopReasonMaxTokens MessagesStopReason = "max_tokens"
MessagesStopReasonStopSequence MessagesStopReason = "stop_sequence"
MessagesStopReasonToolUse MessagesStopReason = "tool_use"
)
type MessagesRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
MaxTokens int `json:"max_tokens"`
System string `json:"-"`
MultiSystem []MessageSystemPart `json:"-"`
Metadata map[string]any `json:"metadata,omitempty"`
StopSequences []string `json:"stop_sequences,omitempty"`
Stream bool `json:"stream,omitempty"`
Temperature *float32 `json:"temperature,omitempty"`
TopP *float32 `json:"top_p,omitempty"`
TopK *int `json:"top_k,omitempty"`
Tools []ToolDefinition `json:"tools,omitempty"`
ToolChoice *ToolChoice `json:"tool_choice,omitempty"`
}
func (m MessagesRequest) MarshalJSON() ([]byte, error) {
type Alias MessagesRequest
aux := struct {
System interface{} `json:"system,omitempty"`
Alias
}{
Alias: (Alias)(m),
}
// 根据 MultiSystem 是否为空来设置 system 字段
if len(m.MultiSystem) > 0 {
aux.System = m.MultiSystem
} else if len(m.System) > 0 {
aux.System = m.System
}
return json.Marshal(aux)
}
func (m *MessagesRequest) SetTemperature(t float32) {
m.Temperature = &t
}
func (m *MessagesRequest) SetTopP(p float32) {
m.TopP = &p
}
func (m *MessagesRequest) SetTopK(k int) {
m.TopK = &k
}
type MessageSystemPart struct {
Type string `json:"type"`
Text string `json:"text"`
CacheControl *MessageCacheControl `json:"cache_control,omitempty"`
}
type Message struct {
Role string `json:"role"`
Content []MessageContent `json:"content"`
}
func NewUserTextMessage(text string) Message {
return Message{
Role: RoleUser,
Content: []MessageContent{NewTextMessageContent(text)},
}
}
func NewAssistantTextMessage(text string) Message {
return Message{
Role: RoleAssistant,
Content: []MessageContent{NewTextMessageContent(text)},
}
}
func NewToolResultsMessage(toolUseID, content string, isError bool) Message {
return Message{
Role: RoleUser,
Content: []MessageContent{NewToolResultMessageContent(toolUseID, content, isError)},
}
}
func (m Message) GetFirstContent() MessageContent {
if len(m.Content) == 0 {
return MessageContent{}
}
return m.Content[0]
}
type CacheControlType string
const (
CacheControlTypeEphemeral CacheControlType = "ephemeral"
)
type MessageCacheControl struct {
Type CacheControlType `json:"type"`
}
type MessageContent struct {
Type MessagesContentType `json:"type"`
Text *string `json:"text,omitempty"`
Source *MessageContentImageSource `json:"source,omitempty"`
*MessageContentToolResult
*MessageContentToolUse
PartialJson *string `json:"partial_json,omitempty"`
CacheControl *MessageCacheControl `json:"cache_control,omitempty"`
}
func NewTextMessageContent(text string) MessageContent {
return MessageContent{
Type: MessagesContentTypeText,
Text: &text,
}
}
func NewImageMessageContent(source MessageContentImageSource) MessageContent {
return MessageContent{
Type: MessagesContentTypeImage,
Source: &source,
}
}
func NewToolResultMessageContent(toolUseID, content string, isError bool) MessageContent {
return MessageContent{
Type: MessagesContentTypeToolResult,
MessageContentToolResult: NewMessageContentToolResult(toolUseID, content, isError),
}
}
func NewToolUseMessageContent(toolUseID, name string, input json.RawMessage) MessageContent {
return MessageContent{
Type: MessagesContentTypeToolUse,
MessageContentToolUse: &MessageContentToolUse{
ID: toolUseID,
Name: name,
Input: input,
},
}
}
func (m *MessageContent) SetCacheControl(ts ...CacheControlType) {
t := CacheControlTypeEphemeral
if len(ts) > 0 {
t = ts[0]
}
m.CacheControl = &MessageCacheControl{
Type: t,
}
}
func (m *MessageContent) GetText() string {
if m.Text != nil {
return *m.Text
}
return ""
}
func (m *MessageContent) ConcatText(s string) {
if m.Text == nil {
m.Text = &s
} else {
*m.Text += s
}
}
func (m *MessageContent) MergeContentDelta(mc MessageContent) {
switch mc.Type {
case MessagesContentTypeText:
m.ConcatText(mc.GetText())
case MessagesContentTypeTextDelta:
m.ConcatText(mc.GetText())
case MessagesContentTypeImage:
m.Source = mc.Source
case MessagesContentTypeToolResult:
m.MessageContentToolResult = mc.MessageContentToolResult
case MessagesContentTypeToolUse:
m.MessageContentToolUse = &MessageContentToolUse{
ID: mc.MessageContentToolUse.ID,
Name: mc.MessageContentToolUse.Name,
}
case MessagesContentTypeInputJsonDelta:
if m.PartialJson == nil {
m.PartialJson = mc.PartialJson
} else {
*m.PartialJson += *mc.PartialJson
}
}
}
type MessageContentToolResult struct {
ToolUseID *string `json:"tool_use_id,omitempty"`
Content []MessageContent `json:"content,omitempty"`
IsError *bool `json:"is_error,omitempty"`
}
func NewMessageContentToolResult(toolUseID, content string, isError bool) *MessageContentToolResult {
return &MessageContentToolResult{
ToolUseID: &toolUseID,
Content: []MessageContent{
{
Type: MessagesContentTypeText,
Text: &content,
},
},
IsError: &isError,
}
}
type MessageContentImageSource struct {
Type string `json:"type"`
MediaType string `json:"media_type"`
Data any `json:"data"`
}
type MessageContentToolUse struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Input json.RawMessage `json:"input,omitempty"`
}
func (c *MessageContentToolUse) UnmarshalInput(v any) error {
return json.Unmarshal(c.Input, v)
}
type MessagesResponse struct {
httpHeader
ID string `json:"id"`
Type MessagesResponseType `json:"type"`
Role string `json:"role"`
Content []MessageContent `json:"content"`
Model string `json:"model"`
StopReason MessagesStopReason `json:"stop_reason"`
StopSequence string `json:"stop_sequence"`
Usage MessagesUsage `json:"usage"`
}
// GetFirstContentText get Content[0].Text avoid panic
func (m MessagesResponse) GetFirstContentText() string {
if len(m.Content) == 0 {
return ""
}
return m.Content[0].GetText()
}
type MessagesUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
// The number of tokens written to the cache when creating a new entry.
CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
// The number of tokens retrieved from the cache for associated request.
CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"`
}
type ToolDefinition struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
// InputSchema is an object describing the tool.
// You can pass json.RawMessage to describe the schema,
// or you can pass in a struct which serializes to the proper JSON schema.
// The jsonschema package is provided for convenience, but you should
// consider another specialized library if you require more complex schemas.
InputSchema any `json:"input_schema"`
}
type ToolChoice struct {
// oneof: auto(default) any tool
Type string `json:"type"`
Name string `json:"name,omitempty"`
}
func (c *Client) CreateMessages(ctx context.Context, request MessagesRequest) (response MessagesResponse, err error) {
request.Stream = false
var setters []requestSetter
if len(c.config.BetaVersion) > 0 {
setters = append(setters, withBetaVersion(c.config.BetaVersion))
}
urlSuffix := "/messages"
req, err := c.newRequest(ctx, http.MethodPost, urlSuffix, request, setters...)
if err != nil {
return
}
err = c.sendRequest(req, &response)
return
}