跳至主要內容

OpenAI Responses API Conversations

OpenAI Responses API Conversations 提供 Mastra Agent 作為 Responses API 時的對話管理功能。它提供用於在 Mastra 中建立、取得、刪除和查看基於 thread 的對話的方法。

此 API 是 OpenAI Responses API 的後續配套功能。儲存的 Responses 呼叫會傳回 conversation_id;在 Mastra 中,該值就是原始 memory threadId。需要直接操作該 thread 時,請使用 client.conversations

此 API 目前處於實驗階段。

與 OpenAI Responses 的關係
「與 OpenAI Responses 的關係」的直接連結

使用 OpenAI Responses API 產生和續寫內容:

const response = await client.responses.create({
agent_id: 'support-agent',
input: 'Start a support thread',
store: true,
})

console.log(response.conversation_id)

需要查看或管理已儲存的 thread 時,請使用 Conversations API:

const conversation = await client.conversations.retrieve(response.conversation_id!)
const items = await client.conversations.items.list(response.conversation_id!)

使用範例
「使用範例」的直接連結

import { MastraClient } from '@mastra/client-js'

const client = new MastraClient({
baseUrl: 'http://localhost:4111',
})

const conversation = await client.conversations.create({
agent_id: 'support-agent',
})

console.log(conversation.id)

方法
「方法」的直接連結

生命週期
「生命週期」的直接連結

create(params)
「createparams」的直接連結

為所選 Agent 建立新的對話 thread。

const conversation = await client.conversations.create({
agent_id: 'support-agent',
title: 'Billing support',
})

傳回: Promise<Conversation>

retrieve(conversationId, requestContext?)
「retrieveconversationid-requestcontext」的直接連結

透過 thread ID 取得對話。

const conversation = await client.conversations.retrieve('thread_123')

console.log(conversation.thread)

傳回: Promise<Conversation>

delete(conversationId, requestContext?)
「deleteconversationid-requestcontext」的直接連結

透過 thread ID 刪除對話。

const deleted = await client.conversations.delete('thread_123')

console.log(deleted.deleted)

傳回: Promise<ConversationDeleted>

項目
「項目」的直接連結

items.list(conversationId, requestContext?)
「itemslistconversationid-requestcontext」的直接連結

列出對話中儲存的項目。

const items = await client.conversations.items.list('thread_123')

console.log(items.data)

傳回: Promise<ConversationItemsPage>

回應結構
「回應結構」的直接連結

create()retrieve() 傳回包含以下內容的對話物件:

  • id:原始 thread ID
  • object:始終為 'conversation'
  • thread:儲存的 thread 記錄

delete() 傳回:

  • id:原始 thread ID
  • object:始終為 'conversation.deleted'
  • deleted:始終為 true

items.list() 傳回:

  • object:始終為 'list'
  • data:對話項目,例如 messagefunction_callfunction_call_output
  • first_id:目前頁面中第一個項目的 ID
  • last_id:目前頁面中最後一個項目的 ID
  • has_more:目前頁面之後是否還有更多項目

參數
「參數」的直接連結

agent_id:

string
必填。擁有對話 memory 的已註冊 Mastra Agent。

conversation_id?:

string
選用。用作原始 thread ID 的對話 ID。

resource_id?:

string
選用。與對話 thread 關聯的資源 ID。

title?:

string
選用。與對話一起儲存的 thread 標題。

metadata?:

Record<string, unknown>
選用。與對話一起儲存的 thread 中繼資料。

requestContext?:

RequestContext | Record<string, any>
選用。轉發到 Mastra 伺服器的請求情境。