對話與回憶概述

AgentSession 來保持召喚間的對話上下文。

當會話使用服務管理儲存時,可能會包含不透明的服務端會話 ID。 OpenAI 的回應與對話 ID 預設是針對後備的 API 金鑰或專案;若託管代理使用同一金鑰或專案給多個終端使用者,請將這些 ID 儲存在伺服器端,並在恢復前驗證已認證的使用者或租戶。 詳情請參見會議。

核心使用模式

大多數應用程式遵循相同的流程:

  1. 建立一個會話 (CreateSessionAsync()
  2. 把那場課交給每一位 RunAsync(...)
  3. 從序列化狀態 DeserializeSessionAsync(...) 還原
  4. 請繼續提供服務對話ID(依代理人而異,例如) myChatClientAgent.CreateSessionAsync("existing-id")
  1. 建立一個會話 (create_session()
  2. 把那場課交給每一位 run(...)
  3. 透過服務對話 ID(get_session(...))或序列化狀態來進行 Rehydrate
  1. 建立一個會話 (CreateSession(...)
  2. 將該工作階段透過 agent.WithSession(session) 傳遞給每個 RunText(...)
  3. 使用 json.Unmarshal(...) 從序列化狀態重新還原到 agent.Session

Go agent 套件提供對話狀態的核心類型: agent.Session 與對話綁定的鍵值狀態,以及 agent.ContextProvider 上下文注入與持久性。

// Create and reuse a session
AgentSession session = await agent.CreateSessionAsync();

var first = await agent.RunAsync("My name is Alice.", session);
var second = await agent.RunAsync("What is my name?", session);

// Persist and restore later
var serialized = agent.SerializeSession(session);
AgentSession resumed = await agent.DeserializeSessionAsync(serialized);
# Create and reuse a session
session = agent.create_session()

first = await agent.run("My name is Alice.", session=session)
second = await agent.run("What is my name?", session=session)

# Rehydrate by service conversation ID when needed
service_session = agent.get_session(service_session_id="<service-conversation-id>")

# Persist and restore later
serialized = session.to_dict()
resumed = AgentSession.from_dict(serialized)
session, err := a.CreateSession(ctx)
if err != nil {
    panic(err)
}

使用會話進行多回合對話

resp, _ := a.RunText(ctx, "My name is Alice.", agent.WithSession(session)).Collect()
resp, _ = a.RunText(ctx, "What is my name?", agent.WithSession(session)).Collect()

持久化會話

會話可序列化為 JSON 儲存,之後再恢復:

data, err := json.Marshal(session)
if err != nil {
    panic(err)
}
// store data...

// later:
var resumed agent.Session
if err := json.Unmarshal(data, &resumed); err != nil {
    panic(err)
}

resp, err := a.RunText(ctx, "Continue from where we left off.", agent.WithSession(&resumed)).Collect()

導覽地圖

頁面 專注
會議 AgentSession 結構與序列化
情境提供者 內建與自訂的上下文/歷史提供者模式
上下文壓縮 有效管理對話成長
儲存空間 內建儲存模式與外部持久化策略

後續步驟