상위: Agno
요약
Agno의 Context Engineering은 모델에 어떤 정보를 보낼지 설계하는 것이다. 시스템 메시지, 인스트럭션, 대화 히스토리, 의존성 주입, 컨텍스트 캐싱을 통해 에이전트의 동작을 정밀하게 제어한다. "어떤 정보가 원하는 결과를 달성할 가능성이 가장 높은가?"가 핵심 질문이다.
컨텍스트 4대 구성 요소
에이전트가 모델에 보내는 컨텍스트는 4가지로 구성된다:
| 요소 | 설명 |
|---|---|
| System Message | 에이전트 설명, 인스트럭션, 도구 정의, 추가 컨텍스트를 포함하는 메인 메시지 |
| User Message | 사용자 입력 + Knowledge 참조 + 의존성이 주입된 메시지 |
| Chat History | 이전 대화 기록 |
| Additional Input | Few-shot 예시, 보충 데이터 (시스템과 사용자 메시지 사이에 위치) |
System Message 조립 순서
시스템 메시지는 여러 파라미터에서 정해진 순서로 조립된다. 정적 콘텐츠가 앞, 동적 콘텐츠가 뒤에 배치되어 프롬프트 캐싱에 유리하다:
1. description — 에이전트 정체성 (맨 앞)
2. role — <your_role> 태그
3. instructions — <instructions> 태그 (add_instruction_tags=True)
4. <additional_information> 섹션:
├── markdown=True — "Use markdown to format your answer"
├── add_datetime_to_context — 현재 날짜/시간
├── add_location_to_context — 대략적 위치
├── add_name_to_context — 에이전트 이름
└── Tool instructions — Toolkit의 add_instructions=True
5. expected_output — 원하는 응답 형식
6. additional_context — 시스템 메시지 끝에 추가
7. User memories — add_memories_to_context=True
8. Session summary — add_session_summary_to_context=True
9. Session state — add_session_state_to_context=True
결과 예시:
You are a famous short story writer asked to write for a magazine
<instructions>
- Always write 2 sentence stories.
</instructions>
<additional_information>
- Use markdown to format your answer
</additional_information>
system_message="..."로 전체를 직접 오버라이드할 수도 있다 (일부 모델은 build_context=False도 필요).
User Message 확장
사용자 입력에 자동으로 추가되는 내용:
add_knowledge_to_context=True→<references>태그로 Knowledge 검색 결과 추가add_dependencies_to_context=True→<additional context>태그로 의존성 추가
결과 예시:
What is the capital of France?
Use the following references from the knowledge base if it helps:
<references>
- Reference 1
- Reference 2
</references>
<additional context>
{"name": "John Doe"}
</additional context>
Instructions (인스트럭션)
에이전트의 행동을 가이드하는 지시문이다.
정적 인스트럭션
agent = Agent(
instructions=["Always cite sources.", "Use tables for data."], # 리스트도 가능
)
동적 인스트럭션 (함수)
RunContext를 받는 함수를 전달하면 매 실행마다 동적으로 인스트럭션을 생성한다:
from agno.run.context import RunContext
def get_instructions(run_context: RunContext) -> str:
user_id = run_context.session_state.get("current_user_id")
if user_id:
return f"You are assisting user {user_id}. Be personalized."
return "You are a general assistant."
agent = Agent(
instructions=get_instructions, # 함수를 전달
)
agent.print_response("Hello", user_id="john.doe")
RunContext는 세션 상태, 사용자 ID, 의존성 등에 접근할 수 있어 사용자별 맞춤 인스트럭션이 가능하다.
Dependencies (의존성 주입)
에이전트 컨텍스트에 외부 변수를 주입하는 메커니즘이다. 딕셔너리 형태로 정의하며, 정적 값과 동적 함수를 모두 지원한다. resolve_in_context=True(기본값)가 활성화되어야 {...} 치환이 작동한다.
정적 의존성
agent = Agent(
dependencies={"name": "John Doe", "role": "admin"},
instructions="You are assisting {name} who is a {role}.",
)
{dependency_name} 구문으로 인스트럭션과 메시지에서 참조할 수 있다.
동적 의존성 (Callable)
함수를 값으로 전달하면 런타임에 자동 실행되어 반환값이 주입된다:
import json, httpx
def get_top_hackernews_stories(num_stories: int = 5) -> str:
stories = [
httpx.get(f"https://hacker-news.firebaseio.com/v0/item/{id}.json").json()
for id in httpx.get("https://hacker-news.firebaseio.com/v0/topstories.json").json()[:num_stories]
]
return json.dumps(stories, indent=4)
agent = Agent(
dependencies={"top_hackernews_stories": get_top_hackernews_stories},
add_dependencies_to_context=True, # 자동으로 <additional context>에 추가
markdown=True,
)
agent.print_response("Summarize the top stories on HackerNews", stream=True)
add_dependencies_to_context
| 값 | 동작 |
|---|---|
False (기본) | {dependency_name}으로 명시적 참조해야 함 |
True | User Message에 <additional context> 섹션으로 자동 추가 |
의존성 해결 과정
1. Agent.run() 호출
2. dependencies 딕셔너리 순회
3. Callable이면 실행 → 반환값으로 교체
4. {dependency_name} 템플릿 치환 (resolve_in_context=True)
5. add_dependencies_to_context=True이면 User Message에 <additional context> 추가
6. 모델에 전송
run()에서 동적 전달
초기화 시점뿐 아니라 run() 호출 시에도 의존성을 전달할 수 있다:
response = agent.run(
"Analyze this user",
dependencies={
"user_profile": {"name": "Jane", "plan": "pro"},
"current_context": get_current_context, # Callable
},
add_dependencies_to_context=True,
)
Team에서의 의존성
Team도 동일한 패턴을 지원한다. 모든 멤버 에이전트에서 접근 가능하다:
team = Team(
dependencies={"user_profile": get_user_profile},
instructions=["Personalize for: {user_profile}"],
members=[agent1, agent2],
)
도구에서 의존성 접근
도구 함수에서 RunContext를 통해 의존성에 접근한다:
from agno.run.context import RunContext
def get_user_profile(run_context: RunContext) -> str:
"""Fetch user profile from dependencies."""
user_id = run_context.user_id
profiles = run_context.dependencies.get("user_profiles", {})
return profiles.get(user_id, "Unknown user")
agent = Agent(
tools=[get_user_profile],
dependencies={"user_profiles": {"john": "John Doe, Premium"}},
)
Few-shot Learning (Additional Input)
additional_input 파라미터로 시스템 메시지와 사용자 메시지 사이에 예시를 삽입한다. Message 객체 리스트를 전달한다:
from agno.models.message import Message
support_examples = [
Message(role="user", content="I forgot my password"),
Message(role="assistant", content="I'll help reset your password..."),
]
agent = Agent(
additional_input=support_examples,
instructions=["You are an expert customer support specialist."],
)
인스트럭션 내에 직접 예시를 작성하는 방법도 있다:
agent = Agent(
instructions="""
You are a sentiment classifier.
Examples:
Input: "I love this product!" → positive
Input: "This is terrible" → negative
""",
)
Context Caching (Prompt Caching)
시스템 프롬프트를 프로바이더 인프라에 캐싱하여 처리 시간과 비용을 절감한다.
Anthropic
from agno.models.anthropic import Claude
agent = Agent(
model=Claude(
id="claude-sonnet-4-6",
cache_system_prompt=True, # 프롬프트 캐싱 활성화
),
)
확장 캐시 (5분 → 1시간):
agent = Agent(
model=Claude(
id="claude-sonnet-4-6",
default_headers={"anthropic-beta": "extended-cache-ttl-2025-04-11"},
cache_system_prompt=True,
extended_cache_time=True,
),
)
요구사항: 시스템 프롬프트 1024 토큰 이상이어야 캐싱 활성화. 메트릭: response.metrics.cache_write_tokens, cache_read_tokens.
OpenAI
자동 캐싱 — 별도 설정 불필요. 반복되는 프롬프트 접두사를 자동으로 캐싱한다.
OpenRouter
프로바이더에 따라 자동 캐싱. Anthropic 직접 연결 대비 효율은 낮다.
캐싱 전략
- 정적 콘텐츠를 시스템 메시지 앞부분에 배치한다 (description, instructions)
- 자주 바뀌는 동적 콘텐츠는 뒤에 배치한다 (session state, memories)
- 인스트럭션, 도구 정의, 가드레일 등 고정 부분이 캐싱 대상이다
Response Caching (로컬 캐싱)
모델 응답을 로컬에 캐싱하여 동일 요청에 대한 중복 API 호출을 방지한다.
| 파라미터 | 타입 | 기본값 | 설명 |
|---|---|---|---|
cache_response | bool | False | 로컬 응답 캐싱 활성화 |
cache_ttl | int (초) | None (무기한) | 캐시 만료 시간 |
cache_dir | str | ~/.agno/cache/model_responses | 캐시 디렉토리 |
agent = Agent(
model=OpenAIChat(
id="gpt-4o",
cache_response=True,
cache_ttl=3600, # 1시간
cache_dir="./cache",
),
)
Prompt Caching + Response Caching 동시 사용:
agent = Agent(
model=Claude(
id="claude-sonnet-4-6",
cache_response=True, # 로컬 캐싱
cache_system_prompt=True, # 프로바이더측 캐싱
cache_ttl=7200,
),
)
스트리밍 응답도 캐시되며, 캐시 히트 시 단일 청크로 반환된다. 동적 콘텐츠가 많은 프로덕션 환경에서는 비권장.
히스토리 관리
| 파라미터 | 설명 |
|---|---|
add_history_to_context | 대화 히스토리 포함 여부 |
num_history_runs | 포함할 최근 실행 수 |
max_tool_calls_from_history | 히스토리에서 포함할 도구 호출 수 (토큰 절약) |
filter_tool_calls_from_history | 도구 호출 메시지 완전 제외 |
agent = Agent(
add_history_to_context=True,
num_history_runs=5,
max_tool_calls_from_history=3, # 최근 3개 도구 호출만
)
주요 컨텍스트 파라미터 전체 참조
| 파라미터 | 타입 | 기본값 | 설명 |
|---|---|---|---|
description | str | None | 시스템 메시지 시작에 추가 |
role | str | None | <your_role> 태그 |
instructions | str/List/Callable | None | <instructions> 태그 |
expected_output | str | None | 원하는 응답 형식 |
additional_context | str | None | 시스템 메시지 끝에 추가 |
system_message | str/Callable/Message | None | 시스템 메시지 완전 오버라이드 |
build_context | bool | True | 컨텍스트 자동 조립 활성화 |
resolve_in_context | bool | True | {...} 템플릿 치환 활성화 |
dependencies | Dict | None | 의존성 주입 딕셔너리 |
add_dependencies_to_context | bool | False | 의존성 자동 추가 |
additional_input | List | None | Few-shot 예시 |
add_datetime_to_context | bool | False | 날짜/시간 추가 |
add_location_to_context | bool | False | 위치 추가 |
add_name_to_context | bool | False | 에이전트 이름 추가 |
add_knowledge_to_context | bool | False | Knowledge 참조 추가 |
add_memories_to_context | bool | None | 사용자 메모리 추가 |
add_session_summary_to_context | bool | None | 세션 요약 추가 |
add_session_state_to_context | bool | False | 세션 상태 추가 |
add_history_to_context | bool | False | 히스토리 추가 |
num_history_runs | int | — | 히스토리 실행 수 제한 |
markdown | bool | False | 마크다운 포매팅 |
debug_mode | bool | False | 컴파일된 시스템 메시지 출력 |
관련 개념
- Agno: Agno 프레임워크 MOC
- Agno Agent: 단일 에이전트 구성
- Agno Knowledge & Memory: Knowledge, Memory, Storage
- Agno Team: Team에서의 의존성 주입