eino icon indicating copy to clipboard operation
eino copied to clipboard

如何使用ChatModelAgentResumeData的HistoryModifier

Open o0O96O0o opened this issue 10 months ago • 4 comments

当我在使用中断恢复human-in-the-loop是如果需要在调用ResumeWithParams前,修改模型的上下文信息应该如何实现呢? 我看到代码里有个一个struct叫ChatModelAgentResumeData其中提供了修改上下文的钩子但是没有相应的示例与文档。

context := contexts[0]
var chatModelAgentId string
var toolId string
for context != nil {
	lastSegment := context.Address[len(context.Address)-1]

	if lastSegment.Type == adk.AddressSegmentTool {
		// This is a tool - capture its ID
		toolId = context.ID
	} else if lastSegment.Type == adk.AddressSegmentAgent {
		// The first agent you encounter in the chain is the ChatModelAgent
		chatModelAgentId = context.ID
		break
	}

	context = context.Parent
}

这是我获取id的方式,类似单测但是在multi-agent中好像不起作用。 请问有什么好的方式实现multi-agent中子agent调用打断工具resume时修改上下文吗?

o0O96O0o avatar Jan 09 '26 17:01 o0O96O0o

需要先通过 InterruptCtx.Parent 字段去找到 ChatModelAgent 的 Interrupt ID,在 ResumeWithParams 的时候把这个 ID -> ChatModelAgentResumeData 传进去

shentongmartin avatar Jan 13 '26 08:01 shentongmartin

上面那就是我的使用方式,是通过parent去找到对应的ChatModelAgent Id 以eino-examples为例子:

package main

import (
	"bufio"
	"context"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/cloudwego/eino/adk"

	"github.com/cloudwego/eino-examples/adk/common/prints"
	"github.com/cloudwego/eino-examples/adk/common/store"
	"github.com/cloudwego/eino-examples/adk/common/tool"
)

