Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

Introduction to Agents Day 3

情境工程:會話與記憶

第三天

探索如何建構能夠記住過往互動並保持情境的AI智能體。學習如何實現短期記憶和長期記憶,以創建更強大的智能體,使其能夠處理複雜的

LLM記憶

  1. 上下文工程: 動態管理知識
  2. Sections: 保持記憶的life time
  3. Memory: 在Sections間留存的事項

上下文工程

適應不同prompt

  1. 取得context 與相關資料
  2. 準備context
  3. 引入LLM 與tools
  4. 上傳context 成為長期記憶

Section

  1. 短期記憶管理
  2. 保持同一個執行階段
  3. 與其他LLM共享Memory
  4. ADK上有2組件
    • Events: 建構對話中區塊
    • State: 對話中不斷修改的資訊

Session在NotebookLM對應

  • Session: 一個筆記本
  • Events: 單元格
  • SessionService: 筆記簿
  • Runner: AI助理控管執行

Memory

  1. 長期記憶管理
  2. 經過ETL過程
  3. 可產生記憶,並用信心指數取得相關片段

Memory Layer

  1. Model Weights 層: 儲存訓練過程中在公開資料上學習到的通用知識,包含數千億個參數
  2. KV Cache 層: 透過儲存和重複使用先前計算的注意力張量來加速 AI 推理的中間結果
  3. Context 層: 查詢時提供的相關、通常是私密的或及時的背景信息,以幫助模型做出適當的反應,包括長期記憶和檢索增強生成(RAG)

評估產出

Precision確保生成內容不包含太多錯誤或無關資訊,過高精確率意味著內容可靠,但可能會犧牲部分資訊的全面性。

Recall確保生成內容涵蓋足夠多的真實資訊,避免遺漏重要細節,但高召回率可能會導致精確率下降。

在LLM生成文章中使用Precision和Recall,可以衡量生成文本與參考標準或真實資訊之間的重疊程度,常配合F1-score(兩者調和平均)使用,平衡兩者的取捨,從而提升生成文章的質量和相關性。

白皮書要點

  • 上下文工程: 在智能體的上下文視窗中動態組裝和管理訊息,從而創建有狀態且個性化的 AI
  • 將會話定義為單一即時對話歷史記錄的容器,將記憶定義為長期持久化機制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from typing import Any, Dict

from google.adk.agents import Agent, LlmAgent
from google.adk.apps.app import App, EventsCompactionConfig
from google.adk.models.google_llm import Gemini
from google.adk.sessions import DatabaseSessionService
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
from google.adk.tools.tool_context import ToolContext
from google.genai import types

# 重試機制
retry_config = types.HttpRetryOptions(
attempts=5, # Maximum retry attempts
exp_base=7, # Delay multiplier
initial_delay=1,
http_status_codes=[429, 500, 503, 504], # Retry on these HTTP errors
)

# 使用Session
root_agent = Agent(
model=Gemini(model="gemini-2.5-flash-lite", retry_options=retry_config),
...
)

session_service = InMemorySessionService()
runner = Runner(agent=root_agent, app_name=APP_NAME, session_service=session_service)
await run_session(
runner,
[
"Hi, I am Sam! What is the capital of United States?",
"Hello! What is my name?", # 會回傳記憶內容Sam
],
"stateful-agentic-session",
)

# session_service也可以用SQLite
db_url = "sqlite:///my_agent_data.db" # Local SQLite file
session_service = DatabaseSessionService(db_url=db_url)
runner = Runner(agent=chatbot_agent, app_name=APP_NAME, session_service=session_service)

# 長短記憶
memory_service = (
InMemoryMemoryService()
)
session_service = InMemorySessionService() # Handles conversations
runner = Runner(
agent=user_agent,
app_name="MemoryDemoApp",
session_service=session_service,
memory_service=memory_service,
)

# 清除DB
if os.path.exists("my_agent_data.db"):
os.remove("my_agent_data.db")

使用手冊

  • 添加記憶
    • MemoryService 或 SessionService,皆用Runner執行
    • 轉成長期記憶
      • await memory_service.add_session_to_memory(session)
    • 搜尋記憶
      • await memory_service.search_memory(app_name, user_id, query)
    • 取得記憶
      • load_memory: agent決定由長或短記憶取出
      • preload_memory: 由長期記憶取出

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels