generated from cloudwego/.github
-
Notifications
You must be signed in to change notification settings - Fork 718
feat: Agent callbacks and Multi-Agent definition for adk #590
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
N3kox
wants to merge
4
commits into
main
Choose a base branch
from
feat/adk_cb
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
69c1559
feat: Agent callbacks and Multi-Agent definition for adk
N3kox c756302
fix: duplicate graph callback injection in ChatModelAgent.Run
N3kox c726a20
refactor: EntranceType to InvocationType
N3kox 72ff0d0
refactor: rename AgentContext.EntranceType to InvocationType, fix gol…
N3kox File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,182 @@ | ||
| /* | ||
| * 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 adk | ||
|
|
||
| import ( | ||
| "context" | ||
|
|
||
| "github.com/cloudwego/eino/components/tool" | ||
| "github.com/cloudwego/eino/compose" | ||
| ) | ||
|
|
||
| // AgentMiddleware provides hooks to customize agent behavior at various stages of execution. | ||
| type AgentMiddleware struct { | ||
| // Name of the middleware, default empty. This will be used for middleware deduplication. | ||
| Name string | ||
|
|
||
| // AdditionalInstruction adds supplementary text to the agent's system instruction. | ||
| // This instruction is concatenated with the base instruction before each chat model call. | ||
| AdditionalInstruction string | ||
|
|
||
| // AdditionalTools adds supplementary tools to the agent's available toolset. | ||
| // These tools are combined with the tools configured for the agent. | ||
| AdditionalTools []tool.BaseTool | ||
|
|
||
| // BeforeChatModel is called before each ChatModel invocation, allowing modification of the agent state. | ||
| BeforeChatModel func(context.Context, *ChatModelAgentState) error | ||
|
|
||
| // AfterChatModel is called after each ChatModel invocation, allowing modification of the agent state. | ||
| AfterChatModel func(context.Context, *ChatModelAgentState) error | ||
|
|
||
| // WrapToolCall wraps tool calls with custom middleware logic. | ||
| // Each middleware contains Invokable and/or Streamable functions for tool calls. | ||
| WrapToolCall compose.ToolMiddleware | ||
|
|
||
| // BeforeAgent is called before the agent starts executing. It allows modifying the context | ||
| // or performing any setup actions before the agent begins processing. | ||
| // When an error is returned: | ||
| // 1. The framework will immediately return an AsyncIterator containing only this error | ||
| // 2. Subsequent BeforeAgent steps in other middlewares will be interrupted | ||
| // 3. The OnEvents handlers in previously executed middlewares will be invoked | ||
| BeforeAgent func(ctx context.Context, ac *AgentContext) (nextContext context.Context, err error) | ||
|
|
||
| // OnEvents is called to handle events generated by the agent during execution. | ||
| // - iter: The iterator contains the original output from the agent or the processed output from the previous middlewares. | ||
| // - gen: The generator is used to send the processed events to the next middleware or directly as output. | ||
| // This allows for filtering, transforming, or adding events in the middleware chain. | ||
| OnEvents func(ctx context.Context, ac *AgentContext, iter *AsyncIterator[*AgentEvent], gen *AsyncGenerator[*AgentEvent]) | ||
| } | ||
|
|
||
| // AgentMiddlewareChecker is an interface that agents can implement to indicate | ||
| // whether they support and enable middleware functionality. | ||
| // Agents implementing this interface will execute middlewares internally; | ||
| // otherwise, middlewares will be executed outside the agent by Runner. | ||
| type AgentMiddlewareChecker interface { | ||
| IsAgentMiddlewareEnabled() bool | ||
| } | ||
|
|
||
| // ChatModelAgentState represents the state of a chat model agent during conversation. | ||
| type ChatModelAgentState struct { | ||
| // Messages contains all messages in the current conversation session. | ||
| Messages []Message | ||
| } | ||
|
|
||
| type InvocationType string | ||
|
|
||
| const ( | ||
| // InvocationTypeRun indicates the agent is starting a new execution from scratch. | ||
| InvocationTypeRun InvocationType = "Run" | ||
| // InvocationTypeResume indicates the agent is resuming a previously interrupted execution. | ||
| InvocationTypeResume InvocationType = "Resume" | ||
| ) | ||
|
|
||
| // AgentContext contains the context information for an agent's execution. | ||
| // It provides access to input data, resume information, and execution options. | ||
| type AgentContext struct { | ||
| // AgentInput contains the input data for the agent's execution. | ||
| AgentInput *AgentInput | ||
| // ResumeInfo contains information needed to resume a previously interrupted execution. | ||
| ResumeInfo *ResumeInfo | ||
| // AgentRunOptions contains options for configuring the agent's execution. | ||
| AgentRunOptions []AgentRunOption | ||
|
|
||
| // internal properties, read only | ||
| agentName string | ||
| invocationType InvocationType | ||
| } | ||
|
|
||
| func (a *AgentContext) AgentName() string { | ||
| return a.agentName | ||
| } | ||
|
|
||
| func (a *AgentContext) InvocationType() InvocationType { | ||
| return a.invocationType | ||
| } | ||
|
|
||
| func isAgentMiddlewareEnabled(a Agent) bool { | ||
| if c, ok := a.(AgentMiddlewareChecker); ok && c.IsAgentMiddlewareEnabled() { | ||
| return true | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| func newAgentMWHelper(mws ...AgentMiddleware) *agentMWHelper { | ||
| helper := &agentMWHelper{} | ||
| dedup := make(map[string]struct{}) | ||
| for _, mw := range mws { | ||
| if _, found := dedup[mw.Name]; mw.Name != "" && found { | ||
| continue | ||
| } | ||
| dedup[mw.Name] = struct{}{} | ||
| helper.beforeAgentFns = append(helper.beforeAgentFns, mw.BeforeAgent) | ||
| helper.onEventsFns = append(helper.onEventsFns, mw.OnEvents) | ||
| } | ||
| return helper | ||
| } | ||
|
|
||
| type agentMWHelper struct { | ||
| beforeAgentFns []func(ctx context.Context, ac *AgentContext) (nextContext context.Context, err error) | ||
| onEventsFns []func(ctx context.Context, ac *AgentContext, iter *AsyncIterator[*AgentEvent], gen *AsyncGenerator[*AgentEvent]) | ||
| } | ||
|
|
||
| func (a *agentMWHelper) execBeforeAgents(ctx context.Context, ac *AgentContext) (context.Context, *AsyncIterator[*AgentEvent]) { | ||
| var err error | ||
| for i, beforeAgent := range a.beforeAgentFns { | ||
| if beforeAgent == nil { | ||
| continue | ||
| } | ||
| ctx, err = beforeAgent(ctx, ac) | ||
| if err != nil { | ||
| iter, gen := NewAsyncIteratorPair[*AgentEvent]() | ||
| gen.Send(&AgentEvent{Err: err}) | ||
| gen.Close() | ||
| return ctx, a.execOnEventsFromIndex(ctx, ac, i-1, iter) | ||
| } | ||
| } | ||
| return ctx, nil | ||
| } | ||
|
|
||
| func (a *agentMWHelper) execOnEvents(ctx context.Context, ac *AgentContext, iter *AsyncIterator[*AgentEvent]) *AsyncIterator[*AgentEvent] { | ||
| return a.execOnEventsFromIndex(ctx, ac, len(a.onEventsFns)-1, iter) | ||
| } | ||
|
|
||
| func (a *agentMWHelper) execOnEventsFromIndex(ctx context.Context, ac *AgentContext, fromIdx int, iter *AsyncIterator[*AgentEvent]) *AsyncIterator[*AgentEvent] { | ||
| for idx := fromIdx; idx >= 0; idx-- { | ||
| onEvents := a.onEventsFns[idx] | ||
| if onEvents == nil { | ||
| continue | ||
| } | ||
| i, g := NewAsyncIteratorPair[*AgentEvent]() | ||
| onEvents(ctx, ac, iter, g) | ||
| iter = i | ||
| } | ||
| return iter | ||
| } | ||
|
|
||
| var globalAgentMiddlewares []AgentMiddleware | ||
|
|
||
| // AppendGlobalAgentMiddlewares is used to add global Agent middlewares. | ||
| // These middlewares execute at the outermost layer of every Agent (following the "onion model" pattern). | ||
| func AppendGlobalAgentMiddlewares(mws ...AgentMiddleware) { | ||
| globalAgentMiddlewares = append(globalAgentMiddlewares, mws...) | ||
| } | ||
|
|
||
| // GetGlobalAgentMiddlewares is used to retrieve global Agent middlewares. | ||
| // This method is typically employed by custom Agent that has implemented the AgentMiddlewareChecker interface. | ||
| func GetGlobalAgentMiddlewares() []AgentMiddleware { | ||
| return globalAgentMiddlewares | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
mw.BeforeAgents, mw.OnEvents 判空?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
bydesign,BeforeAgents 第 n 个立刻返回时,前 n-1 个 OnEvents 要执行,设置空的 func 是为了 padding index,判空由运行时处理