func main() {
	ctx := context.Background()
	a := NewTicketBookingAgent()
	runner := adk.NewRunner(ctx, adk.RunnerConfig{
		EnableStreaming: true, // you can disable streaming here
		Agent:           a,

		// provide a CheckPointStore for eino to persist the execution state of the agent for later resumption.
		// Here we use an in-memory store for simplicity.
		// In the real world, you can use a distributed store like Redis to persist the checkpoints.
		CheckPointStore: store.NewInMemoryStore(),
	})
	iter := runner.Query(ctx, "book a ticket for Martin, to Beijing, on 2025-12-01, the phone number is 1234567. directly call tool.", adk.WithCheckPointID("1"))

	var lastEvent *adk.AgentEvent
	for {
		event, ok := iter.Next()
		if !ok {
			break
		}
		if event.Err != nil {
			log.Fatal(event.Err)
		}

		prints.Event(event)

		lastEvent = event
	}

	if lastEvent == nil {
		log.Fatal("last event is nil")
	}
	if lastEvent.Action == nil || lastEvent.Action.Interrupted == nil {
		log.Fatal("last event is not an interrupt event")
	}

	// this interruptID is crucial 'locator' for Eino to know where the interrupt happens,
	// so when resuming later, you have to provide this same `interruptID` along with the approval result back to Eino
	interruptContext := lastEvent.Action.Interrupted.InterruptContexts[0]
	var chatModelAgentId string
	var toolId string
	for interruptContext != nil {
		lastSegment := interruptContext.Address[len(interruptContext.Address)-1]

		if lastSegment.Type == adk.AddressSegmentTool {
			// This is a tool - capture its ID
			toolId = interruptContext.ID
		} else if lastSegment.Type == adk.AddressSegmentAgent {
			// The first agent you encounter in the chain is the ChatModelAgent
			chatModelAgentId = interruptContext.ID
			break
		}

		interruptContext = interruptContext.Parent
	}

	var apResult *tool.ApprovalResult
	for {
		scanner := bufio.NewScanner(os.Stdin)
		fmt.Print("your input here: ")
		scanner.Scan()
		fmt.Println()
		nInput := scanner.Text()
		if strings.ToUpper(nInput) == "Y" {
			apResult = &tool.ApprovalResult{Approved: true}
			break
		} else if strings.ToUpper(nInput) == "N" {
			// Prompt for reason when denying
			fmt.Print("Please provide a reason for denial: ")
			scanner.Scan()
			reason := scanner.Text()
			fmt.Println()
			apResult = &tool.ApprovalResult{Approved: false, DisapproveReason: &reason}
			break
		}

		fmt.Println("invalid input, please input Y or N")
	}

	// here we directly resumes right in the same instance where the original `Runner.Query` happened.
	// In the real world, the original `Runner.Run/Query` and the subsequent `Runner.ResumeWithParams`
	// can happen in different processes or machines, as long as you use the same `CheckPointID`,
	// and you provided a distributed `CheckPointStore` when creating the `Runner` instance.

	resumeData := &adk.ChatModelAgentResumeData{
		HistoryModifier: func(ctx context.Context, history []adk.Message) []adk.Message {
			// Example: Update a specific message in history
			history[0].Content = "new user message"
			return history
		},
	}

	iter, err := runner.ResumeWithParams(ctx, "1", &adk.ResumeParams{
		Targets: map[string]any{
			toolId:           apResult,
			chatModelAgentId: resumeData,
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	for {
		event, ok := iter.Next()
		if !ok {
			break
		}

		if event.Err != nil {
			log.Fatal(event.Err)
		}

		prints.Event(event)
	}
}

HistoryModifier: func(ctx context.Context, history []adk.Message) []adk.Message {	// Example: Update a specific message in history
	history[0].Content = "new user message"
	return history
},

debug时候这部分还是没有执行,最终的trace:

[
  {
    "messages": [
      {
        "role": "system",
        "content": "You are an expert ticket booker.\nBased on the user's request, use the \"BookTicket\" tool to book tickets."
      },
      {
        "role": "user",
        "content": "book a ticket for Martin, to Beijing, on 2025-12-01, the phone number is 1234567. directly call tool."
      },
      {
        "role": "assistant",
        "tool_calls": [
          {
            "id": "call_F6yojovJHNEPJD5vYk6Vl0ST",
            "type": "function",
            "function": {
              "name": "BookTicket",
              "arguments": "{\"location\":\"Beijing\",\"passenger_name\":\"Martin\",\"passenger_phone_number\":\"1234567\"}"
            }
          }
        ]
      },
      {
        "role": "tool",
        "content": "tool 'BookTicket' disapproved, reason: n",
        "tool_call_id": "call_F6yojovJHNEPJD5vYk6Vl0ST"
      }
    ]
  }
]

请问这样子用有什么问题吗?

o0O96O0o avatar Jan 13 '26 12:01 o0O96O0o

else if lastSegment.Type == adk.AddressSegmentAgent { // The first agent you encounter in the chain is the ChatModelAgent chatModelAgentId = interruptContext.ID

这里可能有问题。得判断一下 AddressSegment.ID 是不是你想要修改的 ChatModelAgent 的 AgentName

shentongmartin avatar Jan 13 '26 12:01 shentongmartin

例子里面是单agent系统应该不会有其他的AgentName我需要怎么找到对应的interruptId呢。根据Parent的Address同样也是TicketBooker(再往上也是),请问这个层级代表什么呢? 类似这样(root在最下面) Id: 120a3cdd-56ce-4174-a29e-3f6bcb07874c Name(Address.Id): BookTicket Type: tool -> Id: 97e081d1-93f4-4d52-8b9c-4d1cb7df8e56 Name(Address.Id): TicketBooker Type: agent -> Id: f9d921dd-e5d7-4e1d-9e69-af2eb0be7c03 Name(Address.Id): TicketBooker Type: agent -> Id: aef8e5f1-537e-497c-bc0c-c708d69f9195 Name(Address.Id): TicketBooker Type: agent -> nil

o0O96O0o avatar Jan 14 '26 10:01 o0O96O0o