# 保存 LLM 会话消息

```{raw} html
<div class="mo-api-page-show-toc" aria-hidden="true"></div>
```

向当前用户的会话保存一条消息记录。


```http
POST https://api.moi.matrixorigin.cn/v5/workspaces/{workspace_id}/llm/sessions/{session_id}/messages
```

## 调用前准备

`BASE_URL` 使用产品 API 前缀 `https://api.moi.matrixorigin.cn/v5`；专有部署填写对应的产品 API 地址。

[配置同一环境的工作区身份与变量](objects.md#request-prerequisites)。

## 请求

:::::::{div} mo-api-tabs
::::::{tab-set}
:::::{tab-item} 输入示例

```bash
curl --request POST \
  "$BASE_URL/workspaces/$WORKSPACE_ID/llm/sessions/$SESSION_ID/messages" \
  --header "X-API-Key: $MOI_KEY" \
  --header "X-Workspace-ID: $WORKSPACE_ID" \
  --header "Content-Type: application/json" \
  --data-raw '{"source":"moi","role":0,"content":"保存这条消息"}'
```

:::::
:::::{tab-item} 参数说明

| 参数 | 位置 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- | --- |
| `workspace_id` | 路径 | string | 是 | 目标工作区，与 X-Workspace-ID 一致。 |
| `session_id` | 路径 | integer | 是 | 本服务返回的正整数 ID。 |
| `source` | 请求体 | string | 否 | 应用来源字符串；独立于会话来源保存。 |
| `role` | 请求体 | integer | 否 | 消息角色：0=user、1=system、2=assistant、3=agent_tool；省略按 0。 |
| `original_content` | 请求体 | string | 否 | 原始内容文本。 |
| `content` | 请求体 | string | 否 | 消息内容文本；当前接口允许空字符串。 |
| `model` | 请求体 | string | 否 | 作为消息记录保存的模型名称，不触发模型调用。 |
| `status` | 请求体 | string | 否 | 记录状态；空字符串、null 或省略时为 pending。 |
| `response` | 请求体 | string | 否 | 保存的响应文本。 |
| `modified_response` | 请求体 | string | 否 | 保存的修改后响应文本。 |
| `config` | 请求体 | string | 否 | 作为文本保存的配置。 |

成功表示记录已保存，不代表模型执行或回答完成。此接口没有业务 request_id 去重；结果未知时先查询消息，避免重复保存。写入状态是存储字段，不能替代运行任务状态。

:::::
::::::
:::::::

## 成功响应

:::::::{div} mo-api-tabs mo-api-response-tabs
::::::{tab-set}
:::::{tab-item} 响应示例

```json
{
  "code": 0,
  "data": {
    "id": 71,
    "user_id": "user-example",
    "session_id": 41,
    "source": "moi",
    "role": 0,
    "original_content": "",
    "content": "保存这条消息",
    "model": "",
    "status": "pending",
    "response": "",
    "modified_response": "",
    "config": "",
    "created_at": 1794445200,
    "updated_at": 1794445200
  }
}
```

:::::
:::::{tab-item} 字段说明

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `code` | integer | 成功为 0；HTTP 状态码为 201。 |
| `data` | object | [消息记录](objects.md#message-object)。 |

:::::
::::::
:::::::

## 错误响应

[错误格式与读取范围](objects.md#error-contract)说明身份、参数、资源读取与存储失败的不同结果。
