메모리 관리
메모리 관리 (Memory Management)
사용자 선호도와 피드백을 저장해 LLM이 세션을 넘어 기억하도록 할 수 있어요. 사용자와 팀별로 범위가 지정되며 내장 접근 제어가 있어요.
요구 사항: PostgreSQL이 연결된 LiteLLM v1.83.10+가 필요해요. 설정 변경은 필요 없어요.
출처: 문서
본문
생성 (Create)
curl:
curl -X POST "http://localhost:4000/v1/memory" \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{
"key": "user:preferences",
"value": "Prefers concise responses. Timezone: PST.",
"metadata": {"version": 1}
}'
Python:
import httpx
client = httpx.Client(
base_url="http://localhost:4000",
headers={"Authorization": "Bearer sk-<your-litellm-api-key>"},
)
client.post("/v1/memory", json={
"key": "user:preferences",
"value": "Prefers concise responses. Timezone: PST.",
"metadata": {"version": 1},
})
읽기 (Read)
curl "http://localhost:4000/v1/memory/user:preferences" \
-H "Authorization: Bearer ***"
갱신 (Update)
curl -X PUT "http://localhost:4000/v1/memory/user:preferences" \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{"value": "Prefers concise responses. Timezone: EST."}'
목록 (List)
# All entries
curl "http://localhost:4000/v1/memory" \
-H "Authorization: Bearer ***"
# By prefix
curl "http://localhost:4000/v1/memory?key_prefix=user:" \
-H "Authorization: Bearer ***"
삭제 (Delete)
curl -X DELETE "http://localhost:4000/v1/memory/user:preferences" \
-H "Authorization: Bearer ***"
접근 제어 (Access Control)
API 키를 기준으로 범위 지정이 자동으로 이뤄져요.
| 역할 (Role) | 읽기 (Reads) | 쓰기 (Writes) |
|---|---|---|
| User | Own + team entries | Own entries only |
| Team admin | Own + team entries | Own + team entries |
| Proxy admin | All | All |
키 이름짓기 (Key Naming)
키는 전역적으로 고유해요. 접두사로 네임스페이스와 조회를 하세요:
user:preferences → per-user settings
team:playbook:onboarding → shared team resources
agent:memory:scratchpad → agent working memory
예시: Slack 봇의 사용자별 메모리
Slack 워크스페이스와 사용자별로 메모리를 분할해 각 사람의 선호도가 격리되도록 해요.
키 형식: slack:{team_id}:{user_id}
import httpx
LITELLM_BASE = "http://localhost:4000"
LITELLM_KEY = "sk-<your-litellm-api-key>"
def memory_key(team_id: str, user_id: str) -> str:
return f"slack:{team_id}:{user_id}"
async def get_preferences(team_id: str, user_id: str) -> str:
"""Read saved preferences. Returns "" if none exist."""
key = memory_key(team_id, user_id)
async with httpx.AsyncClient() as client:
r = await client.get(
f"{LITELLM_BASE}/v1/memory/{key}",
headers={"Authorization": f"Bearer {LITELLM_KEY}"},
)
if r.status_code == 404:
return ""
return r.json().get("value", "")
async def save_preference(team_id: str, user_id: str, note: str):
"""Append a preference. PUT upserts — creates or updates."""
key = memory_key(team_id, user_id)
existing = await get_preferences(team_id, user_id)
# Store as bullet list
bullets = [b for b in existing.split("\n") if b.strip()]
bullets.append(f"- {note}")
async with httpx.AsyncClient() as client:
await client.put(
f"{LITELLM_BASE}/v1/memory/{key}",
headers={"Authorization": f"Bearer {LITELLM_KEY}"},
json={"value": "\n".join(bullets)},
)
매 턴 시스템 프롬프트에 주입:
prefs = await get_preferences(team_id, user_id)
messages = [
{"role": "system", "content": f"""You are a helpful assistant.
SAVED USER PREFERENCES:
{prefs}
Follow these unless the current message contradicts them."""},
{"role": "user", "content": user_message},
]
워크스페이스의 모든 선호도 조회:
curl "http://localhost:4000/v1/memory?key_prefix=slack:T024BE7LD:" \
-H "Authorization: Bearer ***"
메타데이터 (Metadata)
항목에 아무 JSON이든 붙일 수 있어요:
{
"key": "agent:findings",
"value": "Q1 API usage up 15%...",
"metadata": {"tags": ["research"], "confidence": 0.92}
}
API 레퍼런스 (API Reference)
요청/응답 스키마, 파라미터, 오류 코드 전체는 /memory 엔드포인트 레퍼런스 문서를 참고해요.