Read Agent Conversations

List visible agent conversations in the current workspace, read conversation details by string conversation ID, and page through message sequences and content parts.

Task flow

Workspace agent service handle
              │
              ▼
Page through visible conversations
              │
              ▼
Select conversation ID and read details
              │
              ▼
Page through messages in that conversation

Prerequisites

  1. Complete the endpoint, personal access token, and workspace setup in Use the SDK.

  2. Ensure at least one visible agent conversation exists in the workspace; if the list is empty, send a message first following Invoke Agents and Track Tasks.

List conversations and read messages

Run the example below to fetch up to 20 visible conversations in the workspace, read details for the first conversation (associated agent ID, title, and status), and fetch up to 20 messages with their role, sequence number, and content parts. Select another entry from the returned batch by ID or title when needed.

import json
import os
from urllib.parse import quote

import moi_product_sdk as sdk


def main():
    client = sdk.new_with_personal_access_token(
        os.environ["PRODUCT_API_BASE_URL"],
        os.environ["PRODUCT_API_KEY"],
    )
    agents = client.workspace(os.environ["WORKSPACE_ID"]).agents()

    page = agents.resource_get("conversations", "", sdk.with_limit(20))
    print("conversation total:", page["total"], "batch:", len(page["items"]))
    if not page["items"]:
        print("No visible agent conversations in this workspace.")
        return

    for item in page["items"]:
        print("conversation:", item["id"], "title:", item["title"])

    conversation_id = page["items"][0]["id"]
    tail = "/" + quote(conversation_id, safe="")
    detail = agents.resource_get("conversations", tail)
    if detail["id"] != conversation_id:
        raise RuntimeError("Conversation detail ID does not match the selected ID")
    print(
        "detail:",
        detail["id"],
        "agent_id:",
        detail["agent_id"],
        "title:",
        detail["title"],
        "status:",
        detail["status"],
    )

    messages = agents.resource_get(
        "conversations", tail + "/messages", sdk.with_limit(20)
    )
    print("message total:", messages["total"], "batch:", len(messages["items"]))
    for message in messages["items"]:
        if message["conversation_id"] != conversation_id:
            raise RuntimeError("Message does not belong to the selected conversation")
        print(
            "message:",
            message["id"],
            "role:",
            message["role"],
            "seq:",
            message["seq"],
        )
        print(json.dumps(message["parts"], ensure_ascii=False))


if __name__ == "__main__":
    main()
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/url"
	"os"

	sdk "github.com/matrixorigin/matrixflow/sdk/go-sdk"
)

type conversation struct {
	ID      string `json:"id"`
	AgentID string `json:"agent_id"`
	Title   string `json:"title"`
	Status  string `json:"status"`
}

type message struct {
	ID             string          `json:"id"`
	ConversationID string          `json:"conversation_id"`
	Role           string          `json:"role"`
	Seq            int64           `json:"seq"`
	Parts          json.RawMessage `json:"parts"`
}

type conversationPage struct {
	Items []conversation `json:"items"`
	Total int            `json:"total"`
}

type messagePage struct {
	Items []message `json:"items"`
	Total int       `json:"total"`
}

func readJSON(ctx context.Context, agents *sdk.AgentService, tail string, out any) error {
	data, err := agents.ResourceGet(ctx, "conversations", tail, sdk.WithLimit(20))
	if err != nil {
		return err
	}
	raw, err := json.Marshal(data)
	if err != nil {
		return err
	}
	return json.Unmarshal(raw, out)
}

func run() error {
	client, err := sdk.NewWithPersonalAccessToken(
		os.Getenv("PRODUCT_API_BASE_URL"),
		os.Getenv("PRODUCT_API_KEY"),
	)
	if err != nil {
		return err
	}
	defer client.Close()

	ctx := context.Background()
	agents := client.Agents(os.Getenv("WORKSPACE_ID"))

	var listed conversationPage
	if err := readJSON(ctx, agents, "", &listed); err != nil {
		return err
	}
	fmt.Println("conversation total:", listed.Total, "batch:", len(listed.Items))
	if len(listed.Items) == 0 {
		fmt.Println("No visible agent conversations in this workspace.")
		return nil
	}
	for _, item := range listed.Items {
		fmt.Println("conversation:", item.ID, "title:", item.Title)
	}

	conversationID := listed.Items[0].ID
	tail := "/" + url.PathEscape(conversationID)
	var detail conversation
	if err := readJSON(ctx, agents, tail, &detail); err != nil {
		return err
	}
	if detail.ID != conversationID {
		return fmt.Errorf("conversation detail ID does not match the selected ID")
	}
	fmt.Println("detail:", detail.ID, "agent_id:", detail.AgentID, "title:", detail.Title, "status:", detail.Status)

	var messages messagePage
	if err := readJSON(ctx, agents, tail+"/messages", &messages); err != nil {
		return err
	}
	fmt.Println("message total:", messages.Total, "batch:", len(messages.Items))
	for _, item := range messages.Items {
		if item.ConversationID != conversationID {
			return fmt.Errorf("message does not belong to the selected conversation")
		}
		fmt.Printf("message: %s role: %s seq: %d\n%s\n", item.ID, item.Role, item.Seq, item.Parts)
	}
	return nil
}

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

Pagination and conversation states

  • Conversation lists and per-conversation message lists paginate independently. Advance the offset by the number of returned items until you reach total or receive an empty page.

  • Conversation status describes the stored conversation record; to track the live execution state and artifacts of an individual asynchronous task, query that task ID directly.

  • Agent conversations use string IDs; for workspace-level numeric session records, see Manage Conversation Records.

Next steps

Last updated on