You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.8 KiB
Go

/*
* Copyright 2025 CloudWeGo 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 einoagent
import (
"context"
"github.com/cloudwego/eino-ext/components/retriever/redis"
"github.com/cloudwego/eino/compose"
"github.com/cloudwego/eino/flow/agent/react"
"github.com/cloudwego/eino/schema"
)
type EinoAgentBuildConfig struct {
ChatTemplateKeyOfChatTemplate *ChatTemplateConfig
ReactAgentKeyOfLambda *react.AgentConfig
RedisRetrieverKeyOfRetriever *redis.RetrieverConfig
}
type BuildConfig struct {
EinoAgent *EinoAgentBuildConfig
}
func BuildEinoAgent(ctx context.Context, config *BuildConfig) (r compose.Runnable[*UserMessage, *schema.Message], err error) {
const (
InputToQuery = "InputToQuery"
ChatTemplate = "ChatTemplate"
ReactAgent = "ReactAgent"
RedisRetriever = "RedisRetriever"
InputToHistory = "InputToHistory"
)
g := compose.NewGraph[*UserMessage, *schema.Message]()
_ = g.AddLambdaNode(InputToQuery, compose.InvokableLambdaWithOption(NewInputToQuery),
compose.WithNodeName("UserMessageToQuery"))
chatTemplateKeyOfChatTemplate, err := NewChatTemplate(ctx, config.EinoAgent.ChatTemplateKeyOfChatTemplate)
if err != nil {
return nil, err
}
_ = g.AddChatTemplateNode(ChatTemplate, chatTemplateKeyOfChatTemplate)
reactAgentKeyOfLambda, err := NewReactAgent(ctx, config.EinoAgent.ReactAgentKeyOfLambda)
if err != nil {
return nil, err
}
_ = g.AddLambdaNode(ReactAgent, reactAgentKeyOfLambda, compose.WithNodeName("ReAct Agent"))
redisRetrieverKeyOfRetriever, err := NewRedisRetriever(ctx, config.EinoAgent.RedisRetrieverKeyOfRetriever)
if err != nil {
return nil, err
}
_ = g.AddRetrieverNode(RedisRetriever, redisRetrieverKeyOfRetriever, compose.WithOutputKey("documents"))
_ = g.AddLambdaNode(InputToHistory, compose.InvokableLambdaWithOption(NewInputToHistory),
compose.WithNodeName("UserMessageToVariables"))
_ = g.AddEdge(compose.START, InputToQuery)
_ = g.AddEdge(compose.START, InputToHistory)
_ = g.AddEdge(ReactAgent, compose.END)
_ = g.AddEdge(InputToQuery, RedisRetriever)
_ = g.AddEdge(RedisRetriever, ChatTemplate)
_ = g.AddEdge(InputToHistory, ChatTemplate)
_ = g.AddEdge(ChatTemplate, ReactAgent)
r, err = g.Compile(ctx, compose.WithGraphName("EinoAgent"), compose.WithNodeTriggerMode(compose.AllPredecessor))
if err != nil {
return nil, err
}
return r, err
}