-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathopenapi_agent_run.go
More file actions
330 lines (293 loc) · 10.7 KB
/
openapi_agent_run.go
File metadata and controls
330 lines (293 loc) · 10.7 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
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
330
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package conversation
import (
"context"
"encoding/json"
"errors"
"io"
"strconv"
"github.com/cloudwego/eino/schema"
"github.com/coze-dev/coze-studio/backend/api/model/conversation/common"
"github.com/coze-dev/coze-studio/backend/api/model/conversation/run"
"github.com/coze-dev/coze-studio/backend/api/model/crossdomain/agentrun"
"github.com/coze-dev/coze-studio/backend/api/model/crossdomain/message"
"github.com/coze-dev/coze-studio/backend/api/model/crossdomain/singleagent"
"github.com/coze-dev/coze-studio/backend/application/base/ctxutil"
saEntity "github.com/coze-dev/coze-studio/backend/domain/agent/singleagent/entity"
"github.com/coze-dev/coze-studio/backend/domain/conversation/agentrun/entity"
convEntity "github.com/coze-dev/coze-studio/backend/domain/conversation/conversation/entity"
cmdEntity "github.com/coze-dev/coze-studio/backend/domain/shortcutcmd/entity"
sseImpl "github.com/coze-dev/coze-studio/backend/infra/impl/sse"
"github.com/coze-dev/coze-studio/backend/pkg/lang/conv"
"github.com/coze-dev/coze-studio/backend/pkg/lang/ptr"
"github.com/coze-dev/coze-studio/backend/pkg/logs"
"github.com/coze-dev/coze-studio/backend/types/consts"
"github.com/coze-dev/coze-studio/backend/types/errno"
)
func (a *OpenapiAgentRunApplication) OpenapiAgentRun(ctx context.Context, sseSender *sseImpl.SSenderImpl, ar *run.ChatV3Request) error {
apiKeyInfo := ctxutil.GetApiAuthFromCtx(ctx)
creatorID := apiKeyInfo.UserID
connectorID := apiKeyInfo.ConnectorID
if ptr.From(ar.ConnectorID) == consts.WebSDKConnectorID {
connectorID = ptr.From(ar.ConnectorID)
}
agentInfo, caErr := a.checkAgent(ctx, ar, connectorID)
if caErr != nil {
logs.CtxErrorf(ctx, "checkAgent err:%v", caErr)
return caErr
}
conversationData, ccErr := a.checkConversation(ctx, ar, creatorID, connectorID)
if ccErr != nil {
logs.CtxErrorf(ctx, "checkConversation err:%v", ccErr)
return ccErr
}
spaceID := agentInfo.SpaceID
arr, err := a.buildAgentRunRequest(ctx, ar, connectorID, spaceID, conversationData)
if err != nil {
logs.CtxErrorf(ctx, "buildAgentRunRequest err:%v", err)
return err
}
streamer, err := ConversationSVC.AgentRunDomainSVC.AgentRun(ctx, arr)
if err != nil {
return err
}
a.pullStream(ctx, sseSender, streamer)
return nil
}
func (a *OpenapiAgentRunApplication) checkConversation(ctx context.Context, ar *run.ChatV3Request, userID int64, connectorID int64) (*convEntity.Conversation, error) {
var conversationData *convEntity.Conversation
if ptr.From(ar.ConversationID) > 0 {
conData, err := ConversationSVC.ConversationDomainSVC.GetByID(ctx, ptr.From(ar.ConversationID))
if err != nil {
return nil, err
}
conversationData = conData
}
if ptr.From(ar.ConversationID) == 0 || conversationData == nil {
conData, err := ConversationSVC.ConversationDomainSVC.Create(ctx, &convEntity.CreateMeta{
AgentID: ar.BotID,
UserID: userID,
ConnectorID: connectorID,
Scene: common.Scene_SceneOpenApi,
})
if err != nil {
return nil, err
}
if conData == nil {
return nil, errors.New("conversation data is nil")
}
conversationData = conData
ar.ConversationID = ptr.Of(conversationData.ID)
}
if conversationData.CreatorID != userID {
return nil, errors.New("conversation data not match")
}
return conversationData, nil
}
func (a *OpenapiAgentRunApplication) checkAgent(ctx context.Context, ar *run.ChatV3Request, connectorID int64) (*saEntity.SingleAgent, error) {
agentInfo, err := ConversationSVC.appContext.SingleAgentDomainSVC.ObtainAgentByIdentity(ctx, &singleagent.AgentIdentity{
AgentID: ar.BotID,
IsDraft: false,
ConnectorID: connectorID,
})
if err != nil {
return nil, err
}
if agentInfo == nil {
return nil, errors.New("agent info is nil")
}
return agentInfo, nil
}
func (a *OpenapiAgentRunApplication) buildAgentRunRequest(ctx context.Context, ar *run.ChatV3Request, connectorID int64, spaceID int64, conversationData *convEntity.Conversation) (*entity.AgentRunMeta, error) {
shortcutCMDData, err := a.buildTools(ctx, ar.ShortcutCommand)
if err != nil {
return nil, err
}
multiContent, contentType, err := a.buildMultiContent(ctx, ar)
if err != nil {
return nil, err
}
displayContent := a.buildDisplayContent(ctx, ar)
arm := &entity.AgentRunMeta{
ConversationID: ptr.From(ar.ConversationID),
AgentID: ar.BotID,
Content: multiContent,
DisplayContent: displayContent,
SpaceID: spaceID,
UserID: ar.User,
SectionID: conversationData.SectionID,
PreRetrieveTools: shortcutCMDData,
IsDraft: false,
ConnectorID: connectorID,
ContentType: contentType,
Ext: ar.ExtraParams,
}
return arm, nil
}
func (a *OpenapiAgentRunApplication) buildTools(ctx context.Context, shortcmd *run.ShortcutCommandDetail) ([]*entity.Tool, error) {
var ts []*entity.Tool
if shortcmd == nil {
return ts, nil
}
var shortcutCMD *cmdEntity.ShortcutCmd
cmdMeta, err := a.ShortcutDomainSVC.GetByCmdID(ctx, shortcmd.CommandID, 0)
if err != nil {
return nil, err
}
shortcutCMD = cmdMeta
if shortcutCMD != nil {
argBytes, err := json.Marshal(shortcmd.Parameters)
if err == nil {
ts = append(ts, &entity.Tool{
PluginID: shortcutCMD.PluginID,
Arguments: string(argBytes),
ToolName: shortcutCMD.PluginToolName,
ToolID: shortcutCMD.PluginToolID,
Type: agentrun.ToolType(shortcutCMD.ToolType),
})
}
}
return ts, nil
}
func (a *OpenapiAgentRunApplication) buildDisplayContent(_ context.Context, ar *run.ChatV3Request) string {
for _, item := range ar.AdditionalMessages {
if item.ContentType == run.ContentTypeMixApi {
return item.Content
}
}
return ""
}
func (a *OpenapiAgentRunApplication) buildMultiContent(ctx context.Context, ar *run.ChatV3Request) ([]*message.InputMetaData, message.ContentType, error) {
var multiContents []*message.InputMetaData
contentType := message.ContentTypeText
for _, item := range ar.AdditionalMessages {
if item == nil {
continue
}
if item.Role != string(schema.User) {
return nil, contentType, errors.New("role not match")
}
if item.ContentType == run.ContentTypeText {
if item.Content == "" {
continue
}
multiContents = append(multiContents, &message.InputMetaData{
Type: message.InputTypeText,
Text: item.Content,
})
}
if item.ContentType == run.ContentTypeMixApi {
contentType = message.ContentTypeMix
var inputs []*run.AdditionalContent
err := json.Unmarshal([]byte(item.Content), &inputs)
logs.CtxInfof(ctx, "inputs:%v, err:%v", conv.DebugJsonToStr(inputs), err)
if err != nil {
continue
}
for _, one := range inputs {
if one == nil {
continue
}
switch message.InputType(one.Type) {
case message.InputTypeText:
multiContents = append(multiContents, &message.InputMetaData{
Type: message.InputTypeText,
Text: ptr.From(one.Text),
})
case message.InputTypeImage, message.InputTypeFile:
multiContents = append(multiContents, &message.InputMetaData{
Type: message.InputType(one.Type),
FileData: []*message.FileData{
{
Url: one.GetFileURL(),
},
},
})
default:
continue
}
}
}
}
return multiContents, contentType, nil
}
func (a *OpenapiAgentRunApplication) pullStream(ctx context.Context, sseSender *sseImpl.SSenderImpl, streamer *schema.StreamReader[*entity.AgentRunResponse]) {
for {
chunk, recvErr := streamer.Recv()
logs.CtxInfof(ctx, "chunk :%v, err:%v", conv.DebugJsonToStr(chunk), recvErr)
if recvErr != nil {
if errors.Is(recvErr, io.EOF) {
return
}
sseSender.Send(ctx, buildErrorEvent(errno.ErrConversationAgentRunError, recvErr.Error()))
return
}
switch chunk.Event {
case entity.RunEventError:
sseSender.Send(ctx, buildErrorEvent(chunk.Error.Code, chunk.Error.Msg))
case entity.RunEventStreamDone:
sseSender.Send(ctx, buildDoneEvent(string(entity.RunEventStreamDone)))
case entity.RunEventAck:
case entity.RunEventCreated, entity.RunEventCancelled, entity.RunEventInProgress, entity.RunEventFailed, entity.RunEventCompleted:
sseSender.Send(ctx, buildMessageChunkEvent(string(chunk.Event), buildARSM2ApiChatMessage(chunk)))
case entity.RunEventMessageDelta, entity.RunEventMessageCompleted:
sseSender.Send(ctx, buildMessageChunkEvent(string(chunk.Event), buildARSM2ApiMessage(chunk)))
default:
logs.CtxErrorf(ctx, "unknow handler event:%v", chunk.Event)
}
}
}
func buildARSM2ApiMessage(chunk *entity.AgentRunResponse) []byte {
chunkMessageItem := chunk.ChunkMessageItem
chunkMessage := &run.ChatV3MessageDetail{
ID: strconv.FormatInt(chunkMessageItem.ID, 10),
ConversationID: strconv.FormatInt(chunkMessageItem.ConversationID, 10),
BotID: strconv.FormatInt(chunkMessageItem.AgentID, 10),
Role: string(chunkMessageItem.Role),
Type: string(chunkMessageItem.MessageType),
Content: chunkMessageItem.Content,
ContentType: string(chunkMessageItem.ContentType),
MetaData: chunkMessageItem.Ext,
ChatID: strconv.FormatInt(chunkMessageItem.RunID, 10),
ReasoningContent: chunkMessageItem.ReasoningContent,
CreatedAt: ptr.Of(chunkMessageItem.CreatedAt / 1000),
}
mCM, _ := json.Marshal(chunkMessage)
return mCM
}
func buildARSM2ApiChatMessage(chunk *entity.AgentRunResponse) []byte {
chunkRunItem := chunk.ChunkRunItem
chunkMessage := &run.ChatV3ChatDetail{
ID: chunkRunItem.ID,
ConversationID: chunkRunItem.ConversationID,
BotID: chunkRunItem.AgentID,
Status: string(chunkRunItem.Status),
SectionID: ptr.Of(chunkRunItem.SectionID),
CreatedAt: ptr.Of(int32(chunkRunItem.CreatedAt / 1000)),
CompletedAt: ptr.Of(int32(chunkRunItem.CompletedAt / 1000)),
FailedAt: ptr.Of(int32(chunkRunItem.FailedAt / 1000)),
}
if chunkRunItem.Usage != nil {
chunkMessage.Usage = &run.Usage{
TokenCount: ptr.Of(int32(chunkRunItem.Usage.LlmTotalTokens)),
InputTokens: ptr.Of(int32(chunkRunItem.Usage.LlmPromptTokens)),
OutputTokens: ptr.Of(int32(chunkRunItem.Usage.LlmCompletionTokens)),
}
}
mCM, _ := json.Marshal(chunkMessage)
return mCM
}