Regenerate Agent Replies¶
Provide revision instructions for a completed agent task and generate a new reply. The program reads the source task’s conversation context ID, sends a branch-mode regeneration control message, and queries the newly created task’s status and artifacts.
Task flow¶
Completed source task ID (SOURCE_TASK_ID)
│
▼
Read source task and extract contextId
│
▼
Send moi.run.control (regenerate)
│
▼
Obtain new_task_id and read artifacts
Prerequisites¶
Complete the endpoint, personal access token, and workspace setup in Use the SDK.
Confirm the agent ID that owns the source task by following Discover and Select Agents.
Obtain a
completedsource task ID from Invoke Agents and Track Tasks, keeping the same identity, workspace, and agent.Generate and save a control ID and control message ID beforehand so you do not mint new identifiers if a network timeout requires checking the outcome.
Set the source task and control identifiers in your terminal:
export AGENT_ID='<agent-id>'
export SOURCE_TASK_ID='<completed-source-task-id>'
export CONTROL_ID="$(python3 -c 'import uuid; print(uuid.uuid4())')"
export CONTROL_MESSAGE_ID="$(python3 -c 'import uuid; print(uuid.uuid4())')"
Request regeneration and inspect the new task¶
The example requests shorter sentences while preserving citations in a conversation branch (conversationMode set to "branch"). Regeneration invokes models and potentially bound tools again; review any external write effects from the source task before running it.
import json
import os
import uuid
import moi_product_sdk as sdk
client = sdk.new_with_personal_access_token(
os.environ["PRODUCT_API_BASE_URL"],
os.environ["PRODUCT_API_KEY"],
)
workspace = client.workspace(os.environ["WORKSPACE_ID"])
agent = workspace.agent_by_id(os.environ["AGENT_ID"])
source_id = os.environ["SOURCE_TASK_ID"]
source = sdk.agent_a2a_payload(agent.get_task(sdk.AgentTaskRequest(source_id)))
if source.get("id") != source_id or source.get("status", {}).get("state") != "completed":
raise RuntimeError("Select a completed source task")
context_id = source["contextId"]
control_id = os.environ["CONTROL_ID"]
message_id = os.environ["CONTROL_MESSAGE_ID"]
params = {
"message": {
"kind": "message",
"role": "user",
"messageId": message_id,
"contextId": context_id,
"taskId": source_id,
"parts": [
{
"kind": "data",
"data": {
"type": "moi.run.control",
"version": 1,
"controlId": control_id,
"action": "regenerate",
"rerunMode": "same_manifest",
"conversationMode": "branch",
"guidance": "Use shorter sentences and preserve all cited sources.",
"target": {
"agentId": os.environ["AGENT_ID"],
"contextId": context_id,
"taskId": source_id,
},
},
}
],
}
}
try:
result = agent.a2a(
sdk.A2ARequest("message/send", id_=str(uuid.uuid4()), params=params)
)
except sdk.Error as error:
if error.details.get("task_id"):
print("task_id:", error.details["task_id"])
raise
ack = sdk.agent_a2a_payload(result)
new_id = ack.get("id", "") if ack.get("kind") == "task" else ""
if ack.get("kind") == "message":
for part in ack.get("parts", []):
data = part.get("data", {})
if (
data.get("type") == "moi.run.control.result"
and data.get("controlId") == control_id
):
new_id = data.get("taskId", "")
if not new_id or new_id == source_id:
raise RuntimeError("No new task ID confirmed; retain the original control request")
print("new_task_id:", new_id)
payload = sdk.agent_a2a_payload(agent.get_task(sdk.AgentTaskRequest(new_id)))
print("task_id:", payload.get("id"))
print("contextId:", payload.get("contextId"))
print("state:", payload.get("status", {}).get("state"))
print(
"status message:",
json.dumps(payload.get("status", {}).get("message"), ensure_ascii=False),
)
for artifact in payload.get("artifacts", []):
print("artifactId:", artifact.get("artifactId"))
print("parts:", json.dumps(artifact.get("parts", []), ensure_ascii=False))
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"time"
sdk "github.com/matrixorigin/matrixflow/sdk/go-sdk"
)
func main() {
ctx := context.Background()
client, err := sdk.NewWithPersonalAccessToken(
os.Getenv("PRODUCT_API_BASE_URL"),
os.Getenv("PRODUCT_API_KEY"),
)
if err != nil {
panic(err)
}
defer client.Close()
workspace, err := client.Workspace(os.Getenv("WORKSPACE_ID"))
if err != nil {
panic(err)
}
agent, err := workspace.AgentByID(os.Getenv("AGENT_ID"))
if err != nil {
panic(err)
}
sourceID := os.Getenv("SOURCE_TASK_ID")
sourceResult, err := agent.GetTask(ctx, sdk.AgentTaskRequest{TaskID: sourceID})
if err != nil {
panic(err)
}
source, err := sdk.AgentA2APayload(sourceResult)
if err != nil {
panic(err)
}
sourceStatus, _ := source["status"].(map[string]any)
if source["id"] != sourceID || sourceStatus["state"] != "completed" {
panic("Select a completed source task")
}
contextID, _ := source["contextId"].(string)
controlID := os.Getenv("CONTROL_ID")
messageID := os.Getenv("CONTROL_MESSAGE_ID")
if controlID == "" || messageID == "" {
panic("Set both CONTROL_ID and CONTROL_MESSAGE_ID before sending")
}
params, err := json.Marshal(map[string]any{
"message": map[string]any{
"kind": "message",
"role": "user",
"messageId": messageID,
"contextId": contextID,
"taskId": sourceID,
"parts": []any{
map[string]any{
"kind": "data",
"data": map[string]any{
"type": "moi.run.control",
"version": 1,
"controlId": controlID,
"action": "regenerate",
"rerunMode": "same_manifest",
"conversationMode": "branch",
"guidance": "Use shorter sentences and preserve all cited sources.",
"target": map[string]any{
"agentId": os.Getenv("AGENT_ID"),
"contextId": contextID,
"taskId": sourceID,
},
},
},
},
},
})
if err != nil {
panic(err)
}
result, err := agent.A2A(ctx, sdk.A2ARequest{
JSONRPC: "2.0",
ID: fmt.Sprintf("request-%d", time.Now().UnixNano()),
Method: sdk.A2AMethodSend,
Params: params,
})
if err != nil {
var apiError *sdk.Error
if errors.As(err, &apiError) && apiError.Details["task_id"] != "" {
fmt.Println("task_id:", apiError.Details["task_id"])
}
panic(err)
}
ack, err := sdk.AgentA2APayload(result)
if err != nil {
panic(err)
}
newID := ""
if ack["kind"] == "task" {
newID, _ = ack["id"].(string)
}
if ack["kind"] == "message" {
parts, _ := ack["parts"].([]any)
for _, part := range parts {
value, _ := part.(map[string]any)
data, _ := value["data"].(map[string]any)
if data["type"] == "moi.run.control.result" && data["controlId"] == controlID {
newID, _ = data["taskId"].(string)
}
}
}
if newID == "" || newID == sourceID {
panic("No new task ID confirmed; retain the original control request")
}
fmt.Println("new_task_id:", newID)
current, err := agent.GetTask(ctx, sdk.AgentTaskRequest{TaskID: newID})
if err != nil {
panic(err)
}
payload, err := sdk.AgentA2APayload(current)
if err != nil {
panic(err)
}
fmt.Println("task_id:", payload["id"], "contextId:", payload["contextId"])
status, _ := payload["status"].(map[string]any)
fmt.Println("state:", status["state"])
message, _ := json.Marshal(status["message"])
fmt.Println("status message:", string(message))
artifacts, _ := json.Marshal(payload["artifacts"])
fmt.Println("artifacts:", string(artifacts))
}
Limitations and notes¶
The response can be either the new task object directly or a control acknowledgement carrying
moi.run.control.result; acreatedacknowledgement confirms creation only, so verify final completion through the new task’scompletedstate andartifacts.After a network timeout or disconnect, retain the original
CONTROL_ID,CONTROL_MESSAGE_ID, and any returned new task ID to inspect task state before retrying, avoiding duplicate submissions with new control IDs.This workflow runs the model again to produce a new answer; to edit stored session text without re-invoking a model, see Manage Conversation Records.