좋은 에이전트 만들기
좋은 에이전트 만들기
동작하는 에이전트와 그렇지 않은 에이전트 사이에는 천지 차이가 있어요. 어떻게 하면 전자에 속하는 에이전트를 만들 수 있을까요? 이 가이드에서는 에이전트를 만드는 모범 사례에 대해 이야기해 볼게요.
[!TIP] 에이전트를 처음 만들어 보는 분이라면 먼저 에이전트 소개와 smolagents 둘러보기를 읽고 오시는 게 좋아요.
가장 좋은 에이전트 시스템은 가장 단순합니다: 워크플로를 최대한 단순화하세요
워크플로에 LLM에게 어떤 자율성(agency)을 주는 것은 오류의 위험을 어느 정도 도입하는 일이에요.
잘 짜여진 에이전트 시스템은 어차피 좋은 오류 로깅과 재시도 메커니즘을 갖추고 있어서, LLM 엔진이 실수를 스스로 고칠 기회를 얻어요. 하지만 LLM 오류의 위험을 최대한 줄이려면 워크플로를 단순화하세요!
에이전트 소개의 예시를 다시 봅시다. 서핑 여행 회사의 문의에 답하는 봇이었죠. 새 서핑 스팟에 대해 물어볼 때마다 "여행 거리 API"와 "날씨 API" 두 가지를 각각 호출하게 두는 대신, 두 API를 한 번에 호출해 결과를 합쳐 사용자에게 돌려주는 통합 도구 "return_spot_information" 하나로 만들 수 있어요.
이렇게 하면 비용, 지연 시간, 오류 위험을 모두 줄일 수 있어요!
핵심 지침은 이거예요: LLM 호출 수를 최대한 줄이세요.
여기서 몇 가지를 얻어갈 수 있어요:
- 가능할 때마다 두 도구를 하나로 합치세요(위의 두 API 예시처럼).
- 가능할 때마다 로직은 에이전트의 결정보다 결정적 함수에 기반하도록 하세요.
LLM 엔진으로의 정보 흐름을 개선하세요
여러분의 LLM 엔진은 문만 하나 있고 그 아래로 쪽지를 주고받는 게 바깥세상과의 유일한 소통인 방 안에 갇힌 지능형 로봇과 같다고 생각해 보세요.
명시적으로 프롬프트에 넣지 않는 한, LLM은 밖에서 무슨 일이 있었는지 전혀 알 수 없어요.
그래서 먼저 작업을 아주 명확하게 만드는 것부터 시작하세요! 에이전트는 LLM으로 구동되기 때문에, 작업 표현의 사소한 차이가 완전히 다른 결과를 낳을 수도 있어요.
그다음, 도구 사용에서 에이전트 쪽으로의 정보 흐름을 개선하세요.
따라야 할 구체적인 지침들:
- 각 도구는 LLM 엔진에 유용할 만한 모든 것을 (간단히 도구의
forward메서드 안에print문으로) 로깅해야 해요.- 특히 도구 실행 오류에 대한 세부 사항을 로깅하면 큰 도움이 돼요!
예를 들어 위치와 날짜-시간을 바탕으로 날씨 데이터를 가져오는 도구가 있다고 해 봅시다.
먼저, 좋지 않은 버전이에요:
import datetime
from smolagents import tool
def get_weather_report_at_coordinates(coordinates, date_time):
# Dummy function, returns a list of [temperature in °C, risk of rain on a scale 0-1, wave height in m]
return [28.0, 0.35, 0.85]
def convert_location_to_coordinates(location):
# Returns dummy coordinates
return [3.3, -42.0]
@tool
def get_weather_api(location: str, date_time: str) -> str:
"""
Returns the weather report.
Args:
location: the name of the place that you want the weather for.
date_time: the date and time for which you want the report.
"""
lon, lat = convert_location_to_coordinates(location)
date_time = datetime.strptime(date_time)
return str(get_weather_report_at_coordinates((lon, lat), date_time))
왜 나쁠까요?
date_time에 사용해야 할 형식에 대한 정확성이 없어요- location을 어떻게 지정해야 하는지에 대한 설명이 없어요
- location이 올바른 형식이 아니거나 date_time이 제대로 포맷되지 않은 경우 같은 명시적 실패 케이스를 밝히려는 로깅 메커니즘이 없어요
- 출력 형식이 이해하기 어려워요
도구 호출이 실패하면 메모리에 로그로 남은 오류 트레이스가 LLM이 도구를 역추적해 오류를 고치는 데 도움이 될 수 있어요. 하지만 왜 LLM에게 그렇게 무거운 일을 다 떠넘기게 두겠어요?
이 도구를 만드는 더 나은 방법은 다음과 같아요:
@tool
def get_weather_api(location: str, date_time: str) -> str:
"""
Returns the weather report.
Args:
location: the name of the place that you want the weather for. Should be a place name, followed by possibly a city name, then a country, like "Anchor Point, Taghazout, Morocco".
date_time: the date and time for which you want the report, formatted as '%m/%d/%y %H:%M:%S'.
"""
lon, lat = convert_location_to_coordinates(location)
try:
date_time = datetime.strptime(date_time)
except Exception as e:
raise ValueError("Conversion of `date_time` to datetime format failed, make sure to provide a string in format '%m/%d/%y %H:%M:%S'. Full trace:" + str(e))
temperature_celsius, risk_of_rain, wave_height = get_weather_report_at_coordinates((lon, lat), date_time)
return f"Weather report for {location}, {date_time}: Temperature will be {temperature_celsius}°C, risk of rain is {risk_of_rain*100:.0f}%, wave height is {wave_height}m."
일반적으로 LLM의 부담을 줄이려면 스스로에게 이렇게 물어보는 게 좋아요: "내가 멍청하고 이 도구를 처음 써본다면, 이 도구로 프로그래밍하고 내 실수를 스스로 고치는 게 얼마나 쉬울까?"
에이전트에 더 많은 인자를 주세요
작업을 설명하는 단순한 문자열 너머의 추가 객체를 에이전트에 넘기려면 additional_args 인자를 사용해 어떤 타입의 객체든 전달할 수 있어요:
from smolagents import CodeAgent, InferenceClientModel
model_id = "meta-llama/Llama-3.3-70B-Instruct"
agent = CodeAgent(tools=[], model=InferenceClientModel(model_id=model_id), add_base_tools=True)
agent.run(
"Why does Mike not know many people in New York?",
additional_args={"mp3_sound_file_url":'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/recording.mp3'}
)
예를 들어 에이전트가 활용하길 원하는 이미지나 문자열을 이 additional_args 인자로 넘길 수 있어요.
에이전트를 디버깅하는 방법
1. 더 강력한 LLM을 사용하세요
에이전트 워크플로에서는 일부 오류는 실제 오류이지만, 또 다른 일부는 LLM 엔진이 제대로 추론하지 못한 탓이에요.
예를 들어 자동차 그림을 만들라고 한 CodeAgent의 이 트레이스를 봅시다:
==================================================================================================== New task ====================================================================================================
Make me a cool car picture
──────────────────────────────────────────────────────────────────────────────────────────────────── New step ────────────────────────────────────────────────────────────────────────────────────────────────────
Agent is executing the code below: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
image_generator(prompt="A cool, futuristic sports car with LED headlights, aerodynamic design, and vibrant color, high-res, photorealistic")
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Last output from code snippet: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
/var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png
Step 1:
- Time taken: 16.35 seconds
- Input tokens: 1,383
- Output tokens: 77
──────────────────────────────────────────────────────────────────────────────────────────────────── New step ────────────────────────────────────────────────────────────────────────────────────────────────────
Agent is executing the code below: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
final_answer("/var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png")
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Print outputs:
Last output from code snippet: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
/var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png
Final answer:
/var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png
이미지가 반환되는 대신 사용자에게 경로가 반환되고 있어요. 시스템의 버그처럼 보일 수 있지만, 실제로 에이전트 시스템이 오류를 일으킨 게 아니에요. 다만 LLM 두뇌가 이미지 출력을 변수에 저장하지 않는 실수를 저지른 것뿐이에요. 그래서 이미지를 저장하는 동안 로그로 남은 경로 외에는 다시 접근할 방법이 없으니, 이미지 대신 경로를 반환한 거예요.
에이전트를 디버깅하는 첫 단계는 따라서 "더 강력한 LLM을 사용하세요"예요. Qwen2/5-72B-Instruct 같은 대안이라면 그런 실수를 하지 않았을 거예요.
2. 더 많은 정보 또는 구체적인 지침을 제공하세요
모델을 더 효과적으로 안내하기만 하면, 덜 강력한 모델도 쓸 수 있어요.
여러분의 모델 입장이 되어 보세요. 여러분이 작업을 푸는 모델이라면, 지금 가진 정보로(시스템 프롬프트 + 작업 표현 + 도구 설명) 어려움을 겪지 않을까요?
상세한 지침이 필요할까요?
- 지침이 항상 에이전트에 주어져야 하는 것이라면(시스템 프롬프트가 보통 그렇게 동작한다고 이해하듯이): 에이전트 초기화 시
instructions인자 아래 문자열로 전달하면 돼요. (참고: instructions는 시스템 프롬프트에 추가되는 것이지, 교체하는 게 아니에요.) - 특정 작업에 관한 것이라면: 그 세부 사항을 모두 작업에 추가하세요. 작업은 수십 페이지처럼 매우 길어도 괜찮아요.
- 특정 도구를 어떻게 쓰는지에 관한 것이라면: 그 도구의
description속성에 포함하세요.
3. 프롬프트 템플릿을 바꾸세요 (일반적으로 권장하지 않음)
위의 명확화로도 충분하지 않다면, 에이전트의 프롬프트 템플릿을 바꿀 수 있어요.
어떻게 동작하는지 봅시다. 예를 들어 CodeAgent의 기본 프롬프트 템플릿을 확인해 볼게요 (아래 버전은 zero-shot 예시를 건너뛰어 짧게 줄인 거예요).
print(agent.prompt_templates["system_prompt"])
이렇게 나와요:
You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.
To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
To solve the task, you must plan forward to proceed in a series of steps, in a cycle of Thought, Code, and Observation sequences.
At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
Then in the Code sequence you should write the code in simple Python. The code sequence must be opened with '{{code_block_opening_tag}}', and closed with '{{code_block_closing_tag}}'.
During each intermediate step, you can use 'print()' to save whatever important information you will then need.
These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
In the end you have to return a final answer using the `final_answer` tool.
Here are a few examples using notional tools:
---
Task: "Generate an image of the oldest person in this document."
Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
{{code_block_opening_tag}}
answer = document_qa(document=document, question="Who is the oldest person mentioned?")
print(answer)
{{code_block_closing_tag}}
Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
Thought: I will now generate an image showcasing the oldest person.
{{code_block_opening_tag}}
image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
final_answer(image)
{{code_block_closing_tag}}
---
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
{{code_block_opening_tag}}
result = 5 + 3 + 1294.678
final_answer(result)
{{code_block_closing_tag}}
---
Task:
"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
{'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
{{code_block_opening_tag}}
translated_question = translator(question=question, src_lang="French", tgt_lang="English")
print(f"The translated question is {translated_question}.")
answer = image_qa(image=image, question=translated_question)
final_answer(f"The answer is {answer}")
{{code_block_closing_tag}}
---
Task:
In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
{{code_block_opening_tag}}
pages = web_search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
print(pages)
{{code_block_closing_tag}}
Observation:
No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
{{code_block_opening_tag}}
pages = web_search(query="1979 interview Stanislaus Ulam")
print(pages)
{{code_block_closing_tag}}
Observation:
Found 6 pages:
[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
(truncated)
Thought: I will read the first 2 pages to know more.
{{code_block_opening_tag}}
for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
whole_page = visit_webpage(url)
print(whole_page)
print("\n" + "="*80 + "\n") # Print separator between pages
{{code_block_closing_tag}}
Observation:
Manhattan Project Locations:
Los Alamos, NM
Stanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at
(truncated)
Thought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: "He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity." Let's answer in one word.
{{code_block_opening_tag}}
final_answer("diminished")
{{code_block_closing_tag}}
---
Task: "Which city has the highest population: Guangzhou or Shanghai?"
Thought: I need to get the populations for both cities and compare them: I will use the tool `web_search` to get the population of both cities.
{{code_block_opening_tag}}
for city in ["Guangzhou", "Shanghai"]:
print(f"Population {city}:", web_search(f"{city} population")
{{code_block_closing_tag}}
Observation:
Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
Population Shanghai: '26 million (2019)'
Thought: Now I know that Shanghai has the highest population.
{{code_block_opening_tag}}
final_answer("Shanghai")
{{code_block_closing_tag}}
---
Task: "What is the current age of the pope, raised to the power 0.36?"
Thought: I will use the tool `wikipedia_search` to get the age of the pope, and confirm that with a web search.
{{code_block_opening_tag}}
pope_age_wiki = wikipedia_search(query="current pope age")
print("Pope age as per wikipedia:", pope_age_wiki)
pope_age_search = web_search(query="current pope age")
print("Pope age as per google search:", pope_age_search)
{{code_block_closing_tag}}
Observation:
Pope age: "The pope Francis is currently 88 years old."
Thought: I know that the pope is 88 years old. Let's compute the result using python code.
{{code_block_opening_tag}}
pope_current_age = 88 ** 0.36
final_answer(pope_current_age)
{{code_block_closing_tag}}
Above example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools, behaving like regular python functions:
{{code_block_opening_tag}}
{%- for tool in tools.values() %}
{{ tool.to_code_prompt() }}
{% endfor %}
{{code_block_closing_tag}}
{%- if managed_agents and managed_agents.values() | list %}
You can also give tasks to team members.
Calling a team member works similarly to calling a tool: provide the task description as the 'task' argument. Since this team member is a real human, be as detailed and verbose as necessary in your task description.
You can also include any relevant variables or context using the 'additional_args' argument.
Here is a list of the team members that you can call:
{{code_block_opening_tag}}
{%- for agent in managed_agents.values() %}
def {{ agent.name }}(task: str, additional_args: dict[str, Any]) -> str:
"""{{ agent.description }}
Args:
task: Long detailed description of the task.
additional_args: Dictionary of extra inputs to pass to the managed agent, e.g. images, dataframes, or any other contextual data it may need.
"""
{% endfor %}
{{code_block_closing_tag}}
{%- endif %}
Here are the rules you should always follow to solve your task:
1. Always provide a 'Thought:' sequence, and a '{{code_block_opening_tag}}' sequence ending with '{{code_block_closing_tag}}', else you will fail.
2. Use only variables that you have defined!
3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wikipedia_search({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wikipedia_search(query="What is the place where James Bond lives?")'.
4. For tools WITHOUT JSON output schema: Take care to not chain too many sequential tool calls in the same code block, as their output format is unpredictable. For instance, a call to wikipedia_search without a JSON output schema has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
5. For tools WITH JSON output schema: You can confidently chain multiple tool calls and directly access structured output fields in the same code block! When a tool has a JSON output schema, you know exactly what fields and data types to expect, allowing you to write robust code that directly accesses the structured response (e.g., result['field_name']) without needing intermediate print() statements.
6. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
7. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
8. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
9. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
10. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
11. Don't give up! You're in charge of solving the task, not providing directions to solve it.
{%- if custom_instructions %}
{{custom_instructions}}
{%- endif %}
Now Begin!
보시다시피 "{{ tool.description }}" 같은 플레이스홀더가 있어요. 이들은 에이전트 초기화 시 도구나 관리 에이전트의 자동 생성된 설명을 끼워 넣는 데 사용돼요.
그래서 system_prompt 파라미터에 커스텀 프롬프트를 인자로 넘겨 이 시스템 프롬프트 템플릿을 덮어쓸 수 있지만, 새 시스템 프롬프트에는 다음 플레이스홀더를 담을 수 있어요:
- 도구 설명을 끼워 넣으려면:
{%- for tool in tools.values() %} - {{ tool.to_tool_calling_prompt() }} {%- endfor %} - 관리 에이전트가 있다면 그 설명을 끼워 넣으려면:
{%- if managed_agents and managed_agents.values() | list %} You can also give tasks to team members. Calling a team member works similarly to calling a tool: provide the task description as the 'task' argument. Since this team member is a real human, be as detailed and verbose as necessary in your task description. You can also include any relevant variables or context using the 'additional_args' argument. Here is a list of the team members that you can call: {%- for agent in managed_agents.values() %} - {{ agent.name }}: {{ agent.description }} {%- endfor %} {%- endif %} CodeAgent에만 해당하는, 허용된 임포트 목록을 끼워 넣으려면:"{{authorized_imports}}"
그런 다음 시스템 프롬프트를 이렇게 바꿀 수 있어요:
agent.prompt_templates["system_prompt"] = agent.prompt_templates["system_prompt"] + "\nHere you go!"
이 방법은 ToolCallingAgent에도 동일하게 동작해요.
하지만 일반적으로는 에이전트 초기화 시 instructions 인자를 넘기는 쪽이 더 단순해요:
agent = CodeAgent(tools=[], model=InferenceClientModel(model_id=model_id), instructions="Always talk like a 5 year old.")
instructions는 시스템 프롬프트에 추가되는 것이지, 교체하는 게 아니라는 점을 기억하세요.
4. 추가 플래닝
우리는 일반 행동 단계 사이에 에이전트가 주기적으로 실행할 수 있는 보조 플래닝 단계용 모델을 제공해요. 이 단계에서는 도구 호출이 없고, LLM은 단순히 자신이 아는 사실 목록을 갱신하고 그 사실들에 기반해 다음에 어떤 단계를 밟아야 할지 반성(reflect)하도록 요청받아요.
from smolagents import load_tool, CodeAgent, InferenceClientModel, WebSearchTool
from dotenv import load_dotenv
load_dotenv()
# Import tool from Hub
image_generation_tool = load_tool("m-ric/text-to-image", trust_remote_code=True)
search_tool = WebSearchTool()
agent = CodeAgent(
tools=[search_tool, image_generation_tool],
model=InferenceClientModel(model_id="Qwen/Qwen2.5-72B-Instruct"),
planning_interval=3 # This is where you activate planning!
)
# Run it!
result = agent.run(
"How long would a cheetah at full speed take to run the length of Pont Alexandre III?",
)