<span id="管理会话记录与消息"></span>
<span id="管理会话记录"></span>

# Manage Conversation Records

Use the AI Studio SDK to query persisted conversations and messages visible to the current identity in a workspace, update conversation titles conditionally, or delete conversations that are no longer needed. Persisted conversations use numeric session IDs; to read conversation history produced by agent runs, see [Read Agent Conversations](智能体/管理会话和消息.md#sdk-ai-studio-sessions-s1).

(sdk-ai-studio-conversation-records-flow)=
<span id="任务流程"></span>

## Task flow

```text
Workspace conversation service
            │
            ▼
List persisted sessions by page ──▶ Select numeric session ID
                                          │
                                          ├── Read session details and messages
                                          └── Update title conditionally or delete session
```

(sdk-ai-studio-conversation-records-prepare)=
<span id="准备"></span>

## Prerequisites

1. Complete the endpoint, personal access token, and workspace setup in [Use the SDK](../../quickstart/ai-studio/sdk.md).
2. Ensure the workspace contains persisted conversations visible to the current identity; select a target session ID from the list results in the next step.

(sdk-ai-studio-conversation-records-read)=
<span id="查询会话与消息"></span>

## Query sessions and messages

List visible conversations by page first, then use the numeric ID of the target conversation to read its details and messages.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
import os

import moi_product_sdk as sdk

client = sdk.new_with_personal_access_token(
    os.environ["PRODUCT_API_BASE_URL"],
    os.environ["PRODUCT_API_KEY"],
)
service = client.conversations(os.environ["WORKSPACE_ID"])

page = service.list_sessions(
    sdk.with_query_param("page", "1"),
    sdk.with_query_param("page_size", "20"),
)
print("Total sessions:", page.total)
for item in page.sessions:
    print(item.id, item.title, item.source)

if not page.sessions:
    raise SystemExit("No persisted sessions found in this workspace")

session_id = page.sessions[0].id
session = service.get_session(session_id)
messages = service.list_messages(
    session_id,
    sdk.with_query_param("limit", "50"),
)
print("Selected session:", session.id, session.title)
for message in messages.messages:
    print(message.id, message.role, message.status, message.content)
```

::::

::::{tab-item} Go
:sync: go

```go
package main

import (
	"context"
	"fmt"
	"os"

	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)
	}
	service := client.Conversations(os.Getenv("WORKSPACE_ID"))

	page, err := service.ListSessions(
		ctx,
		sdk.WithQueryParam("page", "1"),
		sdk.WithQueryParam("page_size", "20"),
	)
	if err != nil {
		panic(err)
	}
	fmt.Println("Total sessions:", page.GetTotal())
	for _, item := range page.GetSessions() {
		fmt.Println(item.GetId(), item.GetTitle(), item.GetSource())
	}
	if len(page.GetSessions()) == 0 {
		return
	}

	sessionID := page.GetSessions()[0].GetId()
	session, err := service.GetSession(ctx, sessionID)
	if err != nil {
		panic(err)
	}
	messages, err := service.ListMessages(
		ctx,
		sessionID,
		sdk.WithQueryParam("limit", "50"),
	)
	if err != nil {
		panic(err)
	}
	fmt.Println("Selected session:", session.GetId(), session.GetTitle())
	for _, message := range messages.GetMessages() {
		fmt.Println(message.GetId(), message.GetRole(), message.GetStatus(), message.GetContent())
	}
}
```

::::

:::::

Conversation lists paginate by page number and page size, and accept optional filter parameters for source, keyword, or tag. Message lists paginate forward by cursor: read the initial page first, then pass the ID of the last returned message through the `after` query parameter until an empty list is returned. The total count reflects all messages in the conversation and does not decrease as the cursor advances.

(sdk-ai-studio-conversation-records-maintain)=
<span id="维护会话"></span>
<span id="更新或删除会话"></span>

## Update or delete a session

When updating a conversation title, you can pass the expected previous title as an optimistic check. If the current title on the server no longer matches, the service returns the current conversation without overwriting the title; compare the returned title to confirm whether the update took effect. Passing an empty title or configuration string leaves existing content unchanged.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
expected_title = session.title
updated = service.update_session(
    session_id,
    sdk.ConversationWorkspaceSessionRequest(
        title="Archived conversation",
        expected_title=expected_title,
    ),
)
print("Updated title:", updated.title)
```

::::

::::{tab-item} Go
:sync: go

```go
expectedTitle := session.GetTitle()
updated, err := service.UpdateSession(ctx, sessionID, &sdk.ConversationWorkspaceSessionRequest{
	Title:         "Archived conversation",
	ExpectedTitle: &expectedTitle,
})
if err != nil {
	panic(err)
}
fmt.Println("Updated title:", updated.GetTitle())
```

::::

:::::

When a conversation and its messages are no longer needed, delete the conversation by its numeric session ID and query the conversation list again to confirm removal. Modifying stored assistant response text updates the persisted record without triggering new model inference.

(sdk-ai-studio-conversation-records-next)=
<span id="下一步"></span>

## Next steps

- [Read Agent Conversations](智能体/管理会话和消息.md)
- [Regenerate Agent Replies](智能体/重新生成智能体回答.md)
