C.W.K.
Stream
Lesson 02 of 08 · published

query() vs ClaudeSDKClient: lifecycle로 픽

~16 min · query, ClaudeSDKClient, lifecycle

Level 0Observer
0 XP0/64 lessons0/13 achievements
0/150 XP to next level150 XP to go0% complete

두 lifecycle에 두 API

SDK가 top-level 진입점 둘 노출. query(prompt, options)는 one-shot async generator — 서브프로세스 spin up, 단일 프롬프트 완료까지 run, tear down. ClaudeSDKClient(options)는 long-lived 클라이언트 — 한 번 connect, 메시지 여럿 보내, 서브프로세스 살려둠.

query() fit 시점

스크립트, CI 작업, batch 변환, 에이전트가 완료까지 run하고 exit하는 어느 거. 각 query 독립. cwk-site가 build-time 콘텐츠 생성에 query() 사용.

ClaudeSDKClient fit 시점

챗 애플리케이션, long-running 운영자, 메시지 여럿이 상태 공유하는 어느 거. cwkPippa Claude 브레인이 conversation_id당 ClaudeSDKClient 하나 — 서브프로세스 persist, 대화 계속, SDK가 너 재전송 없이 internal history replay.

원칙: One-shot엔 query(). Long haul엔 Client. 섞기 OK; lifecycle에 wrong 거 쓰는 게 낭비.

Code

query()로 one-shot·python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def explain_file(path: str):
    options = ClaudeAgentOptions(
        cwd="/Users/me/repo",
        allowed_tools=["Read"],  # 읽기만; 편집 X
    )
    async for event in query(
        prompt=f"Read {path} and write a one-paragraph explanation of what it does.",
        options=options,
    ):
        if hasattr(event, "text"):
            print(event.text, end="")

asyncio.run(explain_file("src/main.py"))
Long-lived ClaudeSDKClient·python
import asyncio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

async def chat_session():
    client = ClaudeSDKClient(
        options=ClaudeAgentOptions(
            cwd="/Users/me/repo",
            system_prompt={"type": "preset", "preset": "claude_code"},
        )
    )
    await client.connect()
    try:
        # 멀티턴 대화; SDK가 모든 거 내부적으로 기억.
        async for event in client.send_message("What does this repo do?"):
            print_event(event)
        async for event in client.send_message("Add a CLI flag for verbose output."):
            print_event(event)
    finally:
        await client.disconnect()

asyncio.run(chat_session())

External links

Exercise

빌드한 또는 빌드 원하는 기능에 대해 query()와 ClaudeSDKClient 사이 결정하고 한 줄 정당화. 이미 코딩했으면 옳은 거 썼는지 확인 — 아니면 switch.
Hint
냄새 테스트 — One-shot 스크립트가 should보다 느리면 Client 썼을 가능성; 챗이 컨텍스트 잃으면 query 썼을 가능성.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.