# Smolagents

## Docs

- [`smolagents`[[smolagents]]](https://huggingface.co/docs/smolagents/main/ko/index.md)
- [에이전트 안내서[[agents---guided-tour]]](https://huggingface.co/docs/smolagents/main/ko/guided_tour.md)
- [설치 옵션[[installation-options]]](https://huggingface.co/docs/smolagents/main/ko/installation.md)
- [멀티스텝 에이전트는 어떻게 동작하나요?[[how-do-multi-step-agents-work]]](https://huggingface.co/docs/smolagents/main/ko/conceptual_guides/react.md)
- [에이전트[[agents]]](https://huggingface.co/docs/smolagents/main/ko/reference/agents.md)
- [모델[[models]]](https://huggingface.co/docs/smolagents/main/ko/reference/models.md)
- [Agentic RAG[[agentic-rag]]](https://huggingface.co/docs/smolagents/main/ko/examples/rag.md)
- [에이전트를 활용한 웹 브라우저 자동화 🤖🌐[[web-browser-automation-with-agents-🤖🌐]]](https://huggingface.co/docs/smolagents/main/ko/examples/web_browser.md)
- [에이전트를 활용한 비동기 애플리케이션[[async-applications-with-agents]]](https://huggingface.co/docs/smolagents/main/ko/examples/async_agent.md)
- [멀티 에이전트 시스템 오케스트레이션 🤖🤝🤖](https://huggingface.co/docs/smolagents/main/ko/examples/multiagents.md)
- [Text-to-SQL[[text-to-sql]]](https://huggingface.co/docs/smolagents/main/ko/examples/text_to_sql.md)
- [다양한 모델 사용하기 [[using-different-models]]](https://huggingface.co/docs/smolagents/main/ko/examples/using_different_models.md)
- [좋은 에이전트 구축하기[[building-good-agents]]](https://huggingface.co/docs/smolagents/main/ko/tutorials/building_good_agents.md)
- [📚 에이전트 메모리 관리[[-manage-your-agents-memory]]](https://huggingface.co/docs/smolagents/main/ko/tutorials/memory.md)

### `smolagents`[[smolagents]]
https://huggingface.co/docs/smolagents/main/ko/index.md

# `smolagents`[[smolagents]]

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/license_to_call.png" style="max-width:700px"/>
</div>

## smolagents란 무엇인가요?[[what-is-smolagents]]

`smolagents`는 단 몇 줄의 코드만으로 에이전트를 구축하고 실행할 수 있도록 설계된 오픈소스 Python 라이브러리입니다.

`smolagents`의 주요 특징:

✨ **단순함**: 에이전트 로직이 약 천 줄의 코드로 구현되어 있습니다. 코드 위에 불필요한 복잡한 구조를 추가하지 않고 단순하게 만들었습니다!

🧑‍💻 **코드 에이전트의 완전한 지원**: [`CodeAgent`](reference/agents#smolagents.CodeAgent)는 도구 호출이나 계산 수행을 위해 직접 코드를 작성합니다 ("코드 작성용 에이전트"와는 반대 개념). 이를 통해 함수 중첩, 루프, 조건문 등을 자연스럽게 조합할 수 있습니다. 보안을 위해 [E2B](https://e2b.dev/)나 Docker를 통한 [샌드박스 환경 실행](tutorials/secure_code_execution)을 지원합니다.

📡 **기본 도구 호출 에이전트 지원**: CodeAgent 외에도 [`ToolCallingAgent`](reference/agents#smolagents.ToolCallingAgent)는 일반적인 JSON/텍스트 기반 도구 호출 방식이 필요한 경우를 위해 지원됩니다.

🤗 **Hub 통합**: Gradio Spaces로 에이전트와 도구를 Hub에서 원활하게 공유하고 로드할 수 있습니다.

🌐 **모델 독립적**: Hub의 [Inference providers](https://huggingface.co/docs/inference-providers/index)나 OpenAI, Anthropic 등의 API를 통해 접근하거나, LiteLLM 통합으로 다양한 LLM을 쉽게 연결할 수 있습니다. Transformers나 Ollama를 사용한 로컬 실행도 가능합니다. 원하는 LLM으로 에이전트를 구동하는 것이 간단하고 유연합니다.

👁️ **모달리티 독립적**: 텍스트뿐만 아니라 비전, 비디오, 오디오 입력도 처리할 수 있어 활용 가능한 애플리케이션 범위가 확장됩니다. 비전 관련 [튜토리얼](examples/web_browser)을 확인해보세요.

🛠️ **도구 독립적**: [MCP 서버](reference/tools#smolagents.ToolCollection.from_mcp)의 도구나 [LangChain](reference/tools#smolagents.Tool.from_langchain)의 도구를 사용할 수 있고, [Hub Space](reference/tools#smolagents.Tool.from_space)도 도구로 활용할 수 있습니다.

💻 **CLI 도구**: 보일러플레이트 코드 작성 없이 에이전트를 빠르게 실행할 수 있는 명령줄 유틸리티(smolagent, webagent)가 포함되어 있습니다.

## 빠른 시작[[quickstart]]


smolagents를 단 몇 분 만에 시작해보세요! 이 가이드는 첫 번째 에이전트를 생성하고 실행하는 방법을 보여줍니다.

### 설치[[installation]]

pip으로 smolagents를 설치하세요:

```bash
pip install 'smolagents[toolkit]'  # 웹 검색과 같은 기본 도구 포함
```

### 첫 에이전트 만들기[[create-your-first-agent]]

다음은 에이전트를 생성하고 실행하는 최소한의 예제입니다:

```python
from smolagents import CodeAgent, InferenceClientModel

# 모델 초기화 (Hugging Face Inference API 사용)
model = InferenceClientModel()  # 기본 모델 사용

# 도구 없이 에이전트 생성
agent = CodeAgent(tools=[], model=model)

# 작업으로 에이전트 실행
result = agent.run("Calculate the sum of numbers from 1 to 10")
print(result)
```

끝입니다! 에이전트가 Python 코드를 사용하여 작업을 해결하고 결과를 반환합니다.

### 도구 추가[[adding-tools]]

몇 가지 도구를 추가하여 에이전트를 더 강력하게 만들어보겠습니다:

```python
from smolagents import CodeAgent, InferenceClientModel, DuckDuckGoSearchTool

model = InferenceClientModel()
agent = CodeAgent(
    tools=[DuckDuckGoSearchTool()],
    model=model,
)

# 이제 에이전트가 웹을 검색할 수 있습니다!
result = agent.run("What is the current weather in Paris?")
print(result)
```

### 다른 모델 사용하기[[using-different-models]]

에이전트와 함께 다양한 모델을 사용할 수 있습니다:

```python
# Hugging Face의 특정 모델 사용
model = InferenceClientModel(model_id="meta-llama/Llama-2-70b-chat-hf")

# OpenAI/Anthropic 사용 ('smolagents[litellm]' 필요)
from smolagents import LiteLLMModel
model = LiteLLMModel(model_id="gpt-4")

# 로컬 모델 사용 ('smolagents[transformers]' 필요)
from smolagents import TransformersModel
model = TransformersModel(model_id="meta-llama/Llama-2-7b-chat-hf")
```

## 다음 단계[[next-steps]]

- [설치 가이드](installation)에서 다양한 모델과 도구로 smolagents를 설정하는 방법을 알아보세요
- 더 고급 기능은 [안내서](guided_tour)를 확인하세요
- [커스텀 도구 구축](tutorials/tools)에 대해 알아보세요
- [안전한 코드 실행](tutorials/secure_code_execution)을 살펴보세요
- [멀티 에이전트 시스템](tutorials/building_good_agents) 생성 방법을 확인하세요

<div class="mt-10">
  <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./guided_tour"
      ><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">안내서</div>
      <p class="text-gray-700">기본 사항을 배우고 에이전트 사용에 익숙해지세요. 에이전트를 처음 사용하는 경우 여기서 시작하세요!</p>
    </a>
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./examples/text_to_sql"
      ><div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">실습 가이드</div>
      <p class="text-gray-700">특정 목표를 달성하는 데 도움이 되는 실용적인 가이드: SQL 쿼리를 생성하고 테스트하는 에이전트를 만들어보세요!</p>
    </a>
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./conceptual_guides/intro_agents"
      ><div class="w-full text-center bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">개념 가이드</div>
      <p class="text-gray-700">중요한 주제에 대한 전체적인 이해를 돕는 설명입니다.</p>
   </a>
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./tutorials/building_good_agents"
      ><div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">튜토리얼</div>
      <p class="text-gray-700">에이전트 구축의 중요한 측면을 다루는 포괄적인 튜토리얼입니다.</p>
    </a>
  </div>
</div>


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/index.md" />

### 에이전트 안내서[[agents---guided-tour]]
https://huggingface.co/docs/smolagents/main/ko/guided_tour.md

# 에이전트 안내서[[agents---guided-tour]]


이 안내서에서는 에이전트를 구축하는 방법, 실행하는 방법, 그리고 사용 사례에 맞게 더 잘 작동하도록 맞춤 설정하는 방법을 학습합니다.

## 에이전트 유형 선택: CodeAgent 또는 ToolCallingAgent[[choosing-an-agent-type:-codeagent-or-toolcallingagent]]

`smolagents`는 [CodeAgent](/docs/smolagents/main/ko/reference/agents#smolagents.CodeAgent)와 [ToolCallingAgent](/docs/smolagents/main/ko/reference/agents#smolagents.ToolCallingAgent) 두 가지 에이전트 클래스를 제공하는데, 이 두 클래스는 각각 에이전트가 도구와 상호작용하는 방법이 다릅니다.
두 방식의 핵심 차이점은 '액션을 지정하고 실행'하는 방식에 있습니다: 코드 생성 vs 구조화된 도구 호출.

- [CodeAgent](/docs/smolagents/main/ko/reference/agents#smolagents.CodeAgent)는 도구 호출을 Python 코드 스니펫으로 생성합니다.
  - 코드는 로컬에서 실행되거나(잠재적으로 불안전) 보안 샌드박스에서 실행됩니다.
  - 도구는 Python 함수로 노출됩니다(바인딩을 통해).
  - 도구 호출 예시:
    ```py
    result = search_docs("What is the capital of France?")
    print(result)
    ```
  - 장점:
    - 높은 표현력: 복잡한 로직과 제어 흐름을 허용하고 도구를 결합하고, 반복하고, 변환하고, 추론할 수 있습니다.
    - 유연성: 모든 가능한 액션을 미리 정의할 필요가 없으며, 동적으로 새로운 액션/도구를 생성할 수 있습니다.
    - 창발적 추론: 다단계 문제나 동적 로직에 이상적입니다.
  - 제한사항
    - 오류 위험: 구문 오류, 예외를 처리해야 합니다.
    - 예측성 부족: 예상치 못한 또는 안전하지 않은 출력에 더 취약합니다.
    - 보안 실행 환경이 필요합니다.

- [ToolCallingAgent](/docs/smolagents/main/ko/reference/agents#smolagents.ToolCallingAgent)는 도구 호출을 구조화된 JSON으로 작성합니다.
  - 이는 많은 프레임워크(OpenAI API)에서 사용되는 일반적인 형식으로, 코드 실행 없이 구조화된 도구 상호작용을 가능하게 합니다.
  - 도구는 JSON 스키마로 정의됩니다: 이름, 설명, 매개변수 타입 등.
  - 도구 호출 예시:
    ```json
    {
      "tool_call": {
        "name": "search_docs",
        "arguments": {
          "query": "What is the capital of France?"
        }
      }
    }
    ```
  - 장점:
    - 안정성: 환각이 적고, 출력이 구조화되고 검증됩니다.
    - 안전성: 인수가 엄격하게 검증되고, 임의의 코드가 실행될 위험이 없습니다.
    - 상호 운용성: 외부 API나 서비스에 쉽게 매핑됩니다.
  - 제한사항:
    - 낮은 표현력: 결과를 동적으로 쉽게 결합하거나 변환할 수 없고, 복잡한 로직이나 제어 흐름을 수행할 수 없습니다.
    - 유연성 부족: 모든 가능한 액션을 미리 정의해야 하고, 사전 정의된 도구로 제한됩니다.
    - 코드 합성 없음: 도구 기능으로 제한됩니다.

어떤 에이전트 유형을 사용할지:
- [CodeAgent](/docs/smolagents/main/ko/reference/agents#smolagents.CodeAgent)를 사용하는 경우:
  - 추론, 연결 또는 동적 구성이 필요한 경우.
  - 도구가 결합할 수 있는 함수인 경우(예: 구문 분석 + 수학 + 쿼리).
  - 에이전트가 문제 해결자 또는 프로그래머인 경우.

- [ToolCallingAgent](/docs/smolagents/main/ko/reference/agents#smolagents.ToolCallingAgent)를 사용하는 경우:
  - 단순하고 독립적인 도구가 있는 경우(예: API 호출, 문서 가져오기).
  - 높은 안정성과 명확한 검증을 원하는 경우.
  - 에이전트가 디스패처나 컨트롤러 같은 역할인 경우.

## CodeAgent[[codeagent]]

[CodeAgent](/docs/smolagents/main/ko/reference/agents#smolagents.CodeAgent)는 액션을 수행하고 작업을 해결하기 위해 Python 코드 스니펫을 생성합니다.

기본적으로 Python 코드 실행은 로컬 환경에서 수행됩니다.
사용자가 제공한 도구들(특히 Hugging Face 도구만 있는 경우)과 `print`나 `math` 모듈 함수 같은 사전 정의된 안전한 함수들만 호출할 수 있도록 제한되어 있어 안전합니다.

Python 인터프리터는 기본적으로 안전 목록에 포함된 모듈만 import를 허용하므로, 대부분의 명백한 보안 공격을 방지할 수 있습니다.
[CodeAgent](/docs/smolagents/main/ko/reference/agents#smolagents.CodeAgent)를 초기화할 때 `additional_authorized_imports` 인수에 문자열 목록으로 승인된 모듈을 전달하여 추가 import를 승인할 수 있습니다:

```py
model = InferenceClientModel()
agent = CodeAgent(tools=[], model=model, additional_authorized_imports=['requests', 'bs4'])
agent.run("Could you get me the title of the page at url 'https://huggingface.co/blog'?")
```

또한 추가 보안 계층으로, import 목록에서 명시적으로 승인되지 않는 한 서브모듈에 대한 접근은 기본적으로 금지됩니다.
예를 들어, `numpy.random` 서브모듈에 접근하려면 `additional_authorized_imports` 목록에 `'numpy.random'`을 추가해야 합니다.
이는 `numpy`와 `numpy.random` 같은 모든 서브패키지 및 자체 서브패키지를 허용하는 `numpy.*`를 사용하여 승인할 수도 있습니다.

> [!WARNING]
> LLM은 실행될 임의의 코드를 생성할 수 있습니다: 안전하지 않은 import는 추가하지 마세요!

불법적인 작업을 수행하려고 시도하는 코드나 에이전트가 생성한 코드에 일반적인 Python 오류가 있는 경우 실행이 중단됩니다.

로컬 Python 인터프리터 대신 [E2B code executor](https://e2b.dev/docs#what-is-e2-b)나 Docker를 사용할 수도 있습니다. E2B의 경우, 먼저 [`E2B_API_KEY` 환경 변수를 설정](https://e2b.dev/dashboard?tab=keys)한 다음 에이전트 초기화 시 `executor_type="e2b"`를 전달하세요. Docker의 경우, 초기화 중에 `executor_type="docker"`를 전달하세요.

> [!TIP]
> 코드 실행에 대해 더 자세히 알아보려면 [이 튜토리얼](tutorials/secure_code_execution)을 확인하세요.

### ToolCallingAgent[[toolcallingagent]]

[ToolCallingAgent](/docs/smolagents/main/ko/reference/agents#smolagents.ToolCallingAgent)는 많은 프레임워크(OpenAI API)에서 사용되는 일반적인 형식인 JSON 도구 호출을 출력하여, 코드 실행 없이 구조화된 도구 상호작용을 가능하게 합니다.

코드를 실행하지 않으므로 `additional_authorized_imports` 없이도 [CodeAgent](/docs/smolagents/main/ko/reference/agents#smolagents.CodeAgent)와 거의 동일한 방식으로 작동합니다:

```py
from smolagents import ToolCallingAgent, WebSearchTool

agent = ToolCallingAgent(tools=[WebSearchTool()], model=model)
agent.run("Could you get me the title of the page at url 'https://huggingface.co/blog'?")
```

## 에이전트 구축[[building-your-agent]]

최소한의 에이전트를 초기화하려면 최소한 다음 두 인수가 필요합니다:

- `model`, 에이전트를 구동하는 텍스트 생성 모델 - 에이전트는 단순한 LLM과 다르며, LLM을 엔진으로 사용하는 시스템입니다. 다음 옵션 중 하나를 사용할 수 있습니다:
    - [TransformersModel](/docs/smolagents/main/ko/reference/models#smolagents.TransformersModel)은 사전 초기화된 `transformers` 파이프라인을 가져와 `transformers`를 사용하여 로컬 머신에서 추론을 실행합니다.
    - [InferenceClientModel](/docs/smolagents/main/ko/reference/models#smolagents.InferenceClientModel)은 내부적으로 `huggingface_hub.InferenceClient`를 활용하며 Hub의 모든 추론 제공자를 지원합니다: Cerebras, Cohere, Fal, Fireworks, HF-Inference, Hyperbolic, Nebius, Novita, Replicate, SambaNova, Together 등.
    - [LiteLLMModel](/docs/smolagents/main/ko/reference/models#smolagents.LiteLLMModel)은 마찬가지로 [LiteLLM](https://docs.litellm.ai/)을 통해 100개 이상의 다양한 모델과 제공자를 호출할 수 있습니다!
    - [AzureOpenAIModel](/docs/smolagents/main/ko/reference/models#smolagents.AzureOpenAIModel)은 [Azure](https://azure.microsoft.com/en-us/products/ai-services/openai-service)에 배포된 OpenAI 모델을 사용할 수 있게 해줍니다.
    - [AmazonBedrockModel](/docs/smolagents/main/ko/reference/models#smolagents.AmazonBedrockModel)은 [AWS](https://aws.amazon.com/bedrock/?nc1=h_ls)의 Amazon Bedrock을 사용할 수 있게 해줍니다.
    - [MLXModel](/docs/smolagents/main/ko/reference/models#smolagents.MLXModel)은 로컬 머신에서 추론을 실행하기 위한 [mlx-lm](https://pypi.org/project/mlx-lm/) 파이프라인을 생성합니다.

- `tools`, 에이전트가 작업 해결에 사용할 수 있는 도구 목록입니다. 빈 목록으로 설정할 수도 있습니다. add_base_tools=True 옵션을 사용하면 기본 제공되는 도구들(웹 검색, 코드 실행, 음성 인식 등)을 `tools` 목록에 추가할 수 있습니다.

`tools`와 `model` 두 인수를 설정하면 에이전트를 생성하고 실행할 수 있습니다. [추론 제공자](https://huggingface.co/blog/inference-providers), [transformers](https://github.com/huggingface/transformers/), [ollama](https://ollama.com/), [LiteLLM](https://www.litellm.ai/), [Azure OpenAI](https://azure.microsoft.com/en-us/products/ai-services/openai-service), [Amazon Bedrock](https://aws.amazon.com/bedrock/?nc1=h_ls), 또는 [mlx-lm](https://pypi.org/project/mlx-lm/)을 통해 원하는 LLM을 사용할 수 있습니다.

모든 모델 클래스는 인스턴스화 시점에 추가 키워드 인수(예: `temperature`, `max_tokens`, `top_p` 등)를 직접 전달하는 것을 지원합니다.
이러한 매개변수는 기본 모델의 완성 호출에 자동으로 전달되어 창의성, 응답 길이, 샘플링 전략 등의 모델 동작을 구성할 수 있습니다.

<hfoptions id="Pick a LLM">
<hfoption id="Inference Providers">

추론 제공자는 인증을 위해 `HF_TOKEN`이 필요하지만, 무료 HF 계정에는 이미 포함된 크레딧이 제공됩니다. PRO로 업그레이드하여 포함된 크레딧을 늘리세요.

제한된 모델에 접근하거나 PRO 계정으로 속도 제한을 높이려면 환경 변수 `HF_TOKEN`을 설정하거나 `InferenceClientModel` 초기화 시 `token` 변수를 전달해야 합니다. [설정 페이지](https://huggingface.co/settings/tokens)에서 토큰을 얻을 수 있습니다.

```python
from smolagents import CodeAgent, InferenceClientModel

model_id = "meta-llama/Llama-3.3-70B-Instruct"

model = InferenceClientModel(model_id=model_id, token="<YOUR_HUGGINGFACEHUB_API_TOKEN>") # You can choose to not pass any model_id to InferenceClientModel to use a default model
# you can also specify a particular provider e.g. provider="together" or provider="sambanova"
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```
</hfoption>
<hfoption id="Local Transformers Model">

```python
# !pip install smolagents[transformers]
from smolagents import CodeAgent, TransformersModel

model_id = "meta-llama/Llama-3.2-3B-Instruct"

model = TransformersModel(model_id=model_id)
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```
</hfoption>
<hfoption id="OpenAI or Anthropic API">

`LiteLLMModel`을 사용하려면 환경 변수 `ANTHROPIC_API_KEY` 또는 `OPENAI_API_KEY`를 설정하거나 초기화 시 `api_key` 변수를 전달해야 합니다.

```python
# !pip install smolagents[litellm]
from smolagents import CodeAgent, LiteLLMModel

model = LiteLLMModel(model_id="anthropic/claude-3-5-sonnet-latest", api_key="YOUR_ANTHROPIC_API_KEY") # Could use 'gpt-4o'
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```
</hfoption>
<hfoption id="Ollama">

```python
# !pip install smolagents[litellm]
from smolagents import CodeAgent, LiteLLMModel

model = LiteLLMModel(
    model_id="ollama_chat/llama3.2", # This model is a bit weak for agentic behaviours though
    api_base="http://localhost:11434", # replace with 127.0.0.1:11434 or remote open-ai compatible server if necessary
    api_key="YOUR_API_KEY", # replace with API key if necessary
    num_ctx=8192, # ollama default is 2048 which will fail horribly. 8192 works for easy tasks, more is better. Check https://huggingface.co/spaces/NyxKrage/LLM-Model-VRAM-Calculator to calculate how much VRAM this will need for the selected model.
)

agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```
</hfoption>
<hfoption id="Azure OpenAI">

Azure OpenAI에 연결하려면 `AzureOpenAIModel`을 직접 사용하거나 `LiteLLMModel`을 사용하여 적절히 구성할 수 있습니다.

`AzureOpenAIModel`의 인스턴스를 초기화하려면 모델 배포 이름을 전달한 다음 `azure_endpoint`, `api_key`, `api_version` 인수를 전달하거나 환경 변수 `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_API_KEY`, `OPENAI_API_VERSION`을 설정해야 합니다.

```python
# !pip install smolagents[openai]
from smolagents import CodeAgent, AzureOpenAIModel

model = AzureOpenAIModel(model_id="gpt-4o-mini")
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```

마찬가지로 다음과 같이 `LiteLLMModel`을 구성하여 Azure OpenAI에 연결할 수 있습니다:

- 모델 배포 이름을 `model_id`로 전달하고, 앞에 `azure/`를 붙여야 합니다.
- 환경 변수 `AZURE_API_VERSION`을 설정해야 합니다.
- `api_base`와 `api_key` 인수를 전달하거나 환경 변수 `AZURE_API_KEY`, `AZURE_API_BASE`를 설정합니다.

```python
import os
from smolagents import CodeAgent, LiteLLMModel

AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="gpt-35-turbo-16k-deployment" # example of deployment name

os.environ["AZURE_API_KEY"] = "" # api_key
os.environ["AZURE_API_BASE"] = "" # "https://example-endpoint.openai.azure.com"
os.environ["AZURE_API_VERSION"] = "" # "2024-10-01-preview"

model = LiteLLMModel(model_id="azure/" + AZURE_OPENAI_CHAT_DEPLOYMENT_NAME)
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
   "Could you give me the 118th number in the Fibonacci sequence?",
)
```

</hfoption>
<hfoption id="Amazon Bedrock">

`AmazonBedrockModel` 클래스는 Amazon Bedrock과 직접 연동되어 API 호출과 세부 구성을 지원합니다.

기본 사용법:

```python
# !pip install smolagents[aws_sdk]
from smolagents import CodeAgent, AmazonBedrockModel

model = AmazonBedrockModel(model_id="anthropic.claude-3-sonnet-20240229-v1:0")
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```

고급 구성:

```python
import boto3
from smolagents import AmazonBedrockModel

# Create a custom Bedrock client
bedrock_client = boto3.client(
    'bedrock-runtime',
    region_name='us-east-1',
    aws_access_key_id='YOUR_ACCESS_KEY',
    aws_secret_access_key='YOUR_SECRET_KEY'
)

additional_api_config = {
    "inferenceConfig": {
        "maxTokens": 3000
    },
    "guardrailConfig": {
        "guardrailIdentifier": "identify1",
        "guardrailVersion": 'v1'
    },
}

# Initialize with comprehensive configuration
model = AmazonBedrockModel(
    model_id="us.amazon.nova-pro-v1:0",
    client=bedrock_client,  # Use custom client
    **additional_api_config
)

agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```

LiteLLMModel 사용:

또는 Bedrock 모델과 함께 `LiteLLMModel`을 사용할 수 있습니다:

```python
from smolagents import LiteLLMModel, CodeAgent

model = LiteLLMModel(model_name="bedrock/anthropic.claude-3-sonnet-20240229-v1:0")
agent = CodeAgent(tools=[], model=model)

agent.run("Explain the concept of quantum computing")
```

</hfoption>
<hfoption id="mlx-lm">

```python
# !pip install smolagents[mlx-lm]
from smolagents import CodeAgent, MLXModel

mlx_model = MLXModel("mlx-community/Qwen2.5-Coder-32B-Instruct-4bit")
agent = CodeAgent(model=mlx_model, tools=[], add_base_tools=True)

agent.run("Could you give me the 118th number in the Fibonacci sequence?")
```

</hfoption>
</hfoptions>

## 고급 에이전트 구성[[advanced-agent-configuration]]

### 에이전트 종료 조건 맞춤 설정[[customizing-agent-termination-conditions]]

기본적으로 에이전트는 `final_answer` 함수를 호출하거나 최대 단계 수에 도달할 때까지 계속 실행됩니다.
`final_answer_checks` 매개변수는 에이전트가 실행을 종료하는 시점과 방법을 더 세밀하게 제어할 수 있게 해줍니다:

```python
from smolagents import CodeAgent, InferenceClientModel

# Define a custom final answer check function
def is_integer(final_answer: str, agent_memory=None) -> bool:
    """Return True if final_answer is an integer."""
    try:
        int(final_answer)
        return True
    except ValueError:
        return False

# Initialize agent with custom final answer check
agent = CodeAgent(
    tools=[],
    model=InferenceClientModel(),
    final_answer_checks=[is_integer]
)

agent.run("Calculate the least common multiple of 3 and 7")
```

`final_answer_checks` 매개변수는 각각 다음과 같은 함수들의 목록을 받습니다:
- 에이전트의 final_answer 문자열과 에이전트의 메모리를 매개변수로 받습니다
- final_answer가 유효한지(True) 아닌지(False)를 나타내는 불리언을 반환합니다

함수 중 하나라도 `False`를 반환하면 에이전트는 오류 메시지를 로그에 기록하고 실행을 계속합니다.
이 검증 메커니즘은 다음을 가능하게 합니다:
- 출력 형식 요구사항 강제(예: 수학 문제에 대한 숫자 답변 보장)
- 도메인별 검증 규칙 구현
- 자체 출력을 검증하는 더 견고한 에이전트 생성

## 에이전트 실행 검사[[inspecting-an-agent-run]]

실행 후 무슨 일이 일어났는지 확인하는 데 유용한 몇 가지 속성이 있습니다:

- `agent.logs`는 에이전트의 상세한 실행 로그를 저장합니다. 에이전트 실행의 각 단계마다 모든 정보가 딕셔너리 형태로 저장되어 `agent.logs`에 추가됩니다.
- `agent.write_memory_to_messages()`는 에이전트의 메모리를 모델이 볼 수 있는 채팅 메시지 목록으로 변환합니다. 이 메소드는 로그의 각 단계를 살펴보고 중요한 내용만 메시지로 저장합니다. 예를 들어, 시스템 프롬프트와 작업을 각각 별도 메시지로 저장하고, 각 단계의 LLM 출력과 도구 호출 결과를 개별 메시지로 저장합니다. 전체적인 흐름 파악이 필요할 때 권장드립니다. 단, 모든 로그가 이 메소드를 통해 기록되는 것은 아닙니다.

## 도구[[tools]]

도구는 에이전트가 사용할 수 있는 독립적인 함수입니다. LLM이 도구를 사용하기 위해서는 먼저 API를 구성해야하며, 또한 LLM에게 해당 도구 호출하는 방법을 설명해주어야합니다 :
- 이름
- 설명
- 입력 타입과 설명
- 출력 타입

예를 들어 `PythonInterpreterTool`을 확인할 수 있습니다: 이름, 설명, 입력 설명, 출력 타입, 그리고 액션을 수행하는 `forward` 메소드가 있습니다.

에이전트가 초기화될 때 도구 속성이 에이전트의 시스템 프롬프트에 포함되는 도구 설명을 생성하는 데 사용됩니다. 이를 통해 에이전트는 사용할 수 있는 도구와 그 이유를 알 수 있습니다.

**스키마 정보**: `output_schema`가 정의된 도구(구조화된 출력을 가진 MCP 도구 등)의 경우, `CodeAgent` 시스템 프롬프트에 자동으로 JSON 스키마 정보가 포함됩니다. 이는 에이전트가 도구 출력의 예상 구조를 이해하고 데이터에 적절히 접근할 수 있도록 도와줍니다.

### 기본 툴박스[[default-toolbox]]

"toolkit" extra와 함께 `smolagents`를 설치하면 에이전트를 강화하는 기본 툴박스가 함께 제공되며, `add_base_tools=True` 인수로 초기화 시 에이전트에 추가할 수 있습니다:

- **DuckDuckGo 웹 검색***: DuckDuckGo 브라우저를 사용하여 웹 검색을 수행합니다.
- **Python 코드 인터프리터**: 보안 환경에서 LLM이 생성한 Python 코드를 실행합니다. 이 도구는 코드 기반 에이전트가 이미 기본적으로 Python 코드를 실행할 수 있으므로 `add_base_tools=True`로 초기화할 때만 [ToolCallingAgent](/docs/smolagents/main/ko/reference/agents#smolagents.ToolCallingAgent)에 추가됩니다.
- **Transcriber**: 오디오를 텍스트로 변환하는 Whisper-Turbo 기반의 음성-텍스트 파이프라인입니다.

인수와 함께 호출하여 도구를 수동으로 사용할 수 있습니다.

```python
# !pip install smolagents[toolkit]
from smolagents import WebSearchTool

search_tool = WebSearchTool()
print(search_tool("Who's the current president of Russia?"))
```

### 새로운 도구 생성[[create-a-new-tool]]

Hugging Face의 기본 도구가 다루지 않는 사용 사례를 위해 자신만의 도구를 만들 수 있습니다.
예를 들어, Hub에서 주어진 작업에 대해 가장 많이 다운로드된 모델을 반환하는 도구를 만들어보겠습니다.

아래 코드부터 시작하겠습니다.

```python
from huggingface_hub import list_models

task = "text-classification"

most_downloaded_model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
print(most_downloaded_model.id)
```

이 코드는 함수로 만들고 `tool` 데코레이터를 추가하여 간단히 도구로 변환할 수 있습니다.
하지만 이것이 도구를 만드는 유일한 방법은 아닙니다. [Tool]의 하위 클래스로 직접 정의하는 방법도 있으며, 이 방식은 더 많은 유연성을 제공합니다. 예를 들어 리소스 집약적인 클래스 속성을 초기화할 때 유용합니다.

두 옵션 모두에서 어떻게 작동하는지 살펴보겠습니다:

<hfoptions id="build-a-tool">
<hfoption id="Decorate a function with @tool">

```py
from smolagents import tool

@tool
def model_download_tool(task: str) -> str:
    """
    This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub.
    It returns the name of the checkpoint.

    Args:
        task: The task for which to get the download count.
    """
    most_downloaded_model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
    return most_downloaded_model.id
```

함수에는 다음이 필요합니다:
- 명확한 이름. 이름은 에이전트를 구동하는 LLM이 이해할 수 있도록 이 도구가 무엇을 하는지 충분히 설명적이어야 합니다. 이 도구는 작업에 대해 가장 많이 다운로드된 모델을 반환하므로 `model_download_tool`이라고 명명하겠습니다.
- 입력과 출력 모두에 대한 타입 힌트
- 각 인수가 설명되는 'Args:' 부분을 포함하는 설명(이번에는 타입 표시 없이, 타입 힌트에서 가져옵니다). 도구 이름과 마찬가지로, 이 설명은 에이전트를 구동하는 LLM을 위한 설명서이므로 소홀히 하지 마세요.

이 모든 요소는 초기화 시 에이전트의 시스템 프롬프트에 자동으로 포함됩니다: 따라서 최대한 명확하게 만들도록 노력하세요!

> [!TIP]
> 이 정의 형식은 `apply_chat_template`에서 사용되는 도구 스키마와 동일하며, 유일한 차이점은 추가된 `tool` 데코레이터입니다: 도구 사용 API에 대해 더 자세히 알아보려면 [여기](https://huggingface.co/blog/unified-tool-use#passing-tools-to-a-chat-template)를 읽어보세요.


그런 다음 에이전트를 직접 초기화할 수 있습니다:
```py
from smolagents import CodeAgent, InferenceClientModel
agent = CodeAgent(tools=[model_download_tool], model=InferenceClientModel())
agent.run(
    "Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?"
)
```
</hfoption>
<hfoption id="Subclass Tool">

```py
from smolagents import Tool

class ModelDownloadTool(Tool):
    name = "model_download_tool"
    description = "This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. It returns the name of the checkpoint."
    inputs = {"task": {"type": "string", "description": "The task for which to get the download count."}}
    output_type = "string"

    def forward(self, task: str) -> str:
        most_downloaded_model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
        return most_downloaded_model.id
```

하위 클래스에는 다음 속성이 필요합니다:
- 명확한 `name` (이름). 에이전트를 구동하는 LLM이 도구의 기능을 이해할 수 있도록 이름에 대해 충분히 설명해야 합니다. 이 도구는 작업에 대해 가장 많이 다운로드된 모델을 반환하므로 `model_download_tool`이라고 명명하겠습니다.
- `description`. `name`과 마찬가지로, 이 설명은 에이전트를 구동하는 LLM을 위한 설명서이므로 소홀히 하지 마세요.
- 입력 타입과 설명
- 출력 타입
이 모든 속성은 초기화 시 에이전트의 시스템 프롬프트에 자동으로 포함됩니다: 따라서 최대한 명확하게 만들도록 노력하세요!


그런 다음 에이전트를 직접 초기화할 수 있습니다:
```py
from smolagents import CodeAgent, InferenceClientModel
agent = CodeAgent(tools=[ModelDownloadTool()], model=InferenceClientModel())
agent.run(
    "Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?"
)
```
</hfoption>
</hfoptions>

다음 로그를 얻습니다:
```text
╭──────────────────────────────────────── New run ─────────────────────────────────────────╮
│                                                                                          │
│ Can you give me the name of the model that has the most downloads in the 'text-to-video' │
│ task on the Hugging Face Hub?                                                            │
│                                                                                          │
╰─ InferenceClientModel - Qwen/Qwen2.5-Coder-32B-Instruct ───────────────────────────────────────────╯
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Step 0 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
╭─ Executing this code: ───────────────────────────────────────────────────────────────────╮
│   1 model_name = model_download_tool(task="text-to-video")                               │
│   2 print(model_name)                                                                    │
╰──────────────────────────────────────────────────────────────────────────────────────────╯
Execution logs:
ByteDance/AnimateDiff-Lightning

Out: None
[Step 0: Duration 0.27 seconds| Input tokens: 2,069 | Output tokens: 60]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Step 1 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
╭─ Executing this code: ───────────────────────────────────────────────────────────────────╮
│   1 final_answer("ByteDance/AnimateDiff-Lightning")                                      │
╰──────────────────────────────────────────────────────────────────────────────────────────╯
Out - Final answer: ByteDance/AnimateDiff-Lightning
[Step 1: Duration 0.10 seconds| Input tokens: 4,288 | Output tokens: 148]
Out[20]: 'ByteDance/AnimateDiff-Lightning'
```

> [!TIP]
> 도구에 대해 더 자세히 알아보려면 [전용 튜토리얼](./tutorials/tools#what-is-a-tool-and-how-to-build-one)을 읽어보세요.

## 멀티 에이전트[[multi-agents]]

멀티 에이전트 시스템은 Microsoft의 프레임워크 [Autogen](https://huggingface.co/papers/2308.08155)과 함께 도입되었습니다.

이러한 프레임워크에서는 단일 에이전트 대신 여러 에이전트가 협력하여 작업을 해결합니다.
실제로 대부분의 벤치마크에서 더 우수한 성능을 보여줍니다. 성능이 향상되는 이유는 개념적으로 단순합니다. 많은 작업에서 모든 기능을 담당하는 범용 시스템보다는 특정 하위 작업에 특화된 전문 단위를 사용하는 것이 더 효과적이기 때문입니다. 서로 다른 도구와 메모리를 가진 에이전트들을 활용하면 효율적인 역할 분담이 가능합니다. 예를 들어, 웹 검색 에이전트가 수집한 모든 웹페이지 내용을 코드 생성 에이전트의 메모리에까지 저장할 필요가 있을까요? 각자의 역할에 맞게 분리해서 운영하는 것이 훨씬 효율적입니다.

`smolagents`로 계층적 멀티 에이전트 시스템을 쉽게 구축할 수 있습니다.

이를 위해서는 에이전트에 `name`과 `description` 속성만 있으면 되며, 이는 도구와 마찬가지로 관리자 에이전트의 시스템 프롬프트에 포함되어 관리되는 에이전트를 호출하는 방법을 알려줍니다.
그런 다음 관리자 에이전트를 초기화할 때 `managed_agents` 매개변수에 이 관리되는 에이전트를 전달할 수 있습니다.

다음은 네이티브 `WebSearchTool`을 사용하여 특정 웹 검색 에이전트를 관리하는 에이전트를 만드는 예시입니다:

```py
from smolagents import CodeAgent, InferenceClientModel, WebSearchTool

model = InferenceClientModel()

web_agent = CodeAgent(
    tools=[WebSearchTool()],
    model=model,
    name="web_search_agent",
    description="Runs web searches for you. Give it your query as an argument."
)

manager_agent = CodeAgent(
    tools=[], model=model, managed_agents=[web_agent]
)

manager_agent.run("Who is the CEO of Hugging Face?")
```

> [!TIP]
> 효율적인 멀티 에이전트 구현의 심화 예제를 보려면 [멀티 에이전트 시스템을 GAIA 리더보드 상위권으로 끌어올린 방법](https://huggingface.co/blog/beating-gaia)을 확인하세요.

## 에이전트와 대화하고 멋진 Gradio 인터페이스에서 그 사고 과정을 시각화하기[[talk-with-your-agent-and-visualize-its-thoughts-in-a-cool-gradio-interface]]

`GradioUI`를 사용하여 에이전트에 대화형으로 작업을 제출하고 그 사고와 실행 과정을 관찰할 수 있습니다. 다음은 예시입니다:

```py
from smolagents import (
    load_tool,
    CodeAgent,
    InferenceClientModel,
    GradioUI
)

# Import tool from Hub
image_generation_tool = load_tool("m-ric/text-to-image", trust_remote_code=True)

model = InferenceClientModel(model_id=model_id)

# Initialize the agent with the image generation tool
agent = CodeAgent(tools=[image_generation_tool], model=model)

GradioUI(agent).launch()
```

내부적으로 사용자가 새로운 요청을 입력하면 에이전트는 `agent.run(user_request, reset=False)`로 실행됩니다.
`reset=False` 플래그는 이 새로운 작업을 실행하기 전에 에이전트의 메모리가 플러시되지 않음을 의미하며, 이를 통해 대화가 계속될 수 있습니다.

다른 에이전트 애플리케이션에서도 이 `reset=False` 인수를 사용하여 대화를 계속할 수 있습니다.

Gradio UI에서 사용자가 실행 중인 에이전트를 중단할 수 있도록 하려면 `agent.interrupt()` 메소드를 트리거하는 버튼으로 이를 수행할 수 있습니다.
이렇게 하면 현재 단계가 끝날 때 에이전트가 중지되고 오류가 발생합니다.

## 다음 단계[[next-steps]]

마지막으로 에이전트를 필요에 맞게 구성했다면 Hub에 공유할 수 있습니다!

```py
agent.push_to_hub("m-ric/my_agent")
```

마찬가지로, 도구의 코드를 신뢰한다면 Hub에 업로드된 에이전트를 불러오려면 다음을 사용하세요:
```py
agent.from_hub("m-ric/my_agent", trust_remote_code=True)
```

더 자세한 활용법을 원한다면 다음 튜토리얼들을 참고하세요:
- [코드 에이전트가 작동하는 방법에 대한 설명](./tutorials/secure_code_execution)
- [좋은 에이전트를 구축하는 방법에 대한 가이드](./tutorials/building_good_agents).
- [도구 사용에 대한 상세 가이드](./tutorials/building_good_agents).


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/guided_tour.md" />

### 설치 옵션[[installation-options]]
https://huggingface.co/docs/smolagents/main/ko/installation.md

# 설치 옵션[[installation-options]]

`smolagents` 라이브러리는 pip를 사용하여 설치할 수 있습니다. 사용 가능한 다양한 설치 방법과 옵션을 소개합니다.

## 사전 요구사항[[prerequisites]]
- Python 3.10 이상
- Python 패키지 관리자: [`pip`](https://pip.pypa.io/en/stable/) 또는 [`uv`](https://docs.astral.sh/uv/)

## 가상 환경[[virtual-environment]]

`smolagents`를 Python 가상 환경 내에서 설치하는 것을 강력히 권장합니다.
가상 환경은 프로젝트의 의존성을 다른 Python 프로젝트와 시스템 Python 설치로부터 격리하여
버전 충돌을 방지하고 패키지 관리를 더욱 안정적으로 만들어줍니다.

<hfoptions id="virtual-environment">
<hfoption id="venv">

[`venv`](https://docs.python.org/3/library/venv.html) 사용:

```bash
python -m venv .venv
source .venv/bin/activate
```

</hfoption>
<hfoption id="uv">

[`uv`](https://docs.astral.sh/uv/) 사용:

```bash
uv venv .venv
source .venv/bin/activate
```

</hfoption>
</hfoptions>

## 기본 설치[[basic-installation]]

`smolagents` 핵심 라이브러리를 설치합니다:

<hfoptions id="installation">
<hfoption id="pip">
```bash
pip install smolagents
```
</hfoption>
<hfoption id="uv">
```bash
uv pip install smolagents
```
</hfoption>
</hfoptions>

## 추가 기능과 함께 설치[[installation-with-extras]]

`smolagents`는 필요에 따라 설치할 수 있는 여러 선택적 의존성(extras)을 제공합니다.
다음 구문을 사용하여 이러한 추가 기능을 설치할 수 있습니다:
<hfoptions id="installation">
<hfoption id="pip">
```bash
pip install "smolagents[extra1,extra2]"
```
</hfoption>
<hfoption id="uv">
```bash
uv pip install "smolagents[extra1,extra2]"
```
</hfoption>
</hfoptions>

### 도구[[tools]]
다음 추가 기능은 다양한 도구와 통합을 포함합니다:
<hfoptions id="installation">
<hfoption id="pip">
- **toolkit**: 일반적인 작업을 위한 기본 도구 세트를 설치합니다.
  ```bash
  pip install "smolagents[toolkit]"
  ```
- **mcp**: 외부 도구 및 서비스와 통합하기 위한 Model Context Protocol (MCP) 지원을 추가합니다.
  ```bash
  pip install "smolagents[mcp]"
  ```
</hfoption>
<hfoption id="uv">
- **toolkit**: 일반적인 작업을 위한 기본 도구 세트를 설치합니다.
  ```bash
  uv pip install "smolagents[toolkit]"
  ```
- **mcp**: 외부 도구 및 서비스와 통합하기 위한 Model Context Protocol (MCP) 지원을 추가합니다.
  ```bash
  uv pip install "smolagents[mcp]"
  ```
</hfoption>
</hfoptions>

### 모델 통합[[model-integration]]
다음 추가 기능은 다양한 AI 모델 및 프레임워크와의 통합을 가능하게 합니다:
<hfoptions id="installation">
<hfoption id="pip">
- **openai**: OpenAI API 모델 지원을 추가합니다.
  ```bash
  pip install "smolagents[openai]"
  ```
- **transformers**: Hugging Face 트랜스포머 모델을 활성화합니다.
  ```bash
  pip install "smolagents[transformers]"
  ```
- **vllm**: 효율적인 모델 추론을 위한 VLLM 지원을 추가합니다.
  ```bash
  pip install "smolagents[vllm]"
  ```
- **mlx-lm**: MLX-LM 모델 지원을 활성화합니다.
  ```bash
  pip install "smolagents[mlx-lm]"
  ```
- **litellm**: 경량 모델 추론을 위한 LiteLLM 지원을 추가합니다.
  ```bash
  pip install "smolagents[litellm]"
  ```
- **bedrock**: AWS Bedrock 모델 지원을 활성화합니다.
  ```bash
  pip install "smolagents[bedrock]"
  ```
</hfoption>
<hfoption id="uv">
- **openai**: OpenAI API 모델 지원을 추가합니다.
  ```bash
  uv pip install "smolagents[openai]"
  ```
- **transformers**: Hugging Face 트랜스포머 모델을 활성화합니다.
  ```bash
  uv pip install "smolagents[transformers]"
  ```
- **vllm**: 효율적인 모델 추론을 위한 VLLM 지원을 추가합니다.
  ```bash
  uv pip install "smolagents[vllm]"
  ```
- **mlx-lm**: MLX-LM 모델 지원을 활성화합니다.
  ```bash
  uv pip install "smolagents[mlx-lm]"
  ```
- **litellm**: 경량 모델 추론을 위한 LiteLLM 지원을 추가합니다.
  ```bash
  uv pip install "smolagents[litellm]"
  ```
- **bedrock**: AWS Bedrock 모델 지원을 활성화합니다.
  ```bash
  uv pip install "smolagents[bedrock]"
  ```
</hfoption>
</hfoptions>

### 멀티모달 기능[[multimodal-capabilities]]
다양한 미디어 유형 및 입력 처리를 위한 추가 기능:
<hfoptions id="installation">
<hfoption id="pip">
- **vision**: 이미지 처리 및 컴퓨터 비전 작업 지원을 추가합니다.
  ```bash
  pip install "smolagents[vision]"
  ```
- **audio**: 오디오 처리 기능을 활성화합니다.
  ```bash
  pip install "smolagents[audio]"
  ```
</hfoption>
<hfoption id="uv">
- **vision**: 이미지 처리 및 컴퓨터 비전 작업 지원을 추가합니다.
  ```bash
  uv pip install "smolagents[vision]"
  ```
- **audio**: 오디오 처리 기능을 활성화합니다.
  ```bash
  uv pip install "smolagents[audio]"
  ```
</hfoption>
</hfoptions>

### 원격 실행[[remote-execution]]
코드를 원격으로 실행하기 위한 추가 기능:
<hfoptions id="installation">
<hfoption id="pip">
- **docker**: Docker 컨테이너에서 코드를 실행하는 지원을 추가합니다.
  ```bash
  pip install "smolagents[docker]"
  ```
- **e2b**: 원격 실행을 위한 E2B 지원을 활성화합니다.
  ```bash
  pip install "smolagents[e2b]"
  ```
</hfoption>
<hfoption id="uv">
- **docker**: Docker 컨테이너에서 코드를 실행하는 지원을 추가합니다.
  ```bash
  uv pip install "smolagents[docker]"
  ```
- **e2b**: 원격 실행을 위한 E2B 지원을 활성화합니다.
  ```bash
  uv pip install "smolagents[e2b]"
  ```
</hfoption>
</hfoptions>

### 텔레메트리 및 사용자 인터페이스[[telemetry-and-user-interface]]
텔레메트리, 모니터링 및 사용자 인터페이스 구성 요소를 위한 추가 기능:
<hfoptions id="installation">
<hfoption id="pip">
- **telemetry**: 모니터링 및 추적 지원을 추가합니다.
  ```bash
  pip install "smolagents[telemetry]"
  ```
- **gradio**: 대화형 Gradio UI 구성 요소 지원을 추가합니다.
  ```bash
  pip install "smolagents[gradio]"
  ```
</hfoption>
<hfoption id="uv">
- **telemetry**: 모니터링 및 추적 지원을 추가합니다.
  ```bash
  uv pip install "smolagents[telemetry]"
  ```
- **gradio**: 대화형 Gradio UI 구성 요소 지원을 추가합니다.
  ```bash
  uv pip install "smolagents[gradio]"
  ```
</hfoption>
</hfoptions>

### 전체 설치[[complete-installation]]
사용 가능한 모든 추가 기능을 설치하려면 다음을 사용할 수 있습니다:
<hfoptions id="installation">
<hfoption id="pip">
```bash
pip install "smolagents[all]"
```
</hfoption>
<hfoption id="uv">
```bash
uv pip install "smolagents[all]"
```
</hfoption>
</hfoptions>

## 설치 확인[[verifying-installation]]
설치 후, 다음 코드를 실행해 `smolagents`가 올바르게 설치되었는지 확인할 수 있습니다:
```python
import smolagents
print(smolagents.__version__)
```

## 다음 단계[[next-steps]]
`smolagents`를 성공적으로 설치했다면 다음을 수행할 수 있습니다:
- [안내서](./guided_tour)를 따라 기본 개념을 배워보세요.
- 실용적인 예제를 보고 싶다면 [사용법 가이드](./examples/text_to_sql)를 살펴보세요.
- 고수준 설명을 보려면 [개념 가이드](./conceptual_guides/intro_agents)를 읽어보세요.
- 에이전트 구축에 대한 심화 튜토리얼은 [튜토리얼](./tutorials/building_good_agents)를 확인해보세요.
- 클래스와 함수에 대한 자세한 정보를 확인하고 싶으시면 [API 레퍼런스](./reference/index)를 살펴보세요.


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/installation.md" />

### 멀티스텝 에이전트는 어떻게 동작하나요?[[how-do-multi-step-agents-work]]
https://huggingface.co/docs/smolagents/main/ko/conceptual_guides/react.md

# 멀티스텝 에이전트는 어떻게 동작하나요?[[how-do-multi-step-agents-work]]

ReAct 프레임워크([Yao et al., 2022](https://huggingface.co/papers/2210.03629))는 현재 에이전트 구축하는 가장 일반적인 접근 방식입니다.

ReAct라는 이름은 "추론(Reason)"과 "행동(Act)"을 결합한 것입니다. 실제로 이 구조를 따르는 에이전트는 주어진 작업을 해결하기 위해 필요한 만큼 여러 단계를 거칩니다. 각 단계는 추론 단계와 행동 단계로 이루어져 있으며, 행동 단계에서는 작업 해결에 가까워지도록 다양한 도구를 호출합니다.

`smolagents`가 제공하는 모든 에이전트는 ReAct 프레임워크를 추상화한 단일 `MultiStepAgent` 클래스를 기반으로 합니다.

이 클래스는 기본적으로 아래와 같은 루프로 동작하며, 기존 변수와 지식도 에이전트 로그에 함께 반영됩니다.

초기화: 시스템 프롬프트는 `SystemPromptStep`에 저장되고, 사용자가 입력한 쿼리는 `TaskStep`에 기록됩니다.

While 루프 (ReAct 루프):

- `agent.write_memory_to_messages()`를 사용하여 에이전트 로그를 LLM이 읽을 수 있는 [채팅 메시지](https://huggingface.co/docs/transformers/en/chat_templating) 목록에 작성합니다.
- 이 메시지를 `Model` 객체에 전송하여 응답을 받습니다. 에이전트는 응답을 파싱하여 액션(`ToolCallingAgent`의 경우 JSON blob, `CodeAgent`의 경우 코드 스니펫)을 추출합니다.
- 액션을 실행하고 결과를 메모리에 기록합니다(`ActionStep`).
- 각 단계가 끝날 때마다 `agent.step_callbacks`에 정의된 모든 콜백 함수를 실행합니다.

**계획(planning)**이 활성화된 경우에는 주기적으로 계획을 수정하고 이를 `PlanningStep`에 저장할 수 있습니다. 이 과정에는 현재 작업과 관련된 사실을 메모리에 기록하는 것도 포함됩니다.

`CodeAgent`의 경우, 이 과정은 아래 그림과 같이 나타납니다.

<div class="flex justify-center">
    <img
        src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/codeagent_docs.png"
    />
</div>

비디오를 통해 동작 과정을 확인해보세요.

<div class="flex justify-center">
    <img
        class="block dark:hidden"
        src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/Agent_ManimCE.gif"
    />
    <img
        class="hidden dark:block"
        src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/Agent_ManimCE.gif"
    />
</div>

`smolagents` 라이브러리는 두 가지 버전의 에이전트를 제공합니다.
- 도구 호출을 Python 코드 스니펫 형태로 생성하는 [CodeAgent](/docs/smolagents/main/ko/reference/agents#smolagents.CodeAgent)
- 많은 프레임워크에서 일반적으로 사용하는 방식처럼 도구 호출을 JSON 형태로 작성하는 [ToolCallingAgent](/docs/smolagents/main/ko/reference/agents#smolagents.ToolCallingAgent)

필요에 따라 두 방식 중 어느 것이든 사용할 수 있습니다. 예를 들어, 웹 브라우징처럼 각 페이지 상호작용 후 대기 시간이 필요한 경우 JSON 기반 도구 호출이 잘 맞을 수 있습니다.

> [!TIP]
> 멀티스텝 에이전트에 대해 더 알고 싶다면 허깅페이스 블로그의 [Open-source LLMs as LangChain Agents](https://huggingface.co/blog/open-source-llms-as-agents) 포스트를 읽어보세요.

<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/conceptual_guides/react.md" />

### 에이전트[[agents]]
https://huggingface.co/docs/smolagents/main/ko/reference/agents.md

# 에이전트[[agents]]

<Tip warning={true}>

Smolagents는 실험적인 API로 언제든지 변경될 수 있습니다. API나 사용되는 모델이 변경될 수 있기 때문에 에이전트가 반환하는 결과도 달라질 수 있습니다.

</Tip>

에이전트와 도구에 대해 더 자세히 알아보려면 [소개 가이드](../index)를 꼭 읽어보세요. 이 페이지에는 기본 클래스에 대한 API 문서가 포함되어 있습니다.

## 에이전트[[agents]]

저희 에이전트는 [MultiStepAgent](/docs/smolagents/main/ko/reference/agents#smolagents.MultiStepAgent)를 상속받으며, 이는 하나의 생각과 하나의 도구 호출 및 실행으로 구성된 여러 단계를 수행할 수 있음을 의미합니다. 이 [개념 가이드](../conceptual_guides/react)에서 더 자세히 알아보세요.

저희는 메인 `Agent` 클래스를 기반으로 두 가지 유형의 에이전트를 제공합니다.
  - [CodeAgent](/docs/smolagents/main/ko/reference/agents#smolagents.CodeAgent)는 Python 코드로 도구 호출을 작성합니다.(이것이 기본값입니다.)
  - [ToolCallingAgent](/docs/smolagents/main/ko/reference/agents#smolagents.ToolCallingAgent)는 JSON 형식으로 도구 호출을 작성합니다.

두 경우 모두 초기화 시 `model`과 도구 목록인 `tools`를 인수로 요구합니다.

### 에이전트 클래스[[smolagents.MultiStepAgent]][[smolagents.MultiStepAgent]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.MultiStepAgent</name><anchor>smolagents.MultiStepAgent</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L266</source><parameters>[{"name": "tools", "val": ": list"}, {"name": "model", "val": ": Model"}, {"name": "prompt_templates", "val": ": smolagents.agents.PromptTemplates | None = None"}, {"name": "instructions", "val": ": str | None = None"}, {"name": "max_steps", "val": ": int = 20"}, {"name": "add_base_tools", "val": ": bool = False"}, {"name": "verbosity_level", "val": ": LogLevel = <LogLevel.INFO: 1>"}, {"name": "managed_agents", "val": ": list | None = None"}, {"name": "step_callbacks", "val": ": list[collections.abc.Callable] | dict[typing.Type[smolagents.memory.MemoryStep], collections.abc.Callable | list[collections.abc.Callable]] | None = None"}, {"name": "planning_interval", "val": ": int | None = None"}, {"name": "name", "val": ": str | None = None"}, {"name": "description", "val": ": str | None = None"}, {"name": "provide_run_summary", "val": ": bool = False"}, {"name": "final_answer_checks", "val": ": list[collections.abc.Callable] | None = None"}, {"name": "return_full_result", "val": ": bool = False"}, {"name": "logger", "val": ": smolagents.monitoring.AgentLogger | None = None"}]</parameters><paramsdesc>- **tools** (`list[Tool]`) -- `Tool`s that the agent can use.
- **model** (`Callable[[list[dict[str, str]]], ChatMessage]`) -- Model that will generate the agent's actions.
- **prompt_templates** ([PromptTemplates](/docs/smolagents/main/ko/reference/agents#smolagents.PromptTemplates), *optional*) -- Prompt templates.
- **instructions** (`str`, *optional*) -- Custom instructions for the agent, will be inserted in the system prompt.
- **max_steps** (`int`, default `20`) -- Maximum number of steps the agent can take to solve the task.
- **add_base_tools** (`bool`, default `False`) -- Whether to add the base tools to the agent's tools.
- **verbosity_level** (`LogLevel`, default `LogLevel.INFO`) -- Level of verbosity of the agent's logs.
- **managed_agents** (`list`, *optional*) -- Managed agents that the agent can call.
- **step_callbacks** (`list[Callable]` | `dict[Type[MemoryStep], Callable | list[Callable]]`, *optional*) -- Callbacks that will be called at each step.
- **planning_interval** (`int`, *optional*) -- Interval at which the agent will run a planning step.
- **name** (`str`, *optional*) -- Necessary for a managed agent only - the name by which this agent can be called.
- **description** (`str`, *optional*) -- Necessary for a managed agent only - the description of this agent.
- **provide_run_summary** (`bool`, *optional*) -- Whether to provide a run summary when called as a managed agent.
- **final_answer_checks** (`list[Callable]`, *optional*) -- List of validation functions to run before accepting a final answer.
  Each function should:
  - Take the final answer, the agent's memory, and the agent itself as arguments.
  - Return a boolean indicating whether the final answer is valid.
- **return_full_result** (`bool`, default `False`) -- Whether to return the full `RunResult` object or just the final answer output from the agent run.</paramsdesc><paramgroups>0</paramgroups></docstring>

Agent class that solves the given task step by step, using the ReAct framework:
While the objective is not reached, the agent will perform a cycle of action (given by the LLM) and observation (obtained from the environment).





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>extract_action</name><anchor>smolagents.MultiStepAgent.extract_action</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L783</source><parameters>[{"name": "model_output", "val": ": str"}, {"name": "split_token", "val": ": str"}]</parameters><paramsdesc>- **model_output** (`str`) -- Output of the LLM
- **split_token** (`str`) -- Separator for the action. Should match the example in the system prompt.</paramsdesc><paramgroups>0</paramgroups></docstring>

Parse action from the LLM output




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_dict</name><anchor>smolagents.MultiStepAgent.from_dict</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L1004</source><parameters>[{"name": "agent_dict", "val": ": dict"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **agent_dict** (`dict[str, Any]`) -- Dictionary representation of the agent.
- ****kwargs** -- Additional keyword arguments that will override agent_dict values.</paramsdesc><paramgroups>0</paramgroups><rettype>`MultiStepAgent`</rettype><retdesc>Instance of the agent class.</retdesc></docstring>
Create agent from a dictionary representation.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_folder</name><anchor>smolagents.MultiStepAgent.from_folder</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L1102</source><parameters>[{"name": "folder", "val": ": str | pathlib.Path"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **folder** (`str` or `Path`) -- The folder where the agent is saved.
- ****kwargs** -- Additional keyword arguments that will be passed to the agent's init.</paramsdesc><paramgroups>0</paramgroups></docstring>
Loads an agent from a local folder.




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_hub</name><anchor>smolagents.MultiStepAgent.from_hub</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L1048</source><parameters>[{"name": "repo_id", "val": ": str"}, {"name": "token", "val": ": str | None = None"}, {"name": "trust_remote_code", "val": ": bool = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **repo_id** (`str`) --
  The name of the repo on the Hub where your tool is defined.
- **token** (`str`, *optional*) --
  The token to identify you on hf.co. If unset, will use the token generated when running
  `huggingface-cli login` (stored in `~/.huggingface`).
- **trust_remote_code(`bool`,** *optional*, defaults to False) --
  This flags marks that you understand the risk of running remote code and that you trust this tool.
  If not setting this to True, loading the tool from Hub will fail.
- **kwargs** (additional keyword arguments, *optional*) --
  Additional keyword arguments that will be split in two: all arguments relevant to the Hub (such as
  `cache_dir`, `revision`, `subfolder`) will be used when downloading the files for your agent, and the
  others will be passed along to its init.</paramsdesc><paramgroups>0</paramgroups></docstring>

Loads an agent defined on the Hub.

<Tip warning={true}>

Loading a tool from the Hub means that you'll download the tool and execute it locally.
ALWAYS inspect the tool you're downloading before loading it within your runtime, as you would do when
installing a package using pip/npm/apt.

</Tip>




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>initialize_system_prompt</name><anchor>smolagents.MultiStepAgent.initialize_system_prompt</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L743</source><parameters>[]</parameters></docstring>
To be implemented in child classes

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>interrupt</name><anchor>smolagents.MultiStepAgent.interrupt</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L748</source><parameters>[]</parameters></docstring>
Interrupts the agent execution.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>provide_final_answer</name><anchor>smolagents.MultiStepAgent.provide_final_answer</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L804</source><parameters>[{"name": "task", "val": ": str"}]</parameters><paramsdesc>- **task** (`str`) -- Task to perform.
- **images** (`list[PIL.Image.Image]`, *optional*) -- Image(s) objects.</paramsdesc><paramgroups>0</paramgroups><rettype>`str`</rettype><retdesc>Final answer to the task.</retdesc></docstring>

Provide the final answer to the task, based on the logs of the agent's interactions.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>push_to_hub</name><anchor>smolagents.MultiStepAgent.push_to_hub</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L1134</source><parameters>[{"name": "repo_id", "val": ": str"}, {"name": "commit_message", "val": ": str = 'Upload agent'"}, {"name": "private", "val": ": bool | None = None"}, {"name": "token", "val": ": bool | str | None = None"}, {"name": "create_pr", "val": ": bool = False"}]</parameters><paramsdesc>- **repo_id** (`str`) --
  The name of the repository you want to push to. It should contain your organization name when
  pushing to a given organization.
- **commit_message** (`str`, *optional*, defaults to `"Upload agent"`) --
  Message to commit while pushing.
- **private** (`bool`, *optional*, defaults to `None`) --
  Whether to make the repo private. If `None`, the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
- **token** (`bool` or `str`, *optional*) --
  The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated
  when running `huggingface-cli login` (stored in `~/.huggingface`).
- **create_pr** (`bool`, *optional*, defaults to `False`) --
  Whether to create a PR with the uploaded files or directly commit.</paramsdesc><paramgroups>0</paramgroups></docstring>

Upload the agent to the Hub.




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>replay</name><anchor>smolagents.MultiStepAgent.replay</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L853</source><parameters>[{"name": "detailed", "val": ": bool = False"}]</parameters><paramsdesc>- **detailed** (bool, optional) -- If True, also displays the memory at each step. Defaults to False.
  Careful: will increase log length exponentially. Use only for debugging.</paramsdesc><paramgroups>0</paramgroups></docstring>
Prints a pretty replay of the agent's steps.




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>run</name><anchor>smolagents.MultiStepAgent.run</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L433</source><parameters>[{"name": "task", "val": ": str"}, {"name": "stream", "val": ": bool = False"}, {"name": "reset", "val": ": bool = True"}, {"name": "images", "val": ": list['PIL.Image.Image'] | None = None"}, {"name": "additional_args", "val": ": dict | None = None"}, {"name": "max_steps", "val": ": int | None = None"}, {"name": "return_full_result", "val": ": bool | None = None"}]</parameters><paramsdesc>- **task** (`str`) -- Task to perform.
- **stream** (`bool`) -- Whether to run in streaming mode.
  If `True`, returns a generator that yields each step as it is executed. You must iterate over this generator to process the individual steps (e.g., using a for loop or `next()`).
  If `False`, executes all steps internally and returns only the final answer after completion.
- **reset** (`bool`) -- Whether to reset the conversation or keep it going from previous run.
- **images** (`list[PIL.Image.Image]`, *optional*) -- Image(s) objects.
- **additional_args** (`dict`, *optional*) -- Any other variables that you want to pass to the agent run, for instance images or dataframes. Give them clear names!
- **max_steps** (`int`, *optional*) -- Maximum number of steps the agent can take to solve the task. if not provided, will use the agent's default value.
- **return_full_result** (`bool`, *optional*) -- Whether to return the full `RunResult` object or just the final answer output.
  If `None` (default), the agent's `self.return_full_result` setting is used.</paramsdesc><paramgroups>0</paramgroups></docstring>

Run the agent for the given task.



<ExampleCodeBlock anchor="smolagents.MultiStepAgent.run.example">

Example:
```py
from smolagents import CodeAgent
agent = CodeAgent(tools=[])
agent.run("What is the result of 2 power 3.7384?")
```

</ExampleCodeBlock>


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>save</name><anchor>smolagents.MultiStepAgent.save</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L886</source><parameters>[{"name": "output_dir", "val": ": str | pathlib.Path"}, {"name": "relative_path", "val": ": str | None = None"}]</parameters><paramsdesc>- **output_dir** (`str` or `Path`) -- The folder in which you want to save your agent.</paramsdesc><paramgroups>0</paramgroups></docstring>

Saves the relevant code files for your agent. This will copy the code of your agent in `output_dir` as well as autogenerate:

- a `tools` folder containing the logic for each of the tools under `tools/{tool_name}.py`.
- a `managed_agents` folder containing the logic for each of the managed agents.
- an `agent.json` file containing a dictionary representing your agent.
- a `prompt.yaml` file containing the prompt templates used by your agent.
- an `app.py` file providing a UI for your agent when it is exported to a Space with `agent.push_to_hub()`
- a `requirements.txt` containing the names of the modules used by your tool (as detected when inspecting its
  code)




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>step</name><anchor>smolagents.MultiStepAgent.step</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L776</source><parameters>[{"name": "memory_step", "val": ": ActionStep"}]</parameters></docstring>

Perform one step in the ReAct framework: the agent thinks, acts, and observes the result.
Returns either None if the step is not final, or the final answer.


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>to_dict</name><anchor>smolagents.MultiStepAgent.to_dict</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L964</source><parameters>[]</parameters><rettype>`dict`</rettype><retdesc>Dictionary representation of the agent.</retdesc></docstring>
Convert the agent to a dictionary representation.






</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>visualize</name><anchor>smolagents.MultiStepAgent.visualize</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L849</source><parameters>[]</parameters></docstring>
Creates a rich tree visualization of the agent's structure.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>write_memory_to_messages</name><anchor>smolagents.MultiStepAgent.write_memory_to_messages</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L752</source><parameters>[{"name": "summary_mode", "val": ": bool = False"}]</parameters></docstring>

Reads past llm_outputs, actions, and observations or errors from the memory into a series of messages
that can be used as input to the LLM. Adds a number of keywords (such as PLAN, error, etc) to help
the LLM.


</div></div>

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.CodeAgent</name><anchor>smolagents.CodeAgent</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L1478</source><parameters>[{"name": "tools", "val": ": list"}, {"name": "model", "val": ": Model"}, {"name": "prompt_templates", "val": ": smolagents.agents.PromptTemplates | None = None"}, {"name": "additional_authorized_imports", "val": ": list[str] | None = None"}, {"name": "planning_interval", "val": ": int | None = None"}, {"name": "executor", "val": ": PythonExecutor = None"}, {"name": "executor_type", "val": ": typing.Literal['local', 'e2b', 'modal', 'docker', 'wasm'] = 'local'"}, {"name": "executor_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "max_print_outputs_length", "val": ": int | None = None"}, {"name": "stream_outputs", "val": ": bool = False"}, {"name": "use_structured_outputs_internally", "val": ": bool = False"}, {"name": "code_block_tags", "val": ": str | tuple[str, str] | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **tools** (`list[Tool]`) -- `Tool`s that the agent can use.
- **model** (`Model`) -- Model that will generate the agent's actions.
- **prompt_templates** ([PromptTemplates](/docs/smolagents/main/ko/reference/agents#smolagents.PromptTemplates), *optional*) -- Prompt templates.
- **additional_authorized_imports** (`list[str]`, *optional*) -- Additional authorized imports for the agent.
- **planning_interval** (`int`, *optional*) -- Interval at which the agent will run a planning step.
- **executor** ([PythonExecutor](/docs/smolagents/main/ko/reference/agents#smolagents.PythonExecutor), *optional*) -- Custom Python code executor. If not provided, a default executor will be created based on `executor_type`.
- **executor_type** (`Literal["local", "e2b", "modal", "docker", "wasm"]`, default `"local"`) -- Type of code executor.
- **executor_kwargs** (`dict`, *optional*) -- Additional arguments to pass to initialize the executor.
- **max_print_outputs_length** (`int`, *optional*) -- Maximum length of the print outputs.
- **stream_outputs** (`bool`, *optional*, default `False`) -- Whether to stream outputs during execution.
- **use_structured_outputs_internally** (`bool`, default `False`) -- Whether to use structured generation at each action step: improves performance for many models.

  <Added version="1.17.0"/>
- **code_block_tags** (`tuple[str, str]` | `Literal["markdown"]`, *optional*) -- Opening and closing tags for code blocks (regex strings). Pass a custom tuple, or pass 'markdown' to use ("```(?:python|py)", "\n```"), leave empty to use ("<code>", "</code>").
- ****kwargs** -- Additional keyword arguments.</paramsdesc><paramgroups>0</paramgroups></docstring>

In this agent, the tool calls will be formulated by the LLM in code format, then parsed and executed.





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>cleanup</name><anchor>smolagents.CodeAgent.cleanup</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L1566</source><parameters>[]</parameters></docstring>
Clean up resources used by the agent, such as the remote Python executor.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_dict</name><anchor>smolagents.CodeAgent.from_dict</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L1752</source><parameters>[{"name": "agent_dict", "val": ": dict"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **agent_dict** (`dict[str, Any]`) -- Dictionary representation of the agent.
- ****kwargs** -- Additional keyword arguments that will override agent_dict values.</paramsdesc><paramgroups>0</paramgroups><rettype>`CodeAgent`</rettype><retdesc>Instance of the CodeAgent class.</retdesc></docstring>
Create CodeAgent from a dictionary representation.








</div></div>

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.ToolCallingAgent</name><anchor>smolagents.ToolCallingAgent</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L1189</source><parameters>[{"name": "tools", "val": ": list"}, {"name": "model", "val": ": Model"}, {"name": "prompt_templates", "val": ": smolagents.agents.PromptTemplates | None = None"}, {"name": "planning_interval", "val": ": int | None = None"}, {"name": "stream_outputs", "val": ": bool = False"}, {"name": "max_tool_threads", "val": ": int | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **tools** (`list[Tool]`) -- `Tool`s that the agent can use.
- **model** (`Model`) -- Model that will generate the agent's actions.
- **prompt_templates** ([PromptTemplates](/docs/smolagents/main/ko/reference/agents#smolagents.PromptTemplates), *optional*) -- Prompt templates.
- **planning_interval** (`int`, *optional*) -- Interval at which the agent will run a planning step.
- **stream_outputs** (`bool`, *optional*, default `False`) -- Whether to stream outputs during execution.
- **max_tool_threads** (`int`, *optional*) -- Maximum number of threads for parallel tool calls.
  Higher values increase concurrency but resource usage as well.
  Defaults to `ThreadPoolExecutor`'s default.
- ****kwargs** -- Additional keyword arguments.</paramsdesc><paramgroups>0</paramgroups></docstring>

This agent uses JSON-like tool calls, using method `model.get_tool_call` to leverage the LLM engine's tool calling capabilities.





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>execute_tool_call</name><anchor>smolagents.ToolCallingAgent.execute_tool_call</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L1426</source><parameters>[{"name": "tool_name", "val": ": str"}, {"name": "arguments", "val": ": dict[str, str] | str"}]</parameters><paramsdesc>- **tool_name** (`str`) -- Name of the tool or managed agent to execute.
- **arguments** (dict[str, str] | str) -- Arguments passed to the tool call.</paramsdesc><paramgroups>0</paramgroups></docstring>

Execute a tool or managed agent with the provided arguments.

The arguments are replaced with the actual values from the state if they refer to state variables.




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>process_tool_calls</name><anchor>smolagents.ToolCallingAgent.process_tool_calls</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L1335</source><parameters>[{"name": "chat_message", "val": ": ChatMessage"}, {"name": "memory_step", "val": ": ActionStep"}]</parameters><paramsdesc>- **chat_message** (`ChatMessage`) -- Chat message containing tool calls from the model.
- **memory_step** (`ActionStep)` -- Memory ActionStep to update with results.</paramsdesc><paramgroups>0</paramgroups><yieldtype>`ToolCall | ToolOutput`</yieldtype><yielddesc>The tool call or tool output.</yielddesc></docstring>
Process tool calls from the model output and update agent memory.








</div></div>

### stream_to_gradio[[smolagents.stream_to_gradio]][[smolagents.stream_to_gradio]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>smolagents.stream_to_gradio</name><anchor>smolagents.stream_to_gradio</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/gradio_ui.py#L248</source><parameters>[{"name": "agent", "val": ""}, {"name": "task", "val": ": str"}, {"name": "task_images", "val": ": list | None = None"}, {"name": "reset_agent_memory", "val": ": bool = False"}, {"name": "additional_args", "val": ": dict | None = None"}]</parameters></docstring>
Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages.

</div>

### GradioUI[[smolagents.GradioUI]][[smolagents.GradioUI]]

> [!TIP]
> UI를 사용하려면 `gradio`가 설치되어 있어야 합니다. 설치되어 있지 않다면 `pip install 'smolagents[gradio]'`를 실행해주세요.

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.GradioUI</name><anchor>smolagents.GradioUI</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/gradio_ui.py#L279</source><parameters>[{"name": "agent", "val": ": MultiStepAgent"}, {"name": "file_upload_folder", "val": ": str | None = None"}, {"name": "reset_agent_memory", "val": ": bool = False"}]</parameters><paramsdesc>- **agent** ([MultiStepAgent](/docs/smolagents/main/ko/reference/agents#smolagents.MultiStepAgent)) -- The agent to interact with.
- **file_upload_folder** (`str`, *optional*) -- The folder where uploaded files will be saved.
  If not provided, file uploads are disabled.
- **reset_agent_memory** (`bool`, *optional*, defaults to `False`) -- Whether to reset the agent's memory at the start of each interaction.
  If `True`, the agent will not remember previous interactions.</paramsdesc><paramgroups>0</paramgroups><raises>- ``ModuleNotFoundError`` -- If the `gradio` extra is not installed.</raises><raisederrors>``ModuleNotFoundError``</raisederrors></docstring>

Gradio interface for interacting with a [MultiStepAgent](/docs/smolagents/main/ko/reference/agents#smolagents.MultiStepAgent).

This class provides a web interface to interact with the agent in real-time, allowing users to submit prompts, upload files, and receive responses in a chat-like format.
It  can reset the agent's memory at the start of each interaction if desired.
It supports file uploads, which are saved to a specified folder.
It uses the `gradio.Chatbot` component to display the conversation history.
This class requires the `gradio` extra to be installed: `pip install 'smolagents[gradio]'`.







<ExampleCodeBlock anchor="smolagents.GradioUI.example">

Example:
```python
from smolagents import CodeAgent, GradioUI, InferenceClientModel

model = InferenceClientModel(model_id="meta-llama/Meta-Llama-3.1-8B-Instruct")
agent = CodeAgent(tools=[], model=model)
gradio_ui = GradioUI(agent, file_upload_folder="uploads", reset_agent_memory=True)
gradio_ui.launch()
```

</ExampleCodeBlock>



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>launch</name><anchor>smolagents.GradioUI.launch</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/gradio_ui.py#L406</source><parameters>[{"name": "share", "val": ": bool = True"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **share** (`bool`, defaults to `True`) -- Whether to share the app publicly.
- ****kwargs** -- Additional keyword arguments to pass to the Gradio launch method.</paramsdesc><paramgroups>0</paramgroups></docstring>

Launch the Gradio app with the agent interface.




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>upload_file</name><anchor>smolagents.GradioUI.upload_file</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/gradio_ui.py#L356</source><parameters>[{"name": "file", "val": ""}, {"name": "file_uploads_log", "val": ""}, {"name": "allowed_file_types", "val": " = None"}]</parameters><paramsdesc>- **file** (`gradio.File`) -- The uploaded file.
- **file_uploads_log** (`list`) -- A list to log uploaded files.
- **allowed_file_types** (`list`, *optional*) -- List of allowed file extensions. Defaults to [".pdf", ".docx", ".txt"].</paramsdesc><paramgroups>0</paramgroups></docstring>

Upload a file and add it to the list of uploaded files in the session state.

The file is saved to the `self.file_upload_folder` folder.
If the file type is not allowed, it returns a message indicating the disallowed file type.




</div></div>

## 프롬프트[[smolagents.PromptTemplates]][[smolagents.PromptTemplates]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.PromptTemplates</name><anchor>smolagents.PromptTemplates</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L164</source><parameters>""</parameters><paramsdesc>- **system_prompt** (`str`) -- System prompt.
- **planning** ([PlanningPromptTemplate](/docs/smolagents/main/ko/reference/agents#smolagents.PlanningPromptTemplate)) -- Planning prompt templates.
- **managed_agent** ([ManagedAgentPromptTemplate](/docs/smolagents/main/ko/reference/agents#smolagents.ManagedAgentPromptTemplate)) -- Managed agent prompt templates.
- **final_answer** ([FinalAnswerPromptTemplate](/docs/smolagents/main/ko/reference/agents#smolagents.FinalAnswerPromptTemplate)) -- Final answer prompt templates.</paramsdesc><paramgroups>0</paramgroups></docstring>

Prompt templates for the agent.




</div>

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.PlanningPromptTemplate</name><anchor>smolagents.PlanningPromptTemplate</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L123</source><parameters>""</parameters><paramsdesc>- **plan** (`str`) -- Initial plan prompt.
- **update_plan_pre_messages** (`str`) -- Update plan pre-messages prompt.
- **update_plan_post_messages** (`str`) -- Update plan post-messages prompt.</paramsdesc><paramgroups>0</paramgroups></docstring>

Prompt templates for the planning step.




</div>

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.ManagedAgentPromptTemplate</name><anchor>smolagents.ManagedAgentPromptTemplate</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L138</source><parameters>""</parameters><paramsdesc>- **task** (`str`) -- Task prompt.
- **report** (`str`) -- Report prompt.</paramsdesc><paramgroups>0</paramgroups></docstring>

Prompt templates for the managed agent.




</div>

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.FinalAnswerPromptTemplate</name><anchor>smolagents.FinalAnswerPromptTemplate</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py#L151</source><parameters>""</parameters><paramsdesc>- **pre_messages** (`str`) -- Pre-messages prompt.
- **post_messages** (`str`) -- Post-messages prompt.</paramsdesc><paramgroups>0</paramgroups></docstring>

Prompt templates for the final answer.




</div>

## 메모리[[smolagents.AgentMemory]][[smolagents.AgentMemory]]

Smolagents는 여러 단계에 걸쳐 정보를 저장하기 위해 메모리를 사용합니다.

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.AgentMemory</name><anchor>smolagents.AgentMemory</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/memory.py#L214</source><parameters>[{"name": "system_prompt", "val": ": str"}]</parameters><paramsdesc>- **system_prompt** (`str`) -- System prompt for the agent, which sets the context and instructions for the agent's behavior.</paramsdesc><paramgroups>0</paramgroups></docstring>
Memory for the agent, containing the system prompt and all steps taken by the agent.

This class is used to store the agent's steps, including tasks, actions, and planning steps.
It allows for resetting the memory, retrieving succinct or full step information, and replaying the agent's steps.



**Attributes**:
- **system_prompt** (`SystemPromptStep`) -- System prompt step for the agent.
- **steps** (`list[TaskStep | ActionStep | PlanningStep]`) -- List of steps taken by the agent, which can include tasks, actions, and planning steps.



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>get_full_steps</name><anchor>smolagents.AgentMemory.get_full_steps</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/memory.py#L242</source><parameters>[]</parameters></docstring>
Return a full representation of the agent's steps, including model input messages.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>get_succinct_steps</name><anchor>smolagents.AgentMemory.get_succinct_steps</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/memory.py#L236</source><parameters>[]</parameters></docstring>
Return a succinct representation of the agent's steps, excluding model input messages.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>replay</name><anchor>smolagents.AgentMemory.replay</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/memory.py#L248</source><parameters>[{"name": "logger", "val": ": AgentLogger"}, {"name": "detailed", "val": ": bool = False"}]</parameters><paramsdesc>- **logger** (`AgentLogger`) -- The logger to print replay logs to.
- **detailed** (`bool`, default `False`) -- If True, also displays the memory at each step. Defaults to False.
  Careful: will increase log length exponentially. Use only for debugging.</paramsdesc><paramgroups>0</paramgroups></docstring>
Prints a pretty replay of the agent's steps.




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>reset</name><anchor>smolagents.AgentMemory.reset</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/memory.py#L232</source><parameters>[]</parameters></docstring>
Reset the agent's memory, clearing all steps and keeping the system prompt.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>return_full_code</name><anchor>smolagents.AgentMemory.return_full_code</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/memory.py#L273</source><parameters>[]</parameters></docstring>
Returns all code actions from the agent's steps, concatenated as a single script.

</div></div>

## Python 코드 실행기[[smolagents.PythonExecutor]][[smolagents.PythonExecutor]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.PythonExecutor</name><anchor>smolagents.PythonExecutor</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/local_python_executor.py#L1608</source><parameters>[]</parameters></docstring>


</div>

### 로컬 Python 실행기[[smolagents.LocalPythonExecutor]][[smolagents.LocalPythonExecutor]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.LocalPythonExecutor</name><anchor>smolagents.LocalPythonExecutor</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/local_python_executor.py#L1619</source><parameters>[{"name": "additional_authorized_imports", "val": ": list"}, {"name": "max_print_outputs_length", "val": ": int | None = None"}, {"name": "additional_functions", "val": ": dict[str, collections.abc.Callable] | None = None"}]</parameters><paramsdesc>- **additional_authorized_imports** (`list[str]`) --
  Additional authorized imports for the executor.
- **max_print_outputs_length** (`int`, defaults to `DEFAULT_MAX_LEN_OUTPUT=50_000`) --
  Maximum length of the print outputs.
- **additional_functions** (`dict[str, Callable]`, *optional*) --
  Additional Python functions to be added to the executor.</paramsdesc><paramgroups>0</paramgroups></docstring>

Executor of Python code in a local environment.

This executor evaluates Python code with restricted access to imports and built-in functions,
making it suitable for running untrusted code. It maintains state between executions,
allows for custom tools and functions to be made available to the code, and captures
print outputs separately from return values.




</div>

### 원격 Python 실행기[[smolagents.remote_executors.RemotePythonExecutor]][[smolagents.remote_executors.RemotePythonExecutor]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.remote_executors.RemotePythonExecutor</name><anchor>smolagents.remote_executors.RemotePythonExecutor</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/remote_executors.py#L54</source><parameters>[{"name": "additional_imports", "val": ": list"}, {"name": "logger", "val": ""}]</parameters></docstring>



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>run_code_raise_errors</name><anchor>smolagents.remote_executors.RemotePythonExecutor.run_code_raise_errors</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/remote_executors.py#L63</source><parameters>[{"name": "code", "val": ": str"}]</parameters></docstring>

Execute code, return the result and output, also determining if
the result is the final answer.


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>send_variables</name><anchor>smolagents.remote_executors.RemotePythonExecutor.send_variables</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/remote_executors.py#L88</source><parameters>[{"name": "variables", "val": ": dict"}]</parameters></docstring>

Send variables to the kernel namespace using pickle.


</div></div>

#### E2BExecutor[[smolagents.E2BExecutor]][[smolagents.E2BExecutor]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.E2BExecutor</name><anchor>smolagents.E2BExecutor</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/remote_executors.py#L158</source><parameters>[{"name": "additional_imports", "val": ": list"}, {"name": "logger", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **additional_imports** (`list[str]`) -- Additional imports to install.
- **logger** (`Logger`) -- Logger to use.
- ****kwargs** -- Additional arguments to pass to the E2B Sandbox.</paramsdesc><paramgroups>0</paramgroups></docstring>

Executes Python code using E2B.





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>cleanup</name><anchor>smolagents.E2BExecutor.cleanup</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/remote_executors.py#L240</source><parameters>[]</parameters></docstring>
Clean up the E2B sandbox and resources.

</div></div>

#### DockerExecutor[[smolagents.DockerExecutor]][[smolagents.DockerExecutor]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.DockerExecutor</name><anchor>smolagents.DockerExecutor</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/remote_executors.py#L341</source><parameters>[{"name": "additional_imports", "val": ": list"}, {"name": "logger", "val": ""}, {"name": "host", "val": ": str = '127.0.0.1'"}, {"name": "port", "val": ": int = 8888"}, {"name": "image_name", "val": ": str = 'jupyter-kernel'"}, {"name": "build_new_image", "val": ": bool = True"}, {"name": "container_run_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "dockerfile_content", "val": ": str | None = None"}]</parameters></docstring>

Executes Python code using Jupyter Kernel Gateway in a Docker container.



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>cleanup</name><anchor>smolagents.DockerExecutor.cleanup</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/remote_executors.py#L463</source><parameters>[]</parameters></docstring>
Clean up the Docker container and resources.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>delete</name><anchor>smolagents.DockerExecutor.delete</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/remote_executors.py#L475</source><parameters>[]</parameters></docstring>
Ensure cleanup on deletion.

</div></div>

#### WasmExecutor[[smolagents.WasmExecutor]][[smolagents.WasmExecutor]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.WasmExecutor</name><anchor>smolagents.WasmExecutor</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/remote_executors.py#L612</source><parameters>[{"name": "additional_imports", "val": ": list"}, {"name": "logger", "val": ""}, {"name": "deno_path", "val": ": str = 'deno'"}, {"name": "deno_permissions", "val": ": list[str] | None = None"}, {"name": "timeout", "val": ": int = 60"}]</parameters><paramsdesc>- **additional_imports** (`list[str]`) -- Additional Python packages to install in the Pyodide environment.
- **logger** (`Logger`) -- Logger to use for output and errors.
- **deno_path** (`str`, optional) -- Path to the Deno executable. If not provided, will use "deno" from PATH.
- **deno_permissions** (`list[str]`, optional) -- List of permissions to grant to the Deno runtime.
  Default is minimal permissions needed for execution.
- **timeout** (`int`, optional) -- Timeout in seconds for code execution. Default is 60 seconds.</paramsdesc><paramgroups>0</paramgroups></docstring>

Remote Python code executor in a sandboxed WebAssembly environment powered by Pyodide and Deno.

This executor combines Deno's secure runtime with Pyodide's WebAssembly‑compiled Python interpreter to deliver s
trong isolation guarantees while enabling full Python execution.





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>cleanup</name><anchor>smolagents.WasmExecutor.cleanup</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/remote_executors.py#L793</source><parameters>[]</parameters></docstring>
Clean up resources used by the executor.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>delete</name><anchor>smolagents.WasmExecutor.delete</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/remote_executors.py#L809</source><parameters>[]</parameters></docstring>
Ensure cleanup on deletion.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>install_packages</name><anchor>smolagents.WasmExecutor.install_packages</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/remote_executors.py#L777</source><parameters>[{"name": "additional_imports", "val": ": list"}]</parameters><paramsdesc>- **additional_imports** (`list[str]`) -- Package names to install.</paramsdesc><paramgroups>0</paramgroups><rettype>list[str]</rettype><retdesc>Installed packages.</retdesc></docstring>

Install additional Python packages in the Pyodide environment.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>run_code_raise_errors</name><anchor>smolagents.WasmExecutor.run_code_raise_errors</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/remote_executors.py#L716</source><parameters>[{"name": "code", "val": ": str"}]</parameters><paramsdesc>- **code** (`str`) -- Python code to execute.</paramsdesc><paramgroups>0</paramgroups><rettype>`CodeOutput`</rettype><retdesc>Code output containing the result, logs, and whether it is the final answer.</retdesc></docstring>

Execute Python code in the Pyodide environment and return the result.








</div></div>

<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/reference/agents.md" />

### 모델[[models]]
https://huggingface.co/docs/smolagents/main/ko/reference/models.md

# 모델[[models]]

<Tip warning={true}>

Smolagents는 언제든지 변경될 수 있는 실험적인 API입니다. API 또는 기반 모델이 바뀌면 에이전트가 반환하는 결과도 달라질 수 있습니다.

</Tip>

에이전트와 도구에 대한 자세한 내용은 꼭 [소개 가이드](../index)를 읽어보시기 바랍니다. 이 페이지는 기반 클래스에 대한 API 문서를 포함하고 있습니다.

## 모델[[models]]

smolagents의 모든 모델 클래스는 추가 키워드 인수(`temperature`, `max_tokens`, `top_p` 등)를 인스턴스화 시점에 바로 전달할 수 있습니다.
이 파라미터들은 기반 모델의 생성 호출에 자동으로 전달되어, 창의성, 응답 길이, 샘플링 전략과 같은 모델의 동작을 설정할 수 있습니다.

### 기본 모델[[smolagents.Model]][[smolagents.Model]]

`Model` 클래스는 모든 모델 구현의 기반이 되는 클래스이며, 사용자 정의 모델이 에이전트와 함께 작동하기 위해 구현해야 하는 핵심 인터페이스를 제공합니다.

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.Model</name><anchor>smolagents.Model</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L393</source><parameters>[{"name": "flatten_messages_as_text", "val": ": bool = False"}, {"name": "tool_name_key", "val": ": str = 'name'"}, {"name": "tool_arguments_key", "val": ": str = 'arguments'"}, {"name": "model_id", "val": ": str | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **flatten_messages_as_text** (`bool`, default `False`) --
  Whether to flatten complex message content into plain text format.
- **tool_name_key** (`str`, default `"name"`) --
  The key used to extract tool names from model responses.
- **tool_arguments_key** (`str`, default `"arguments"`) --
  The key used to extract tool arguments from model responses.
- **model_id** (`str`, *optional*) --
  Identifier for the specific model being used.
- ****kwargs** --
  Additional keyword arguments to forward to the underlying model completion call.</paramsdesc><paramgroups>0</paramgroups></docstring>
Base class for all language model implementations.

This abstract class defines the core interface that all model implementations must follow
to work with agents. It provides common functionality for message handling, tool integration,
and model configuration while allowing subclasses to implement their specific generation logic.



Note:
This is an abstract base class. Subclasses must implement the `generate()` method
to provide actual model inference capabilities.

<ExampleCodeBlock anchor="smolagents.Model.example">

Example:
```python
class CustomModel(Model):
    def generate(self, messages, **kwargs):
        # Implementation specific to your model
        pass
```

</ExampleCodeBlock>



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>generate</name><anchor>smolagents.Model.generate</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L494</source><parameters>[{"name": "messages", "val": ": list"}, {"name": "stop_sequences", "val": ": list[str] | None = None"}, {"name": "response_format", "val": ": dict[str, str] | None = None"}, {"name": "tools_to_call_from", "val": ": list[smolagents.tools.Tool] | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **messages** (`list[dict[str, str | list[dict]]] | list[ChatMessage]`) --
  A list of message dictionaries to be processed. Each dictionary should have the structure `{"role": "user/system", "content": "message content"}`.
- **stop_sequences** (`List[str]`, *optional*) --
  A list of strings that will stop the generation if encountered in the model's output.
- **response_format** (`dict[str, str]`, *optional*) --
  The response format to use in the model's response.
- **tools_to_call_from** (`List[Tool]`, *optional*) --
  A list of tools that the model can use to generate responses.
- ****kwargs** --
  Additional keyword arguments to be passed to the underlying model.</paramsdesc><paramgroups>0</paramgroups><rettype>`ChatMessage`</rettype><retdesc>A chat message object containing the model's response.</retdesc></docstring>
Process the input messages and return the model's response.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>parse_tool_calls</name><anchor>smolagents.Model.parse_tool_calls</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L524</source><parameters>[{"name": "message", "val": ": ChatMessage"}]</parameters></docstring>
Sometimes APIs do not return the tool call as a specific object, so we need to parse it.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>to_dict</name><anchor>smolagents.Model.to_dict</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L537</source><parameters>[]</parameters></docstring>

Converts the model into a JSON-compatible dictionary.


</div></div>

### API 모델[[smolagents.ApiModel]][[smolagents.ApiModel]]

`ApiModel` 클래스는 모든 API 기반 모델 구현의 토대가 되며, 외부 API 상호 작용, 속도 제한, 클라이언트 관리 등 모델이 상속하는 공통 기능을 제공합니다.

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.ApiModel</name><anchor>smolagents.ApiModel</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L1066</source><parameters>[{"name": "model_id", "val": ": str"}, {"name": "custom_role_conversions", "val": ": dict[str, str] | None = None"}, {"name": "client", "val": ": typing.Optional[typing.Any] = None"}, {"name": "requests_per_minute", "val": ": float | None = None"}, {"name": "retry", "val": ": bool = True"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **model_id** (`str`) --
  The identifier for the model to be used with the API.
- **custom_role_conversions** (`dict[str, str`], **optional**) --
  Mapping to convert  between internal role names and API-specific role names. Defaults to None.
- **client** (`Any`, **optional**) --
  Pre-configured API client instance. If not provided, a default client will be created. Defaults to None.
- **requests_per_minute** (`float`, **optional**) --
  Rate limit in requests per minute.
- **retry** (`bool`, **optional**) --
  Wether to retry on rate limit errors, up to RETRY_MAX_ATTEMPTS times. Defaults to True.
- ****kwargs** --
  Additional keyword arguments to forward to the underlying model completion call.</paramsdesc><paramgroups>0</paramgroups></docstring>

Base class for API-based language models.

This class serves as a foundation for implementing models that interact with
external APIs. It handles the common functionality for managing model IDs,
custom role mappings, and API client connections.





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>create_client</name><anchor>smolagents.ApiModel.create_client</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L1111</source><parameters>[]</parameters></docstring>
Create the API client for the specific service.

</div></div>

### TransformersModel[[smolagents.TransformersModel]][[smolagents.TransformersModel]]

편의를 위해, 초기화 시 주어진 model_id에 대한 로컬 `transformers` 파이프라인을 구축하여 위 사항들을 구현하는 `TransformersModel`을 추가했습니다.

```python
from smolagents import TransformersModel

model = TransformersModel(model_id="HuggingFaceTB/SmolLM2-360M-Instruct")

print(model([{"role": "user", "content": [{"type": "text", "text": "좋아!"}]}], stop_sequences=["이"]))
```
```text
>>> 좋아! 아래와 같
```

기반 모델에서 지원하는 모든 키워드 인수(`temperature`, `max_new_tokens`, `top_p` 등)를 인스턴스화 시점에 직접 전달할 수 있습니다. 이들은 모델 생성 호출로 전달됩니다:

```python
model = TransformersModel(
    model_id="HuggingFaceTB/SmolLM2-360M-Instruct",
    temperature=0.7,
    max_new_tokens=1000
)
```

> [!TIP]
> 사용자의 컴퓨터에 `transformers`와 `torch`가 설치되어 있어야 합니다. 설치되지 않은 경우 `pip install 'smolagents[transformers]'`를 실행하십시오.

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.TransformersModel</name><anchor>smolagents.TransformersModel</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L793</source><parameters>[{"name": "model_id", "val": ": str | None = None"}, {"name": "device_map", "val": ": str | None = None"}, {"name": "torch_dtype", "val": ": str | None = None"}, {"name": "trust_remote_code", "val": ": bool = False"}, {"name": "model_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "max_new_tokens", "val": ": int = 4096"}, {"name": "max_tokens", "val": ": int | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **model_id** (`str`) --
  The Hugging Face model ID to be used for inference. This can be a path or model identifier from the Hugging Face model hub.
  For example, `"Qwen/Qwen3-Next-80B-A3B-Thinking"`.
- **device_map** (`str`, *optional*) --
  The device_map to initialize your model with.
- **torch_dtype** (`str`, *optional*) --
  The torch_dtype to initialize your model with.
- **trust_remote_code** (bool, default `False`) --
  Some models on the Hub require running remote code: for this model, you would have to set this flag to True.
- **model_kwargs** (`dict[str, Any]`, *optional*) --
  Additional keyword arguments to pass to `AutoModel.from_pretrained` (like revision, model_args, config, etc.).
- **max_new_tokens** (`int`, default `4096`) --
  Maximum number of new tokens to generate, ignoring the number of tokens in the prompt.
- **max_tokens** (`int`, *optional*) --
  Alias for `max_new_tokens`. If provided, this value takes precedence.
- ****kwargs** --
  Additional keyword arguments to forward to the underlying Transformers model generate call, such as `device`.</paramsdesc><paramgroups>0</paramgroups><raises>- ``ValueError`` -- 
  If the model name is not provided.</raises><raisederrors>``ValueError``</raisederrors></docstring>
A class that uses Hugging Face's Transformers library for language model interaction.

This model allows you to load and use Hugging Face's models locally using the Transformers library. It supports features like stop sequences and grammar customization.

> [!TIP]
> You must have `transformers` and `torch` installed on your machine. Please run `pip install 'smolagents[transformers]'` if it's not the case.







<ExampleCodeBlock anchor="smolagents.TransformersModel.example">

Example:
```python
>>> engine = TransformersModel(
...     model_id="Qwen/Qwen3-Next-80B-A3B-Thinking",
...     device="cuda",
...     max_new_tokens=5000,
... )
>>> messages = [{"role": "user", "content": "Explain quantum mechanics in simple terms."}]
>>> response = engine(messages, stop_sequences=["END"])
>>> print(response)
"Quantum mechanics is the branch of physics that studies..."
```

</ExampleCodeBlock>


</div>

### InferenceClientModel[[smolagents.InferenceClientModel]][[smolagents.InferenceClientModel]]

`InferenceClientModel`은 LLM 실행을 위해 huggingface_hub의 [InferenceClient](https://huggingface.co/docs/huggingface_hub/main/en/guides/inference)를 래핑합니다. 이는 Hub에서 사용할 수 있는 모든 [Inference Providers](https://huggingface.co/docs/inference-providers/index)를 지원합니다. Cerebras, Cohere, Fal, Fireworks, HF-Inference, Hyperbolic, Nebius, Novita, Replicate, SambaNova, Together 등이 있습니다.

또한 `requests_per_minute` 인수를 사용하여 분당 요청 수로 속도 제한을 설정할 수 있습니다:

```python
from smolagents import InferenceClientModel

messages = [
  {"role": "user", "content": [{"type": "text", "text": "안녕하세요, 잘 지내고 계신가요?"}]}
]

model = InferenceClientModel(provider="novita", requests_per_minute=60)
print(model(messages))
```
```text
>>> 안녕하세요. 덕분에 잘 지내고 있습니다.
```

기반 모델에서 지원하는 모든 키워드 인수(`temperature`, `max_tokens`, `top_p` 등)를 인스턴스화 시점에 직접 전달할 수 있습니다. 이들은 모델 생성 호출로 전달됩니다:

```python
model = InferenceClientModel(
    provider="novita",
    requests_per_minute=60,
    temperature=0.8,
    max_tokens=500
)
```

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.InferenceClientModel</name><anchor>smolagents.InferenceClientModel</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L1382</source><parameters>[{"name": "model_id", "val": ": str = 'Qwen/Qwen3-Next-80B-A3B-Thinking'"}, {"name": "provider", "val": ": str | None = None"}, {"name": "token", "val": ": str | None = None"}, {"name": "timeout", "val": ": int = 120"}, {"name": "client_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "custom_role_conversions", "val": ": dict[str, str] | None = None"}, {"name": "api_key", "val": ": str | None = None"}, {"name": "bill_to", "val": ": str | None = None"}, {"name": "base_url", "val": ": str | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **model_id** (`str`, *optional*, default `"Qwen/Qwen3-Next-80B-A3B-Thinking"`) --
  The Hugging Face model ID to be used for inference.
  This can be a model identifier from the Hugging Face model hub or a URL to a deployed Inference Endpoint.
  Currently, it defaults to `"Qwen/Qwen3-Next-80B-A3B-Thinking"`, but this may change in the future.
- **provider** (`str`, *optional*) --
  Name of the provider to use for inference. A list of supported providers can be found in the [Inference Providers documentation](https://huggingface.co/docs/inference-providers/index#partners).
  Defaults to "auto" i.e. the first of the providers available for the model, sorted by the user's order [here](https://hf.co/settings/inference-providers).
  If `base_url` is passed, then `provider` is not used.
- **token** (`str`, *optional*) --
  Token used by the Hugging Face API for authentication. This token need to be authorized 'Make calls to the serverless Inference Providers'.
  If the model is gated (like Llama-3 models), the token also needs 'Read access to contents of all public gated repos you can access'.
  If not provided, the class will try to use environment variable 'HF_TOKEN', else use the token stored in the Hugging Face CLI configuration.
- **timeout** (`int`, *optional*, defaults to 120) --
  Timeout for the API request, in seconds.
- **client_kwargs** (`dict[str, Any]`, *optional*) --
  Additional keyword arguments to pass to the Hugging Face InferenceClient.
- **custom_role_conversions** (`dict[str, str]`, *optional*) --
  Custom role conversion mapping to convert message roles in others.
  Useful for specific models that do not support specific message roles like "system".
- **api_key** (`str`, *optional*) --
  Token to use for authentication. This is a duplicated argument from `token` to make [InferenceClientModel](/docs/smolagents/main/ko/reference/models#smolagents.InferenceClientModel)
  follow the same pattern as `openai.OpenAI` client. Cannot be used if `token` is set. Defaults to None.
- **bill_to** (`str`, *optional*) --
  The billing account to use for the requests. By default the requests are billed on the user's account. Requests can only be billed to
  an organization the user is a member of, and which has subscribed to Enterprise Hub.
- **base_url** (`str`, `optional`) --
  Base URL to run inference. This is a duplicated argument from `model` to make [InferenceClientModel](/docs/smolagents/main/ko/reference/models#smolagents.InferenceClientModel)
  follow the same pattern as `openai.OpenAI` client. Cannot be used if `model` is set. Defaults to None.
- ****kwargs** --
  Additional keyword arguments to forward to the underlying Hugging Face InferenceClient completion call.</paramsdesc><paramgroups>0</paramgroups><raises>- ``ValueError`` -- 
  If the model name is not provided.</raises><raisederrors>``ValueError``</raisederrors></docstring>
A class to interact with Hugging Face's Inference Providers for language model interaction.

This model allows you to communicate with Hugging Face's models using Inference Providers. It can be used in both serverless mode, with a dedicated endpoint, or even with a local URL, supporting features like stop sequences and grammar customization.

Providers include Cerebras, Cohere, Fal, Fireworks, HF-Inference, Hyperbolic, Nebius, Novita, Replicate, SambaNova, Together, and more.







<ExampleCodeBlock anchor="smolagents.InferenceClientModel.example">

Example:
```python
>>> engine = InferenceClientModel(
...     model_id="Qwen/Qwen3-Next-80B-A3B-Thinking",
...     provider="hyperbolic",
...     token="your_hf_token_here",
...     max_tokens=5000,
... )
>>> messages = [{"role": "user", "content": "Explain quantum mechanics in simple terms."}]
>>> response = engine(messages, stop_sequences=["END"])
>>> print(response)
"Quantum mechanics is the branch of physics that studies..."
```

</ExampleCodeBlock>



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>create_client</name><anchor>smolagents.InferenceClientModel.create_client</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L1473</source><parameters>[]</parameters></docstring>
Create the Hugging Face client.

</div></div>

### LiteLLMModel[[smolagents.LiteLLMModel]][[smolagents.LiteLLMModel]]

`LiteLLMModel`은 [LiteLLM](https://www.litellm.ai/)을 활용하여 다양한 제공업체의 100개 이상의 LLM을 지원합니다.
모델 초기화 시 키워드 인수를 전달하면, 이후 모델을 사용할 때마다 해당 설정이 적용됩니다. 예를 들어 아래에서는 `temperature`를 전달합니다. 또한 `requests_per_minute` 인수를 통해 분당 요청 수를 제한할 수도 있습니다.

```python
from smolagents import LiteLLMModel

messages = [
  {"role": "user", "content": [{"type": "text", "text": "안녕하세요, 잘 지내고 계신가요?"}]}
]

model = LiteLLMModel(model_id="anthropic/claude-3-5-sonnet-latest", temperature=0.2, max_tokens=10, requests_per_minute=60)
print(model(messages))
```

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.LiteLLMModel</name><anchor>smolagents.LiteLLMModel</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L1131</source><parameters>[{"name": "model_id", "val": ": str | None = None"}, {"name": "api_base", "val": ": str | None = None"}, {"name": "api_key", "val": ": str | None = None"}, {"name": "custom_role_conversions", "val": ": dict[str, str] | None = None"}, {"name": "flatten_messages_as_text", "val": ": bool | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **model_id** (`str`) --
  The model identifier to use on the server (e.g. "gpt-3.5-turbo").
- **api_base** (`str`, *optional*) --
  The base URL of the provider API to call the model.
- **api_key** (`str`, *optional*) --
  The API key to use for authentication.
- **custom_role_conversions** (`dict[str, str]`, *optional*) --
  Custom role conversion mapping to convert message roles in others.
  Useful for specific models that do not support specific message roles like "system".
- **flatten_messages_as_text** (`bool`, *optional*) -- Whether to flatten messages as text.
  Defaults to `True` for models that start with "ollama", "groq", "cerebras".
- ****kwargs** --
  Additional keyword arguments to forward to the underlying LiteLLM completion call.</paramsdesc><paramgroups>0</paramgroups></docstring>
Model to use [LiteLLM Python SDK](https://docs.litellm.ai/docs/#litellm-python-sdk) to access hundreds of LLMs.





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>create_client</name><anchor>smolagents.LiteLLMModel.create_client</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L1181</source><parameters>[]</parameters></docstring>
Create the LiteLLM client.

</div></div>

### LiteLLMRouterModel[[smolagents.LiteLLMRouterModel]][[smolagents.LiteLLMRouterModel]]

`LiteLLMRouterModel`은 [LiteLLM Router](https://docs.litellm.ai/docs/routing)를 감싼 래퍼로, 다양한 고급 라우팅 전략을 지원합니다. 예를 들어, 여러 배포 환경 간 로드 밸런싱, 큐 기반의 중요 요청 우선 처리, 쿨다운, 폴백, 지수적 백오프 재시도 같은 기본 신뢰성 조치 구현 기능을 제공합니다.

```python
from smolagents import LiteLLMRouterModel

messages = [
  {"role": "user", "content": [{"type": "text", "text": "안녕하세요, 잘 지내고 계신가요?"}]}
]

model = LiteLLMRouterModel(
    model_id="llama-3.3-70b",
    model_list=[
        {
            "model_name": "llama-3.3-70b",
            "litellm_params": {"model": "groq/llama-3.3-70b", "api_key": os.getenv("GROQ_API_KEY")},
        },
        {
            "model_name": "llama-3.3-70b",
            "litellm_params": {"model": "cerebras/llama-3.3-70b", "api_key": os.getenv("CEREBRAS_API_KEY")},
        },
    ],
    client_kwargs={
        "routing_strategy": "simple-shuffle",
    },
)
print(model(messages))
```

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.LiteLLMRouterModel</name><anchor>smolagents.LiteLLMRouterModel</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L1289</source><parameters>[{"name": "model_id", "val": ": str"}, {"name": "model_list", "val": ": list"}, {"name": "client_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "custom_role_conversions", "val": ": dict[str, str] | None = None"}, {"name": "flatten_messages_as_text", "val": ": bool | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **model_id** (`str`) --
  Identifier for the model group to use from the model list (e.g., "model-group-1").
- **model_list** (`list[dict[str, Any]]`) --
  Model configurations to be used for routing.
  Each configuration should include the model group name and any necessary parameters.
  For more details, refer to the [LiteLLM Routing](https://docs.litellm.ai/docs/routing#quick-start) documentation.
- **client_kwargs** (`dict[str, Any]`, *optional*) --
  Additional configuration parameters for the Router client. For more details, see the
  [LiteLLM Routing Configurations](https://docs.litellm.ai/docs/routing).
- **custom_role_conversions** (`dict[str, str]`, *optional*) --
  Custom role conversion mapping to convert message roles in others.
  Useful for specific models that do not support specific message roles like "system".
- **flatten_messages_as_text** (`bool`, *optional*) -- Whether to flatten messages as text.
  Defaults to `True` for models that start with "ollama", "groq", "cerebras".
- ****kwargs** --
  Additional keyword arguments to forward to the underlying LiteLLM Router completion call.</paramsdesc><paramgroups>0</paramgroups></docstring>
Router‑based client for interacting with the [LiteLLM Python SDK Router](https://docs.litellm.ai/docs/routing).

This class provides a high-level interface for distributing requests among multiple language models using
the LiteLLM SDK's routing capabilities. It is responsible for initializing and configuring the router client,
applying custom role conversions, and managing message formatting to ensure seamless integration with various LLMs.



<ExampleCodeBlock anchor="smolagents.LiteLLMRouterModel.example">

Example:
```python
>>> import os
>>> from smolagents import CodeAgent, WebSearchTool, LiteLLMRouterModel
>>> os.environ["OPENAI_API_KEY"] = ""
>>> os.environ["AWS_ACCESS_KEY_ID"] = ""
>>> os.environ["AWS_SECRET_ACCESS_KEY"] = ""
>>> os.environ["AWS_REGION"] = ""
>>> llm_loadbalancer_model_list = [
...     {
...         "model_name": "model-group-1",
...         "litellm_params": {
...             "model": "gpt-4o-mini",
...             "api_key": os.getenv("OPENAI_API_KEY"),
...         },
...     },
...     {
...         "model_name": "model-group-1",
...         "litellm_params": {
...             "model": "bedrock/anthropic.claude-3-sonnet-20240229-v1:0",
...             "aws_access_key_id": os.getenv("AWS_ACCESS_KEY_ID"),
...             "aws_secret_access_key": os.getenv("AWS_SECRET_ACCESS_KEY"),
...             "aws_region_name": os.getenv("AWS_REGION"),
...         },
...     },
>>> ]
>>> model = LiteLLMRouterModel(
...    model_id="model-group-1",
...    model_list=llm_loadbalancer_model_list,
...    client_kwargs={
...        "routing_strategy":"simple-shuffle"
...    }
>>> )
>>> agent = CodeAgent(tools=[WebSearchTool()], model=model)
>>> agent.run("How many seconds would it take for a leopard at full speed to run through Pont des Arts?")
```

</ExampleCodeBlock>


</div>

### OpenAIModel[[smolagents.OpenAIModel]][[smolagents.OpenAIModel]]

이 클래스를 사용하면 OpenAIServer와 호환되는 모든 모델을 호출할 수 있습니다. 설정 방법은 다음과 같습니다 (`api_base` url을 다른 서버를 가리키도록 사용자 정의할 수 있습니다):
```py
import os
from smolagents import OpenAIModel

model = OpenAIModel(
    model_id="gpt-4o",
    api_base="https://api.openai.com/v1",
    api_key=os.environ["OPENAI_API_KEY"],
)
```

기반 모델에서 지원하는 모든 키워드 인수(`temperature`, `max_tokens`, `top_p` 등)를 인스턴스화 시점에 직접 전달할 수 있습니다. 이들은 모델 생성 호출로 전달됩니다:

```py
model = OpenAIModel(
    model_id="gpt-4o",
    api_base="https://api.openai.com/v1",
    api_key=os.environ["OPENAI_API_KEY"],
    temperature=0.7,
    max_tokens=1000,
    top_p=0.9,
)
```

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.OpenAIModel</name><anchor>smolagents.OpenAIModel</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L1572</source><parameters>[{"name": "model_id", "val": ": str"}, {"name": "api_base", "val": ": str | None = None"}, {"name": "api_key", "val": ": str | None = None"}, {"name": "organization", "val": ": str | None = None"}, {"name": "project", "val": ": str | None = None"}, {"name": "client_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "custom_role_conversions", "val": ": dict[str, str] | None = None"}, {"name": "flatten_messages_as_text", "val": ": bool = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **model_id** (`str`) --
  The model identifier to use on the server (e.g. "gpt-5").
- **api_base** (`str`, *optional*) --
  The base URL of the OpenAI-compatible API server.
- **api_key** (`str`, *optional*) --
  The API key to use for authentication.
- **organization** (`str`, *optional*) --
  The organization to use for the API request.
- **project** (`str`, *optional*) --
  The project to use for the API request.
- **client_kwargs** (`dict[str, Any]`, *optional*) --
  Additional keyword arguments to pass to the OpenAI client (like organization, project, max_retries etc.).
- **custom_role_conversions** (`dict[str, str]`, *optional*) --
  Custom role conversion mapping to convert message roles in others.
  Useful for specific models that do not support specific message roles like "system".
- **flatten_messages_as_text** (`bool`, default `False`) --
  Whether to flatten messages as text.
- ****kwargs** --
  Additional keyword arguments to forward to the underlying OpenAI API completion call, for instance `temperature`.</paramsdesc><paramgroups>0</paramgroups></docstring>
This model connects to an OpenAI-compatible API server.




</div>

### AzureOpenAIModel[[smolagents.AzureOpenAIModel]][[smolagents.AzureOpenAIModel]]

`AzureOpenAIModel`을 사용하면 모든 Azure OpenAI 배포에 연결할 수 있습니다.

아래에서 설정 예시를 확인할 수 있습니다. `azure_endpoint`, `api_key`, `api_version` 인수는 환경 변수(`AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_API_KEY`, `OPENAI_API_VERSION`)를 설정해 두면 생략할 수 있습니다.

`OPENAI_API_VERSION`에 `AZURE_` 접두사가 포함되지 않는다는 점을 주의하시기 바랍니다. 이는 기반이 되는 [openai](https://github.com/openai/openai-python) 패키지의 설계 방식 때문입니다.

```py
import os

from smolagents import AzureOpenAIModel

model = AzureOpenAIModel(
    model_id = os.environ.get("AZURE_OPENAI_MODEL"),
    azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
    api_key=os.environ.get("AZURE_OPENAI_API_KEY"),
    api_version=os.environ.get("OPENAI_API_VERSION")    
)
```

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.AzureOpenAIModel</name><anchor>smolagents.AzureOpenAIModel</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L1725</source><parameters>[{"name": "model_id", "val": ": str"}, {"name": "azure_endpoint", "val": ": str | None = None"}, {"name": "api_key", "val": ": str | None = None"}, {"name": "api_version", "val": ": str | None = None"}, {"name": "client_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "custom_role_conversions", "val": ": dict[str, str] | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **model_id** (`str`) --
  The model deployment name to use when connecting (e.g. "gpt-4o-mini").
- **azure_endpoint** (`str`, *optional*) --
  The Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/`. If not provided, it will be inferred from the `AZURE_OPENAI_ENDPOINT` environment variable.
- **api_key** (`str`, *optional*) --
  The API key to use for authentication. If not provided, it will be inferred from the `AZURE_OPENAI_API_KEY` environment variable.
- **api_version** (`str`, *optional*) --
  The API version to use. If not provided, it will be inferred from the `OPENAI_API_VERSION` environment variable.
- **client_kwargs** (`dict[str, Any]`, *optional*) --
  Additional keyword arguments to pass to the AzureOpenAI client (like organization, project, max_retries etc.).
- **custom_role_conversions** (`dict[str, str]`, *optional*) --
  Custom role conversion mapping to convert message roles in others.
  Useful for specific models that do not support specific message roles like "system".
- ****kwargs** --
  Additional keyword arguments to forward to the underlying Azure OpenAI API completion call.</paramsdesc><paramgroups>0</paramgroups></docstring>
This model connects to an Azure OpenAI deployment.




</div>

### AmazonBedrockModel[[smolagents.AmazonBedrockModel]][[smolagents.AmazonBedrockModel]]

`AmazonBedrockModel`은 Amazon Bedrock에 연결하고, 사용할 수 있는 모든 모델에서 에이전트를 실행할 수 있도록 지원합니다.

아래는 설정 예시입니다. 이 클래스는 사용자 정의를 위한 추가 옵션도 제공합니다.

```py
import os

from smolagents import AmazonBedrockModel

model = AmazonBedrockModel(
    model_id = os.environ.get("AMAZON_BEDROCK_MODEL_ID"),
)
```

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.AmazonBedrockModel</name><anchor>smolagents.AmazonBedrockModel</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L1785</source><parameters>[{"name": "model_id", "val": ": str"}, {"name": "client", "val": " = None"}, {"name": "client_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "custom_role_conversions", "val": ": dict[str, str] | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **model_id** (`str`) --
  The model identifier to use on Bedrock (e.g. "us.amazon.nova-pro-v1:0").
- **client** (`boto3.client`, *optional*) --
  A custom boto3 client for AWS interactions. If not provided, a default client will be created.
- **client_kwargs** (dict[str, Any], *optional*) --
  Keyword arguments used to configure the boto3 client if it needs to be created internally.
  Examples include `region_name`, `config`, or `endpoint_url`.
- **custom_role_conversions** (`dict[str, str]`, *optional*) --
  Custom role conversion mapping to convert message roles in others.
  Useful for specific models that do not support specific message roles like "system".
  Defaults to converting all roles to "user" role to enable using all the Bedrock models.
- **flatten_messages_as_text** (`bool`, default `False`) --
  Whether to flatten messages as text.
- ****kwargs** --
  Additional keyword arguments to forward to the underlying Amazon Bedrock model converse call.</paramsdesc><paramgroups>0</paramgroups></docstring>

A model class for interacting with Amazon Bedrock Server models through the Bedrock API.

This class provides an interface to interact with various Bedrock language models,
allowing for customized model inference, guardrail configuration, message handling,
and other parameters allowed by boto3 API.

Authentication:

Amazon Bedrock supports multiple authentication methods:
- Default AWS credentials:
  Use the default AWS credential chain (e.g., IAM roles, IAM users).
- API Key Authentication (requires `boto3 >= 1.39.0`):
  Set the API key using the `AWS_BEARER_TOKEN_BEDROCK` environment variable.

> [!TIP]
> API key support requires `boto3 >= 1.39.0`.
> For users not relying on API key authentication, the minimum supported version is `boto3 >= 1.36.18`.



Examples:
<ExampleCodeBlock anchor="smolagents.AmazonBedrockModel.example">

Creating a model instance with default settings:
```python
>>> bedrock_model = AmazonBedrockModel(
...     model_id='us.amazon.nova-pro-v1:0'
... )
```

</ExampleCodeBlock>

<ExampleCodeBlock anchor="smolagents.AmazonBedrockModel.example-2">

Creating a model instance with a custom boto3 client:
```python
>>> import boto3
>>> client = boto3.client('bedrock-runtime', region_name='us-west-2')
>>> bedrock_model = AmazonBedrockModel(
...     model_id='us.amazon.nova-pro-v1:0',
...     client=client
... )
```

</ExampleCodeBlock>

<ExampleCodeBlock anchor="smolagents.AmazonBedrockModel.example-3">

Creating a model instance with client_kwargs for internal client creation:
```python
>>> bedrock_model = AmazonBedrockModel(
...     model_id='us.amazon.nova-pro-v1:0',
...     client_kwargs={'region_name': 'us-west-2', 'endpoint_url': 'https://custom-endpoint.com'}
... )
```

</ExampleCodeBlock>

<ExampleCodeBlock anchor="smolagents.AmazonBedrockModel.example-4">

Creating a model instance with inference and guardrail configurations:
```python
>>> additional_api_config = {
...     "inferenceConfig": {
...         "maxTokens": 3000
...     },
...     "guardrailConfig": {
...         "guardrailIdentifier": "identify1",
...         "guardrailVersion": 'v1'
...     },
... }
>>> bedrock_model = AmazonBedrockModel(
...     model_id='anthropic.claude-3-haiku-20240307-v1:0',
...     **additional_api_config
... )
```

</ExampleCodeBlock>


</div>

### MLXModel[[smolagents.MLXModel]][[smolagents.MLXModel]]


```python
from smolagents import MLXModel

model = MLXModel(model_id="HuggingFaceTB/SmolLM-135M-Instruct")

print(model([{"role": "user", "content": "좋아!"}], stop_sequences=["이"]))
```
```text
>>> 좋아! 아래와 같
```

> [!TIP]
> 사용자의 컴퓨터에 `mlx-lm`이 설치되어 있어야 합니다. 설치되지 않은 경우 `pip install 'smolagents[mlx-lm]'`를 실행해 설치합니다.

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.MLXModel</name><anchor>smolagents.MLXModel</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L684</source><parameters>[{"name": "model_id", "val": ": str"}, {"name": "trust_remote_code", "val": ": bool = False"}, {"name": "load_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "apply_chat_template_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **model_id** (str) --
  The Hugging Face model ID to be used for inference. This can be a path or model identifier from the Hugging Face model hub.
- **tool_name_key** (str) --
  The key, which can usually be found in the model's chat template, for retrieving a tool name.
- **tool_arguments_key** (str) --
  The key, which can usually be found in the model's chat template, for retrieving tool arguments.
- **trust_remote_code** (bool, default `False`) --
  Some models on the Hub require running remote code: for this model, you would have to set this flag to True.
- **load_kwargs** (dict[str, Any], *optional*) --
  Additional keyword arguments to pass to the `mlx.lm.load` method when loading the model and tokenizer.
- **apply_chat_template_kwargs** (dict, *optional*) --
  Additional keyword arguments to pass to the `apply_chat_template` method of the tokenizer.
- ****kwargs** --
  Additional keyword arguments to forward to the underlying MLX model stream_generate call, for instance `max_tokens`.</paramsdesc><paramgroups>0</paramgroups></docstring>
A class to interact with models loaded using MLX on Apple silicon.

> [!TIP]
> You must have `mlx-lm` installed on your machine. Please run `pip install 'smolagents[mlx-lm]'` if it's not the case.



<ExampleCodeBlock anchor="smolagents.MLXModel.example">

Example:
```python
>>> engine = MLXModel(
...     model_id="mlx-community/Qwen2.5-Coder-32B-Instruct-4bit",
...     max_tokens=10000,
... )
>>> messages = [
...     {
...         "role": "user",
...         "content": "Explain quantum mechanics in simple terms."
...     }
... ]
>>> response = engine(messages, stop_sequences=["END"])
>>> print(response)
"Quantum mechanics is the branch of physics that studies..."
```

</ExampleCodeBlock>


</div>

### VLLMModel[[smolagents.VLLMModel]][[smolagents.VLLMModel]]

빠른 LLM 추론 및 서빙을 위해 [vLLM](https://docs.vllm.ai/)을 사용하는 모델입니다.

```python
from smolagents import VLLMModel

model = VLLMModel(model_id="HuggingFaceTB/SmolLM2-360M-Instruct")

print(model([{"role": "user", "content": "좋아!"}], stop_sequences=["이"]))
```

> [!TIP]
> 사용자의 컴퓨터에 `vllm`이 설치되어 있어야 합니다. 설치되지 않은 경우 `pip install 'smolagents[vllm]'`를 실행하세요.

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.VLLMModel</name><anchor>smolagents.VLLMModel</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/models.py#L574</source><parameters>[{"name": "model_id", "val": ""}, {"name": "model_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **model_id** (`str`) --
  The Hugging Face model ID to be used for inference.
  This can be a path or model identifier from the Hugging Face model hub.
- **model_kwargs** (`dict[str, Any]`, *optional*) --
  Additional keyword arguments to forward to the vLLM LLM instantiation, such as `revision`, `max_model_len`, etc.
- ****kwargs** --
  Additional keyword arguments to forward to the underlying vLLM model generate call.</paramsdesc><paramgroups>0</paramgroups></docstring>
Model to use [vLLM](https://docs.vllm.ai/) for fast LLM inference and serving.




</div>

### 사용자 정의 모델[[custom-model]]

자유롭게 자신만의 모델을 만들어 에이전트를 구동하는 데 사용할 수 있습니다.

기본 `Model` 클래스를 상속받아 에이전트를 위한 모델을 만들 수 있습니다.
주요 기준은 `generate` 메소드를 오버라이드하는 것이며, 다음 두 가지 기준을 따릅니다:
1. 입력으로 전달되는 `messages`는 [메시지 형식](./chat_templating)(`List[Dict[str, str]]`)을 따라야 하며 `.content` 속성을 가진 객체를 반환합니다.
2. `stop_sequences` 인수로 전달된 시퀀스에서 출력을 중단합니다.

LLM을 정의하기 위해, 기본 `Model` 클래스를 상속하는 `CustomModel` 클래스를 만들 수 있습니다.
이 클래스는 [메시지](./chat_templating) 리스트를 받아 텍스트를 포함하는 `.content` 속성을 가진 객체를 반환하는 `generate` 메소드를 가져야 합니다. `generate` 메소드는 또한 생성을 중단할 시점을 나타내는 `stop_sequences` 인수를 받아들여야 합니다.

```python
from huggingface_hub import login, InferenceClient

from smolagents import Model

login("<YOUR_HUGGINGFACEHUB_API_TOKEN>")

model_id = "meta-llama/Llama-3.3-70B-Instruct"

client = InferenceClient(model=model_id)

class CustomModel(Model):
    def generate(messages, stop_sequences=["Task"]):
        response = client.chat_completion(messages, stop=stop_sequences, max_tokens=1024)
        answer = response.choices[0].message
        return answer

custom_model = CustomModel()
```

또한, `generate` 메소드는 `grammar` 인수를 받아 [제약된 생성](https://huggingface.co/docs/text-generation-inference/conceptual/guidance)을 허용하여 올바른 형식의 에이전트 출력을 강제할 수 있습니다.


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/reference/models.md" />

### Agentic RAG[[agentic-rag]]
https://huggingface.co/docs/smolagents/main/ko/examples/rag.md

# Agentic RAG[[agentic-rag]]


## RAG(검색 증강 생성) 소개[[introduction-to-retrieval-augmented-generation-rag]]

검색 증강 생성(Retrieval-Augmented Generation, RAG)은 대규모 언어 모델의 능력과 외부 지식 검색을 결합하여 더 정확하고 사실에 기반을 두며 문맥에 맞는 응답을 생성합니다. RAG의 핵심은 "대규모 언어 모델을 사용해 사용자 쿼리에 답변을 제공하되, 지식 베이스에서 검색된 정보에 기반하여 답변하는 것"입니다.

### RAG를 사용하는 이유[[why-use-rag]]

RAG는 기본 대규모 언어 모델이나 미세 조정된 모델을 사용하는 것에 비해 다음과 같은 몇 가지 중요한 장점을 제공합니다.

1. **사실 기반 생성**: 답변의 근거를 검색 결과에 두어 환각 현상을 줄입니다.
2. **도메인 특화**: 모델을 다시 훈련시키지 않고도 특정 도메인의 지식을 제공합니다.
3. **최신 지식 반영**: 모델의 훈련 시점 이후의 정보에도 접근할 수 있습니다.
4. **투명성**: 생성된 콘텐츠의 출처를 인용할 수 있습니다.
5. **제어**: 모델이 접근할 수 있는 정보를 세밀하게 제어할 수 있습니다.

### 전통적인 RAG의 한계[[limitations-of-traditional-rag]]

이러한 장점에도 불구하고, 전통적인 RAG 접근 방식은 다음과 같은 몇 가지 문제가 있습니다.

- **단일 검색 단계**: 초기 검색 결과가 좋지 않으면 최종 생성 결과의 품질이 저하됩니다.
- **쿼리-문서 불일치**: 사용자 쿼리(주로 질문)가 답변을 포함하는 문서(주로 서술문)와 잘 일치하지 않을 수 있습니다.
- **제한된 추론**: 단순한 RAG 파이프라인은 다단계 논리적 추론이나 쿼리 정제를 허용하지 않습니다.
- **컨텍스트 윈도우 제약**: 검색된 문서는 모델의 컨텍스트 윈도우 크기에 맞춰야 합니다.

## Agentic RAG: 더 강력한 접근 방식[[agentic-rag-a-more-powerful-approach]]

**Agentic RAG** 시스템, 즉 검색 능력을 갖춘 에이전트를 구현함으로써 이러한 한계를 극복할 수 있습니다. 이 접근 방식은 RAG를 경직된 파이프라인에서 논리적 추론 중심의 상호작용적 프로세스로 탈바꿈시키는 방식입니다.

### Agentic RAG의 주요 장점[[key-benefits-of-agentic-rag]]

검색 도구를 갖춘 에이전트는 다음을 수행할 수 있습니다.

1. ✅ **최적화된 쿼리 생성**: 에이전트는 사용자 질문을 검색에 적합한 쿼리로 변환할 수 있습니다.
2. ✅ **다중 검색 수행**: 에이전트는 필요에 따라 반복적으로 정보를 검색할 수 있습니다.
3. ✅ **검색 결과 기반 논리적 추론**: 에이전트는 여러 소스의 정보를 분석, 종합하고 결론을 도출할 수 있습니다.
4. ✅ **자체 평가 및 개선**: 에이전트는 검색 결과를 평가하고 접근 방식을 조정할 수 있습니다.

이 접근 방식은 다음과 같은 Agentic RAG 기술을 자연스럽게 구현합니다.
- **가상 문서 임베딩(HyDE)**: 사용자 쿼리를 직접 사용하는 대신, 에이전트가 검색에 최적화된 쿼리를 생성합니다 ([논문 참조](https://huggingface.co/papers/2212.10496))
- **자가 쿼리 정제**: 에이전트가 초기 결과를 분석하고 정제된 쿼리로 후속 검색을 수행할 수 있습니다 ([기술 참조](https://docs.llamaindex.ai/en/stable/examples/evaluation/RetryQuery/))

## Agentic RAG 시스템 구축하기[[building-an-agentic-rag-system]]

이제 단계별로 Agentic RAG 시스템을 구축해 보겠습니다. 이 예제에서는 허깅 페이스 Transformers 라이브러리 설명서를 검색해 질문에 답할 수 있는 에이전트를 만들어 보겠습니다.

아래 코드 스니펫을 따라 하거나, smolagents GitHub 리포지토리에서 전체 예제를 확인할 수 있습니다: [examples/rag.py](https://github.com/huggingface/smolagents/blob/main/examples/rag.py).

### 1단계: 필요한 의존성 설치하기[[step-1-install-required-dependencies]]

먼저, 필요한 패키지를 설치해야 합니다.

```bash
pip install smolagents pandas langchain langchain-community sentence-transformers datasets python-dotenv rank_bm25 --upgrade
```

허깅 페이스의 추론 API를 사용하려면 API 토큰을 설정해야 합니다.

```python
# 환경 변수 로드 (HF_TOKEN 포함)
from dotenv import load_dotenv
load_dotenv()
```

### 2단계: 지식 베이스 준비하기[[step-2-prepare-the-knowledge-base]]

허깅 페이스 설명서가 포함된 데이터 세트를 불러와 검색에 사용할 준비를 해보겠습니다.

```python
import datasets
from langchain.docstore.document import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.retrievers import BM25Retriever

# 허깅 페이스 설명서 데이터 세트 로드
knowledge_base = datasets.load_dataset("m-ric/huggingface_doc", split="train")

# Transformers 라이브러리 설명서만 포함하도록 필터링
knowledge_base = knowledge_base.filter(lambda row: row["source"].startswith("huggingface/transformers"))

# 데이터 세트 항목을 메타데이터가 있는 Document 객체로 변환
source_docs = [
    Document(page_content=doc["text"], metadata={"source": doc["source"].split("/")[1]})
    for doc in knowledge_base
]

# 더 나은 검색을 위해 문서를 작은 청크로 분할
text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,  # 청크당 문자 수
    chunk_overlap=50,  # 컨텍스트 유지를 위한 청크 간 중첩
    add_start_index=True,
    strip_whitespace=True,
    separators=["\n\n", "\n", ".", " ", ""],  # 분할 우선순위
)
docs_processed = text_splitter.split_documents(source_docs)

print(f"Knowledge base prepared with {len(docs_processed)} document chunks")
```

### 3단계: 검색 도구 만들기[[step-3-create-a-retriever-tool]]

이제 에이전트가 지식 베이스에서 정보를 검색하는 데 사용할 수 있는 사용자 정의 도구를 만들어 보겠습니다.

```python
from smolagents import Tool

class RetrieverTool(Tool):
    name = "retriever"
    description = "의미 기반 검색을 사용하여 쿼리에 답변하는 데 가장 관련성이 높은 transformers 설명서 부분을 검색합니다."
    inputs = {
        "query": {
            "type": "string",
            "description": "수행할 쿼리입니다. 대상 문서와 의미적으로 가까워야 합니다. 질문보다는 긍정문을 사용하세요.",
        }
    }
    output_type = "string"

    def __init__(self, docs, **kwargs):
        super().__init__(**kwargs)
        # 처리된 문서로 검색기 초기화
        self.retriever = BM25Retriever.from_documents(
            docs, k=10  # 가장 관련성 높은 상위 10개 문서 반환
        )

    def forward(self, query: str) -> str:
        """제공된 쿼리를 기반으로 검색을 실행합니다."""
        assert isinstance(query, str), "Your search query must be a string"

        # 관련 문서 검색
        docs = self.retriever.invoke(query)

        # 가독성을 위해 검색된 문서 형식 지정
        return "\nRetrieved documents:\n" + "".join(
            [
                f"\n\n===== Document {str(i)} =====\n" + doc.page_content
                for i, doc in enumerate(docs)
            ]
        )

# 처리된 문서로 검색 도구 초기화
retriever_tool = RetrieverTool(docs_processed)
```

> [!TIP]
> 단순성과 속도를 위해 어휘 검색 방식인 BM25를 사용하고 있습니다. 실제 서비스 환경에서는 검색 품질을 높이기 위해 임베딩을 활용한 의미 기반 검색을 사용하는 것이 좋습니다. 고품질 임베딩 모델은 [MTEB 리더보드](https://huggingface.co/spaces/mteb/leaderboard)에서 확인하세요.

### 4단계: 고급 검색 에이전트 만들기[[step-4-create-an-advanced-retrieval-agent]]

다음으로 앞서 만든 검색 도구를 활용해 질문에 답할 수 있는 에이전트를 구성해 봅시다.

```python
from smolagents import InferenceClientModel, CodeAgent

# 검색 도구로 에이전트 초기화
agent = CodeAgent(
    tools=[retriever_tool],  # 에이전트가 사용할 수 있는 도구 목록
    model=InferenceClientModel(),  # 기본 모델 "Qwen/Qwen2.5-Coder-32B-Instruct"
    max_steps=4,  # 논리적 추론 단계 수 제한
    verbosity_level=2,  # 에이전트의 상세한 논리적 추론 과정 표시
)

# 특정 모델을 사용하려면 다음과 같이 지정할 수 있습니다:
# model=InferenceClientModel(model_id="meta-llama/Llama-3.3-70B-Instruct")
```

> [!TIP]
> Inference Provider는 서버리스 추론 파트너가 제공하는 수백 개의 모델에 대한 액세스를 제공합니다. 지원되는 제공업체 목록은 [여기](https://huggingface.co/docs/inference-providers/index)에서 찾을 수 있습니다.

### 5단계: 에이전트를 실행하여 질문에 답하기[[step-5-run-the-agent-to-answer-questions]]

마지막으로 에이전트를 실행해 Transformers 관련 질문에 답해 보겠습니다.

```python
# 정보 검색이 필요한 질문하기
question = "For a transformers model training, which is slower, the forward or the backward pass?"

# 에이전트를 실행하여 답변 얻기
agent_output = agent.run(question)

# 최종 답변 표시
print("\nFinal answer:")
print(agent_output)
```

## Agentic RAG의 실제 적용 사례[[practical-applications-of-agentic-rag]]

Agentic RAG 시스템은 다양한 사용 사례에 적용될 수 있습니다.

1. **기술 문서 지원**: 사용자가 복잡한 기술 문서를 탐색하는 데 도움을 줍니다.
2. **연구 논문 분석**: 과학 논문에서 정보를 추출하고 종합합니다.
3. **법률 문서 검토**: 법률 문서에서 관련 판례와 조항을 찾습니다.
4. **고객 지원**: 제품 설명서와 지식 베이스를 기반으로 질문에 답변합니다.
5. **교육 튜터링**: 교과서와 학습 자료를 기반으로 설명을 제공합니다.

## 결론[[conclusion]]

Agentic RAG는 전통적인 RAG 파이프라인을 뛰어넘는 중요한 발전을 의미합니다. 대형 언어 모델 에이전트의 추론 능력과 검색 시스템의 사실 기반을 결합함으로써, 우리는 더 강력하고 유연하며 정확한 정보 시스템을 구축할 수 있습니다.

저희가 보여드린 접근 방식은 다음과 같은 특징이 있습니다:
- 단일 단계 검색의 한계를 극복합니다.
- 지식 베이스와의 상호작용이 더 자연스러워집니다.
- 자체 평가와 쿼리 정제를 통해 지속해서 개선할 수 있는 프레임워크를 제공합니다.

자신만의 Agentic RAG 시스템을 구축할 때에는, 다양한 검색 방법과 에이전트 아키텍처, 지식 소스를 실험하며 사용 사례에 최적화된 구성을 찾아보세요.

<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/examples/rag.md" />

### 에이전트를 활용한 웹 브라우저 자동화 🤖🌐[[web-browser-automation-with-agents-🤖🌐]]
https://huggingface.co/docs/smolagents/main/ko/examples/web_browser.md

# 에이전트를 활용한 웹 브라우저 자동화 🤖🌐[[web-browser-automation-with-agents-🤖🌐]]


이 노트북에서는 **에이전트 기반 웹 브라우저 자동화 시스템**을 구축해보겠습니다! 이 시스템은 웹사이트 탐색, 요소 상호작용, 정보 자동 추출이 가능합니다.

에이전트는 다음과 같은 기능을 수행할 수 있습니다.

- [x] 웹 페이지 탐색
- [x] 요소 클릭
- [x] 페이지 내 검색
- [x] 팝업 및 모달 처리
- [x] 정보 추출

단계별로 이 시스템을 구축해보겠습니다!

먼저 필요한 의존성을 설치하기 위해 다음을 실행하세요.

```bash
pip install smolagents selenium helium pillow -q
```

필요한 라이브러리를 가져오고 환경 변수를 설정해보겠습니다.

```python
from io import BytesIO
from time import sleep

import helium
from dotenv import load_dotenv
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

from smolagents import CodeAgent, tool
from smolagents.agents import ActionStep

# 환경 변수를 불러옵니다.
load_dotenv()
```

이제 에이전트가 웹 페이지를 탐색하고 상호작용할 수 있도록 하는 핵심 브라우저 상호작용 도구들을 만들어보겠습니다.

```python
@tool
def search_item_ctrl_f(text: str, nth_result: int = 1) -> str:
    """
    현재 페이지에서 Ctrl + F를 사용해 지정된 텍스트를 검색하고, n번째로 등장하는 위치로 이동합니다.
    인자:
        text: 검색할 텍스트
        nth_result: 이동할 n번째 검색 결과 (기본값: 1)
    """
    elements = driver.find_elements(By.XPATH, f"//*[contains(text(), '{text}')]")
    if nth_result > len(elements):
        raise Exception(f"Match n°{nth_result} not found (only {len(elements)} matches found)")
    result = f"Found {len(elements)} matches for '{text}'."
    elem = elements[nth_result - 1]
    driver.execute_script("arguments[0].scrollIntoView(true);", elem)
    result += f"Focused on element {nth_result} of {len(elements)}"
    return result

@tool
def go_back() -> None:
    """이전 페이지로 돌아갑니다."""
    driver.back()

@tool
def close_popups() -> str:
    """
    Closes any visible modal or pop-up on the page. Use this to dismiss pop-up windows!
    This does not work on cookie consent banners.
    """
    webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()
```

Chrome으로 브라우저를 설정하고 스크린샷 기능을 구성해보겠습니다.

```python
# Configure Chrome options
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--force-device-scale-factor=1")
chrome_options.add_argument("--window-size=1000,1350")
chrome_options.add_argument("--disable-pdf-viewer")
chrome_options.add_argument("--window-position=0,0")

# Initialize the browser
driver = helium.start_chrome(headless=False, options=chrome_options)

# Set up screenshot callback
def save_screenshot(memory_step: ActionStep, agent: CodeAgent) -> None:
    sleep(1.0)  # Let JavaScript animations happen before taking the screenshot
    driver = helium.get_driver()
    current_step = memory_step.step_number
    if driver is not None:
        for previous_memory_step in agent.memory.steps:  # Remove previous screenshots for lean processing
            if isinstance(previous_memory_step, ActionStep) and previous_memory_step.step_number <= current_step - 2:
                previous_memory_step.observations_images = None
        png_bytes = driver.get_screenshot_as_png()
        image = Image.open(BytesIO(png_bytes))
        print(f"Captured a browser screenshot: {image.size} pixels")
        memory_step.observations_images = [image.copy()]  # Create a copy to ensure it persists

    # Update observations with current URL
    url_info = f"Current url: {driver.current_url}"
    memory_step.observations = (
        url_info if memory_step.observations is None else memory_step.observations + "\n" + url_info
    )
```

이제 웹 자동화 에이전트를 만들어보겠습니다.

```python
from smolagents import InferenceClientModel

# Initialize the model
model_id = "Qwen/Qwen2-VL-72B-Instruct"  # You can change this to your preferred VLM model
model = InferenceClientModel(model_id=model_id)

# Create the agent
agent = CodeAgent(
    tools=[go_back, close_popups, search_item_ctrl_f],
    model=model,
    additional_authorized_imports=["helium"],
    step_callbacks=[save_screenshot],
    max_steps=20,
    verbosity_level=2,
)

# Import helium for the agent
agent.python_executor("from helium import *", agent.state)
```

에이전트가 웹 자동화를 위해 Helium을 사용하려면 지침이 필요합니다. 다음은 제공할 지침입니다.

```python
helium_instructions = """
You can use helium to access websites. Don't bother about the helium driver, it's already managed.
We've already ran "from helium import *"
Then you can go to pages!
Code:
```py
go_to('github.com/trending')
```<end_code>

You can directly click clickable elements by inputting the text that appears on them.
Code:
```py
click("Top products")
```<end_code>

If it's a link:
Code:
```py
click(Link("Top products"))
```<end_code>

If you try to interact with an element and it's not found, you'll get a LookupError.
In general stop your action after each button click to see what happens on your screenshot.
Never try to login in a page.

To scroll up or down, use scroll_down or scroll_up with as an argument the number of pixels to scroll from.
Code:
```py
scroll_down(num_pixels=1200) # This will scroll one viewport down
```<end_code>

When you have pop-ups with a cross icon to close, don't try to click the close icon by finding its element or targeting an 'X' element (this most often fails).
Just use your built-in tool `close_popups` to close them:
Code:
```py
close_popups()
```<end_code>

You can use .exists() to check for the existence of an element. For example:
Code:
```py
if Text('Accept cookies?').exists():
    click('I accept')
```<end_code>
"""
```

이제 작업과 함께 에이전트를 실행할 수 있습니다! Wikipedia에서 정보를 찾는 것을 시도해보겠습니다.

```python
search_request = """
Please navigate to https://en.wikipedia.org/wiki/Chicago and give me a sentence containing the word "1992" that mentions a construction accident.
"""

agent_output = agent.run(search_request + helium_instructions)
print("Final output:")
print(agent_output)
```

요청을 수정하여 다른 작업을 실행할 수 있습니다. 예를 들어, 제가 얼마나 열심히 일해야 하는지 알아보는 작업입니다.

```python
github_request = """
I'm trying to find how hard I have to work to get a repo in github.com/trending.
Can you navigate to the profile for the top author of the top trending repo, and give me their total number of commits over the last year?
"""

agent_output = agent.run(github_request + helium_instructions)
print("Final output:")
print(agent_output)
```

이 시스템은 특히 다음과 같은 작업에 효과적입니다.
- 웹사이트에서 데이터 추출
- 웹 리서치 자동화
- UI 테스트 및 검증
- 콘텐츠 모니터링


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/examples/web_browser.md" />

### 에이전트를 활용한 비동기 애플리케이션[[async-applications-with-agents]]
https://huggingface.co/docs/smolagents/main/ko/examples/async_agent.md

# 에이전트를 활용한 비동기 애플리케이션[[async-applications-with-agents]]

이 가이드는 smolagents 라이브러리의 동기 에이전트를 Starlette 기반의 비동기 Python 웹 애플리케이션에 통합하는 방법을 설명합니다.
비동기 Python과 에이전트 통합을 처음 접하는 사용자들이 동기 에이전트 로직과 비동기 웹 서버를 효과적으로 결합하는 모범 사례를 익힐 수 있도록 구성했습니다.

## 개요[[overview]]

- **Starlette**: Python에서 비동기 웹 애플리케이션을 구축하기 위한 경량 ASGI 프레임워크입니다.
- **anyio.to_thread.run_sync**: 블로킹(동기) 코드를 백그라운드 스레드에서 실행하여 비동기 이벤트 루프를 차단하지 않도록 하는 유틸리티입니다.
- **CodeAgent**: 프로그래밍 방식으로 작업을 해결할 수 있는 `smolagents` 라이브러리의 에이전트입니다.

## 백그라운드 스레드를 사용하는 이유는?[[why-use-a-background-thread?]]

`CodeAgent.run()`은 Python 코드를 동기적으로 실행합니다. 비동기 엔드포인트에서 직접 호출하면 Starlette의 이벤트 루프를 차단하여 성능과 확장성이 저하됩니다. `anyio.to_thread.run_sync`로 이 작업을 백그라운드 스레드로 위임하면 높은 동시성에서도 앱의 응답성과 효율성을 유지할 수 있습니다.

## 예시 워크플로우[[example-workflow]]

- Starlette 앱은 `task` 문자열이 포함된 JSON 페이로드를 받는 `/run-agent` 엔드포인트를 노출합니다.
- 요청이 수신되면 `anyio.to_thread.run_sync`를 사용하여 백그라운드 스레드에서 에이전트가 실행됩니다.
- 결과는 JSON 응답으로 반환됩니다.

## CodeAgent를 활용한 Starlette 앱 구축[[building-a-starlette-app-with-a-codeagent]]

### 1. 의존성 설치[[1.-install-dependencies]]

```bash
pip install smolagents starlette anyio uvicorn
```

### 2. 애플리케이션 코드 (`main.py`)[[2.-application-code-(`main.py`)]]

```python
import anyio.to_thread
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route

from smolagents import CodeAgent, InferenceClientModel

agent = CodeAgent(
    model=InferenceClientModel(model_id="Qwen/Qwen3-Next-80B-A3B-Thinking"),
    tools=[],
)

async def run_agent(request: Request):
    data = await request.json()
    task = data.get("task", "")
    # Run the agent synchronously in a background thread
    result = await anyio.to_thread.run_sync(agent.run, task)
    return JSONResponse({"result": result})

app = Starlette(routes=[
    Route("/run-agent", run_agent, methods=["POST"]),
])
```

### 3. 앱 실행[[3.-run-the-app]]

```bash
uvicorn async_agent.main:app --reload
```

### 4. 엔드포인트 테스트[[4.-test-the-endpoint]]

```bash
curl -X POST http://localhost:8000/run-agent -H 'Content-Type: application/json' -d '{"task": "What is 2+2?"}'
```

**예상 응답:**

```json
{"result": "4"}
```

## 추가 자료[[further-reading]]

- [Starlette 문서](https://www.starlette.io/)
- [anyio 문서](https://anyio.readthedocs.io/)

---

전체 코드는 [`examples/async_agent`](https://github.com/huggingface/smolagents/tree/main/examples/async_agent)를 참고하세요.


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/examples/async_agent.md" />

### 멀티 에이전트 시스템 오케스트레이션 🤖🤝🤖
https://huggingface.co/docs/smolagents/main/ko/examples/multiagents.md

# 멀티 에이전트 시스템 오케스트레이션 🤖🤝🤖

[[Colab에서 열기]]

이 노트북에서는 **멀티 에이전트 웹 브라우저**를 만들어보겠습니다. 이는 웹을 사용하여 문제를 해결하기 위해 여러 에이전트가 협력하는 에이전트 시스템입니다!

멀티 에이전트는 간단한 계층 구조로 구성됩니다.

```
              +----------------+
              | Manager agent  |
              +----------------+
                       |
        _______________|______________
       |                              |
Code Interpreter            +------------------+
    tool                    | Web Search agent |
                            +------------------+
                               |            |
                        Web Search tool     |
                                   Visit webpage tool
```
이 시스템을 설정해보겠습니다. 

다음 명령어를 실행하여 필요한 종속성을 설치합니다.

```py
!pip install smolagents[toolkit] --upgrade -q
```

Inference Providers를 사용하기 위해 Hugging Face에 로그인합니다:

```py
from huggingface_hub import login

login()
```

⚡️ 에이전트는 Hugging Face의 Inference API를 사용하는 `InferenceClientModel` 클래스를 통해 [Qwen/Qwen3-Next-80B-A3B-Thinking](https://huggingface.co/Qwen/Qwen3-Next-80B-A3B-Thinking)로 구동됩니다. Inference API를 사용하면 모든 오픈소스 모델을 빠르고 쉽게 실행할 수 있습니다.

> [!TIP]
> Inference Providers는 서버리스 추론 파트너가 지원하는 수백 개의 모델에 대한 액세스를 제공합니다. 지원되는 프로바이더 목록은 [여기](https://huggingface.co/docs/inference-providers/index)에서 확인할 수 있습니다.

```py
model_id = "Qwen/Qwen3-Next-80B-A3B-Thinking"
```

## 🔍 웹 검색 도구 생성

웹 브라우징을 위해 Google 검색과 동등한 기능을 제공하는 기본 `WebSearchTool` 도구를 이미 사용할 수 있습니다.

하지만 `WebSearchTool`에서 찾은 페이지를 확인할 수 있는 기능도 필요합니다.
이를 위해 라이브러리에 내장된 `VisitWebpageTool`을 사용할 수도 있지만, 작동 원리를 이해하기 위해 직접 구현해보겠습니다.

`markdownify`를 사용하여 `VisitWebpageTool` 도구를 처음부터 만들어보겠습니다.

```py
import re
import requests
from markdownify import markdownify
from requests.exceptions import RequestException
from smolagents import tool


@tool
def visit_webpage(url: str) -> str:
    """주어진 URL의 웹페이지에 접속하여 그 내용을 마크다운 형식의 반환합니다.

    매개변수:
        url: 방문할 웹페이지의 URL.

    반환값:
        마크다운으로 변환된 웹페이지 내용, 또는 요청이 실패할 경우 오류 메시지.
    """
    try:
        # URL에 GET 요청 전송
        response = requests.get(url)
        response.raise_for_status()  # 잘못된 상태 코드에 대해 예외 발생

        # HTML 내용을 마크다운으로 변환
        markdown_content = markdownify(response.text).strip()

        # 여러 줄 바꿈 제거
        markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)

        return markdown_content

    except RequestException as e:
        return f"Error fetching the webpage: {str(e)}"
    except Exception as e:
        return f"An unexpected error occurred: {str(e)}"
```

이제 도구를 초기화하고 테스트해보겠습니다!

```py
print(visit_webpage("https://en.wikipedia.org/wiki/Hugging_Face")[:500])
```

## 멀티 에이전트 시스템 구축 🤖🤝🤖

이제 `search`와 `visit_webpage` 도구가 모두 준비되었으므로, 이를 사용하여 웹 에이전트를 생성할 수 있습니다.

이 에이전트에 어떤 구성을 선택할까요?
- 웹 브라우징은 병렬 도구 호출이 필요없는 단일 타임라인 작업이므로, JSON 도구 호출 방식이 적합합니다. 따라서 `ToolCallingAgent`를 선택합니다.
- 또한 웹 검색은 올바른 답을 찾기 전에 많은 페이지를 탐색해야 하는 경우가 있으므로, `max_steps`를 10으로 늘리는 것이 좋습니다.

```py
from smolagents import (
    CodeAgent,
    ToolCallingAgent,
    InferenceClientModel,
    WebSearchTool,
)

model = InferenceClientModel(model_id=model_id)

web_agent = ToolCallingAgent(
    tools=[WebSearchTool(), visit_webpage],
    model=model,
    max_steps=10,
    name="web_search_agent",
    description="Runs web searches for you.",
)
```

이 에이전트에 `name`과 `description` 속성을 부여했습니다. 이는 이 에이전트가 매니저 에이전트에 의해 호출될 수 있도록 하는 필수 속성입니다.

그 다음 매니저 에이전트를 생성하고, 초기화 시 `managed_agents` 인수에 관리되는 에이전트를 전달합니다.

이 에이전트는 계획과 사고를 담당하므로, 고급 추론이 유용할 것입니다. 따라서 `CodeAgent`가 잘 작동할 것입니다.

또한 현재 연도를 포함하고 추가 데이터 계산을 수행하는 질문을 하고 싶으므로, 에이전트가 이러한 패키지를 필요로 할 경우에 대비해 `additional_authorized_imports=["time", "numpy", "pandas"]`를 추가해보겠습니다.

```py
manager_agent = CodeAgent(
    tools=[],
    model=model,
    managed_agents=[web_agent],
    additional_authorized_imports=["time", "numpy", "pandas"],
)
```

이게 전부입니다! 이제 시스템을 실행해보겠습니다! 계산과 연구가 모두 필요한 질문을 선택합니다.

```py
answer = manager_agent.run("LLM 훈련이 현재 속도로 2030년까지 계속 확장된다면, 2030년까지 가장 큰 훈련 실행에 전력을 공급하는 데 필요한 전력량은 GW 단위로 얼마가 될까요? 이는 일부 국가들과 비교했을 때 무엇에 해당할까요? 사용된 모든 수치에 대한 출처를 제공해주세요.")
```

답변으로 이런 보고서를 받습니다.
```
현재 성장 전망과 에너지 소비량 추정에 따르면,
2030년까지 LLM 교육이 현재 속도로 계속 확장된다면 다음과 같이 예상됩니다.

1. 2030년까지 가장 큰 훈련 실행에 전력을 공급하는 데 필요한 전력량은 약 303.74 GW가 될 것이며, 
이는 연간 약 2,660,762 GWh로 환산됩니다.

2. 국가별 전력 소비량 비교
   - 중국 총 전력 소비량의 약 34%에 해당합니다.
   - 인도(184%), 러시아(267%), 일본(291%)의 총 전력 소비량을 초과할 것입니다.
   - 이탈리아나 멕시코 같은 국가들의 전력 소비량의 거의 9배가 됩니다.

3. 수치 출처
   - 미래 LLM 훈련을 위한 5 GW의 초기 추정치는 AWS CEO Matt Garman에서 나온 것입니다.
   - 성장 예측은 Springs의 시장 조사에서 79.80%의 CAGR을 사용했습니다.
   - 국가 전력 소비 데이터는 주로 2021년 기준으로 미국 에너지 정보 관리청에서 나온 것입니다.
```

[스케일링 가설](https://gwern.net/scaling-hypothesis)이 계속 참이라면 상당히 큰 발전소가 필요할 것 같습니다.

에이전트들이 작업을 해결하기 위해 효율적으로 협력했습니다! ✅

💡 이 오케스트레이션을 더 많은 에이전트로 쉽게 확장할 수 있습니다: 하나는 코드 실행을, 다른 하나는 웹 검색을,  또 다른 하나는 파일 처리를 담당하는 식으로...


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/examples/multiagents.md" />

### Text-to-SQL[[text-to-sql]]
https://huggingface.co/docs/smolagents/main/ko/examples/text_to_sql.md

# Text-to-SQL[[text-to-sql]]


이 튜토리얼에서는 `smolagents`를 사용해 SQL을 다루는 에이전트를 구현해보겠습니다.

> 먼저 중요한 질문 하나로 시작하겠습니다. 그냥 간단하게 일반적인 text-to-SQL 파이프라인을 쓰면 안 될까요?

표준 text-to-SQL 파이프라인은 안정성이 떨어지는 경우가 많습니다. 쿼리가 잘못 생성될 수 있고, 심지어는 오류 없이 틀리거나 쓸모없는 결과를 반환할 수도 있습니다.

👉 반면, 에이전트 시스템은 출력 결과를 비판적으로 점검할 수 있고 쿼리를 수정할 필요가 있는지 스스로 결정할 수 있이 성능이 크게 향상됩니다.

이제 이 에이전트를 직접 만들어봅시다! 💪

아래 명령어를 실행해 필요한 의존성을 설치하세요:
```bash
!pip install smolagents python-dotenv sqlalchemy --upgrade -q
```

추론 프로바이더를 호출하려면 환경 변수 `HF_TOKEN`에 유효한 토큰이 설정되어 있어야 합니다.
python-dotenv를 이용해 환경 변수를 불러오겠습니다.
```py
from dotenv import load_dotenv
load_dotenv()
```

다음으로, SQL 환경을 구성하겠습니다:
```py
from sqlalchemy import (
    create_engine,
    MetaData,
    Table,
    Column,
    String,
    Integer,
    Float,
    insert,
    inspect,
    text,
)

engine = create_engine("sqlite:///:memory:")
metadata_obj = MetaData()

def insert_rows_into_table(rows, table, engine=engine):
    for row in rows:
        stmt = insert(table).values(**row)
        with engine.begin() as connection:
            connection.execute(stmt)

table_name = "receipts"
receipts = Table(
    table_name,
    metadata_obj,
    Column("receipt_id", Integer, primary_key=True),
    Column("customer_name", String(16), primary_key=True),
    Column("price", Float),
    Column("tip", Float),
)
metadata_obj.create_all(engine)

rows = [
    {"receipt_id": 1, "customer_name": "Alan Payne", "price": 12.06, "tip": 1.20},
    {"receipt_id": 2, "customer_name": "Alex Mason", "price": 23.86, "tip": 0.24},
    {"receipt_id": 3, "customer_name": "Woodrow Wilson", "price": 53.43, "tip": 5.43},
    {"receipt_id": 4, "customer_name": "Margaret James", "price": 21.11, "tip": 1.00},
]
insert_rows_into_table(rows, receipts)
```

### 에이전트 만들기[[build-our-agent]]

이제 도구를 활용해 SQL 테이블을 조회할 수 있도록 만들어봅시다.

툴의 설명 속성은 에이전트 시스템에 의해 LLM 프롬프트에 포함되는 부분으로, LLM이 해당 도구를 어떻게 사용할 수 있는지에 대한 정보를 제공합니다. 바로 이 부분에 우리가 정의한 SQL 테이블의 설명을 작성하면 됩니다.

```py
inspector = inspect(engine)
columns_info = [(col["name"], col["type"]) for col in inspector.get_columns("receipts")]

table_description = "Columns:\n" + "\n".join([f"  - {name}: {col_type}" for name, col_type in columns_info])
print(table_description)
```

```text
Columns:
  - receipt_id: INTEGER
  - customer_name: VARCHAR(16)
  - price: FLOAT
  - tip: FLOAT
```

이제 우리만의 툴을 만들어봅시다. 도구은 아래와 같은 요소를 필요로 합니다. (자세한 내용은 [도구 문서](../tutorials/tools)를 참고하세요)
- 인자(`Args:`) 목록이 포함된 docstring
- 입력과 출력에 대한 타입 힌트

```py
from smolagents import tool

@tool
def sql_engine(query: str) -> str:
    """
    테이블에 SQL 쿼리를 수행할 수 있습니다. 결과를 문자열로 반환합니다.
    테이블 이름은 'receipts'이며, 설명은 다음과 같습니다:
        Columns:
        - receipt_id: INTEGER
        - customer_name: VARCHAR(16)
        - price: FLOAT
        - tip: FLOAT

    Args:
        query: 수행할 쿼리입니다. 올바른 SQL이어야 합니다.
    """
    output = ""
    with engine.connect() as con:
        rows = con.execute(text(query))
        for row in rows:
            output += "\n" + str(row)
    return output
```

이제 이 도구를 사용하는 에이전트를 만들어보겠습니다.

여기서는 smolagent의 메인 에이전트 클래스인 `CodeAgent`를 사용합니다. `CodeAgent`는 코드로 액션을 작성하고 ReAct 프레임워크에 따라 이전 출력 결과를 반복적으로 개선할 수 있습니다.

모델은 에이전트 시스템을 구동하는 LLM을 의미합니다. `InferenceClientModel`을 사용하면 허깅페이스의 Inference API를 통해 서버리스 또는 Dedicated 엔드포인트 방식으로 LLM을 호출할 수 있으며, 필요에 따라 다른 사설 API를 사용할 수도 있습니다.

```py
from smolagents import CodeAgent, InferenceClientModel

agent = CodeAgent(
    tools=[sql_engine],
    model=InferenceClientModel(model_id="meta-llama/Llama-3.1-8B-Instruct"),
)
agent.run("Can you give me the name of the client who got the most expensive receipt?")
```

### 레벨 업: 테이블 조인[[level-2-table-joins]]

이제 좀 더 어려운 과제를 해결해 볼까요? 에이전트가 여러 테이블에 걸친 조인을 처리하도록 만들어 보겠습니다.

이를 위해 각 `receipt_id`에 해당하는 웨이터의 이름을 기록하는 두 번째 테이블을 만들어 보겠습니다.

```py
table_name = "waiters"
waiters = Table(
    table_name,
    metadata_obj,
    Column("receipt_id", Integer, primary_key=True),
    Column("waiter_name", String(16), primary_key=True),
)
metadata_obj.create_all(engine)

rows = [
    {"receipt_id": 1, "waiter_name": "Corey Johnson"},
    {"receipt_id": 2, "waiter_name": "Michael Watts"},
    {"receipt_id": 3, "waiter_name": "Michael Watts"},
    {"receipt_id": 4, "waiter_name": "Margaret James"},
]
insert_rows_into_table(rows, waiters)
```
테이블이 변경되었기 때문에 LLM이 테이블 정보를 올바르게 활용할 수 있도록 `sql_engine`의 설명을 업데이트하겠습니다.

```py
updated_description = """Allows you to perform SQL queries on the table. Beware that this tool's output is a string representation of the execution output.
It can use the following tables:"""

inspector = inspect(engine)
for table in ["receipts", "waiters"]:
    columns_info = [(col["name"], col["type"]) for col in inspector.get_columns(table)]

    table_description = f"Table '{table}':\n"

    table_description += "Columns:\n" + "\n".join([f"  - {name}: {col_type}" for name, col_type in columns_info])
    updated_description += "\n\n" + table_description

print(updated_description)
```
이번 요청은 이전보다 조금 더 어려우므로, 더 강력한 [Qwen/Qwen3-Next-80B-A3B-Thinking](https://huggingface.co/Qwen/Qwen3-Next-80B-A3B-Thinking) 모델을 사용하도록 LLM 엔진을 바꾸겠습니다!

```py
sql_engine.description = updated_description

agent = CodeAgent(
    tools=[sql_engine],
    model=InferenceClientModel(model_id="Qwen/Qwen3-Next-80B-A3B-Thinking"),
)

agent.run("Which waiter got more total money from tips?")
```
바로 성공입니다! 놀라울 만큼 간단하게 설정되지 않았나요?

이번 예제는 여기까지입니다! 지금까지 다음과 같은 개념들을 살펴보았습니다.
- 새로운 도구 만들기
- 도구 설명 업데이트하기
- 더 강력한 LLM으로 에이전트 추론 능력 향상시키기

✅ 이제 여러분이 꿈꿔왔던 text-to-SQL 시스템을 직접 만들어 보세요! ✨


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/examples/text_to_sql.md" />

### 다양한 모델 사용하기 [[using-different-models]]
https://huggingface.co/docs/smolagents/main/ko/examples/using_different_models.md

# 다양한 모델 사용하기 [[using-different-models]]


`smolagents`는 다양한 프로바이더의 여러 언어 모델을 사용할 수 있는 유연한 프레임워크를 제공합니다.
이 가이드는 에이전트와 함께 다양한 모델 유형을 사용하는 방법을 보여줍니다.

## 사용 가능한 모델 유형 [[available-model-types]]

`smolagents`는 기본적으로 여러 모델 유형을 지원합니다:
1. [InferenceClientModel](/docs/smolagents/main/ko/reference/models#smolagents.InferenceClientModel): Hugging Face의 추론 API를 사용하여 모델에 접근
2. [TransformersModel](/docs/smolagents/main/ko/reference/models#smolagents.TransformersModel): 🤗 Transformers 라이브러리를 사용하여 로컬에서 모델 실행
3. [VLLMModel](/docs/smolagents/main/ko/reference/models#smolagents.VLLMModel): 최적화된 서빙으로 빠른 추론을 위해 vLLM 사용
4. [MLXModel](/docs/smolagents/main/ko/reference/models#smolagents.MLXModel): MLX를 사용하여 Apple Silicon 디바이스에 최적화
5. [LiteLLMModel](/docs/smolagents/main/ko/reference/models#smolagents.LiteLLMModel): LiteLLM을 통해 수백 개의 대규모 언어 모델에 접근 제공
6. [LiteLLMRouterModel](/docs/smolagents/main/ko/reference/models#smolagents.LiteLLMRouterModel): 여러 모델 간에 요청을 분산
7. [OpenAIModel](/docs/smolagents/main/ko/reference/models#smolagents.OpenAIModel): OpenAI 호환 API를 구현하는 모든 프로바이더에 접근 제공
8. [AzureOpenAIModel](/docs/smolagents/main/ko/reference/models#smolagents.AzureOpenAIModel): Azure의 OpenAI 서비스 사용
9. [AmazonBedrockModel](/docs/smolagents/main/ko/reference/models#smolagents.AmazonBedrockModel): AWS Bedrock의 API에 연결

모든 모델 클래스는 인스턴스화 시점에 추가 키워드 인수들(`temperature`, `max_tokens`, `top_p` 등)을 직접 전달하는 것을 지원합니다.
이러한 매개변수들은 자동으로 기본 모델의 완성 호출로 전달되어, 창의성, 응답 길이, 샘플링 전략과 같은 모델 동작을 구성할 수 있게 해줍니다.

## Google Gemini 모델 사용하기 [[using-google-gemini-models]]

Google Gemini API 문서(https://ai.google.dev/gemini-api/docs/openai)에서 설명한 바와 같이,
Google은 Gemini 모델에 대해 OpenAI 호환 API를 제공하므로, 적절한 베이스 URL을 설정하여
[OpenAIModel](/docs/smolagents/main/ko/reference/models#smolagents.OpenAIModel)을 Gemini 모델과 함께 사용할 수 있습니다.

먼저, 필요한 의존성을 설치합니다:
```bash
pip install 'smolagents[openai]'
```

그다음, [Gemini API 키를 얻고](https://ai.google.dev/gemini-api/docs/api-key) 코드에서 설정합니다:
```python
GEMINI_API_KEY = <YOUR-GEMINI-API-KEY>
```

이제 `OpenAIModel` 클래스를 사용하고 `api_base` 매개변수를 Gemini API 베이스 URL로 설정하여
Gemini 모델을 초기화할 수 있습니다:
```python
from smolagents import OpenAIModel

model = OpenAIModel(
    model_id="gemini-2.0-flash",
    # Google Gemini OpenAI 호환 API 베이스 URL
    api_base="https://generativelanguage.googleapis.com/v1beta/openai/",
    api_key=GEMINI_API_KEY,
)
```

## OpenRouter 모델 사용하기 [[using-openrouter-models]]

OpenRouter는 통합된 OpenAI 호환 API를 통해 다양한 언어 모델에 대한 접근을 제공합니다.
적절한 베이스 URL을 설정하여 [OpenAIModel](/docs/smolagents/main/ko/reference/models#smolagents.OpenAIModel)을 사용해 OpenRouter에 연결할 수 있습니다.

먼저, 필요한 의존성을 설치합니다:
```bash
pip install 'smolagents[openai]'
```

그다음, [OpenRouter API 키를 얻고](https://openrouter.ai/keys) 코드에서 설정합니다:
```python
OPENROUTER_API_KEY = <YOUR-OPENROUTER-API-KEY>
```

이제 `OpenAIModel` 클래스를 사용하여 OpenRouter에서 사용 가능한 모든 모델을 초기화할 수 있습니다:
```python
from smolagents import OpenAIModel

model = OpenAIModel(
    # OpenRouter에서 사용 가능한 모든 모델 ID를 사용할 수 있습니다
    model_id="openai/gpt-4o",
    # OpenRouter API 베이스 URL
    api_base="https://openrouter.ai/api/v1",
    api_key=OPENROUTER_API_KEY,
)
```

## xAI의 Grok 모델 사용하기 [[using-xais-grok-models]]

xAI의 Grok 모델은 [LiteLLMModel](/docs/smolagents/main/ko/reference/models#smolagents.LiteLLMModel)을 통해 접근할 수 있습니다.

일부 모델("grok-4" 및 "grok-3-mini" 등)은 `stop` 매개변수를 지원하지 않으므로,
API 호출에서 이를 제외하기 위해 `REMOVE_PARAMETER`를 사용해야 합니다.

먼저, 필요한 의존성을 설치합니다:
```bash
pip install smolagents[litellm]
```

그다음, [xAI API 키를 얻고](https://console.x.ai/) 코드에서 설정합니다:
```python
XAI_API_KEY = <YOUR-XAI-API-KEY>
```

이제 `LiteLLMModel` 클래스를 사용하여 Grok 모델을 초기화하고 해당되는 경우 `stop` 매개변수를 제거할 수 있습니다:
```python
from smolagents import LiteLLMModel, REMOVE_PARAMETER

# Grok-4 사용
model = LiteLLMModel(
    model_id="xai/grok-4",
    api_key=XAI_API_KEY,
    stop=REMOVE_PARAMETER,  # grok-4 모델이 이를 지원하지 않으므로 stop 매개변수 제거
    temperature=0.7
)

# 또는 Grok-3-mini 사용
model_mini = LiteLLMModel(
    model_id="xai/grok-3-mini",
    api_key=XAI_API_KEY,
    stop=REMOVE_PARAMETER,  # grok-3-mini 모델이 이를 지원하지 않으므로 stop 매개변수 제거
    max_tokens=1000
)
```


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/examples/using_different_models.md" />

### 좋은 에이전트 구축하기[[building-good-agents]]
https://huggingface.co/docs/smolagents/main/ko/tutorials/building_good_agents.md

# 좋은 에이전트 구축하기[[building-good-agents]]


성공하는 에이전트와 실패하는 에이전트 사이에는 큰 차이가 있습니다.
성공하는 에이전트는 어떻게 만들 수 있을까요?
이 가이드에서 에이전트 구축의 핵심 원칙들을 소개하겠습니다.

> [!TIP]
> 에이전트 구축이 처음이라면 먼저 [에이전트 소개](../conceptual_guides/intro_agents)와 [안내서](../guided_tour)를 읽어보세요.

### 최고의 에이전트 시스템은 가장 단순합니다: 워크플로우를 최대한 단순하게 만드세요[[the-best-agentic-systems-are-the-simplest:-simplify-the-workflow-as-much-as-you-can]]

워크플로우에 LLM에게 어느 정도의 자율성을 부여하는 것은 오류가 발생할 위험이 있습니다.

잘 설계된 에이전트 시스템은 오류를 기록하고 다시 시도하는 기능을 통해 LLM이 자신의 실수를 교정할 수 있게 해줍니다. 그렇다고 해도 처음부터 LLM이 실수하지 않도록 워크플로우를 간단하게 만드는 것이 훨씬 효과적입니다.

[에이전트 소개](../conceptual_guides/intro_agents)의 예시를 다시 살펴보겠습니다: 서핑 여행사 이용자들의 문의에 대응하는 봇입니다.
새로운 서핑 스팟에 대해 질문을 받을 때마다 에이전트가 "여행 거리 API"와 "날씨 API"에 각각 2번의 서로 다른 호출을 하도록 하는 대신, 두 API를 한 번에 호출하고 연결된 출력을 사용자에게 반환하는 함수인 "return_spot_information"이라는 하나의 통합된 도구를 만들 수 있습니다.

이렇게 하면 비용, 지연 시간, 오류 위험을 줄일 수 있습니다!

주요 지침은 다음과 같습니다: LLM 호출 횟수를 최대한 줄이세요.

이것은 몇 가지 결론으로 이어집니다:
- 가능하면 언제든지 두 개의 API 예시처럼 2개의 도구를 하나로 그룹화하세요.
- 가능하면 언제든지 로직은 에이전트의 결정보다는 결정론적 함수로 처리해야 합니다.

### LLM 엔진으로의 정보 흐름을 개선하세요[[improve-the-information-flow-to-the-llm-engine]]

LLM은 쪽지를 통해서만 소통할 수 있는 밀폐된 방 안의 *똑똑한* 로봇이라고 생각하면 됩니다.

프롬프트에 명시하지 않으면 무슨 일이 일어났는지 전혀 알 수 없습니다.

그러니까 일단 작업을 아주 명확하게 정의하는 것부터 시작하세요!
에이전트는 LLM으로 작동하기 때문에, 작업을 설명하는 방식이 조금만 달라져도 결과가 완전히 바뀔 수 있습니다.

그 다음엔 도구에서 에이전트로 정보가 잘 전달되도록 개선해야 합니다.

구체적으로는 이렇게 하세요:
- 각 도구는 LLM에게 도움이 될 만한 정보를 모두 기록해야 합니다.(도구의 `forward` 메서드 안에서 `print`문을 쓰기만 하면 됩니다.)
  - 특히 도구 실행 오류에 대한 자세한 정보를 기록하면 큰 도움이 됩니다!

예를 들어 위치와 날짜-시간을 받아서 날씨 데이터를 가져오는 도구를 보겠습니다:

먼저 좋지 않은 버전입니다:
```python
import datetime
from smolagents import tool

def get_weather_report_at_coordinates(coordinates, date_time):
    # 더미 함수, [섭씨 온도, 0-1 척도의 비 올 확률, 미터 단위 파도 높이] 리스트를 반환
    return [28.0, 0.35, 0.85]

def convert_location_to_coordinates(location):
    # 더미 좌표를 반환
    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`에 사용해야 하는 형식에 대한 정확한 설명이 없습니다.
- 위치를 어떻게 지정해야 하는지에 대한 세부 정보가 없습니다.
- 위치가 적절한 형식이 아니거나 `date_time`이 제대로 형식화되지 않은 경우와 같은 실패 사례를 명시적으로 기록할 수 있는 로깅 메커니즘이 없습니다.
- 출력 형식을 이해하기 어렵습니다.

도구 호출이 실패하면 메모리에 로깅된 오류 추적이 LLM이 도구를 역설계하여 오류를 수정하는 데 도움이 될 수 있습니다. 하지만 왜 그렇게 많은 무거운 작업을 맡겨야 할까요?

이 도구를 구축하는 더 나은 방법은 다음과 같습니다:
```python
@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의 부담을 덜어주려면 이런 질문을 해보세요: "만약 내가 아무것도 모르는 상태에서 이 도구를 처음 사용한다면, 실수했을 때 스스로 고치기가 얼마나 쉬울까?"

### 에이전트에 더 많은 매개변수 제공[[give-more-arguments-to-the-agent]]

작업을 설명하는 단순한 문자열 외에 에이전트에 추가 객체를 전달하려면 `additional_args` 매개변수를 사용하여 모든 유형의 객체를 전달할 수 있습니다:

```py
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` 매개변수를 통해 에이전트가 활용할 수 있도록 원하는 이미지나 문자열을 전달할 수 있습니다.

## 에이전트 디버깅 방법[[how-to-debug-your-agent]]

### 1. 더 강력한 LLM 사용[[use-a-stronger-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. 더 많은 정보나 구체적인 지침 제공[[provide-more-information-or-specific-instructions]]

더 자세하게 안내해준다면 성능이 낮은 모델도 충분히 사용할 수 있습니다.

모델의 관점에서 생각해보세요: 내가 모델이 되어서 이 작업을 해결해야 한다면, 지금 주어진 정보(시스템 프롬프트 + 작업 설명 + 도구 설명)만으로도 충분할까요?

더 구체적인 안내가 필요할까요?

- 지침이 항상 에이전트에게 주어져야 하는 경우(일반적으로 시스템 프롬프트가 작동한다고 이해하는 것처럼): 에이전트 초기화 시 `instructions` 매개변수 아래에 문자열로 전달할 수 있습니다.
- 해결할 특정 작업에 관한 것이라면: 이 모든 세부 사항을 작업에 추가하세요. 작업은 수십 페이지처럼 매우 길 수 있습니다.
- 특정 도구 사용 방법에 관한 것이라면: 해당 도구의 `description` 속성에 포함시키세요.

### 3. 프롬프트 템플릿 변경 (일반적으로 권장되지 않음)[[change-the-prompt-templates-(generally-not-advised)]]

위의 방법들로도 부족하다면 에이전트의 프롬프트 템플릿을 직접 수정할 수 있습니다.

작동 원리를 살펴보겠습니다. [CodeAgent]의 기본 프롬프트 템플릿을 예로 들어보겠습니다(제로샷 예제는 생략하고 간단히 정리했습니다).

```python
print(agent.prompt_templates["system_prompt"])
```
Here is what you get:
```text
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`에만 해당하며, 승인된 import 목록을 삽입하려면: `"{{authorized_imports}}"`

그런 다음 다음과 같이 시스템 프롬프트를 변경할 수 있습니다:

```py
agent.prompt_templates["system_prompt"] = agent.prompt_templates["system_prompt"] + "\nHere you go!"
```

이는 [ToolCallingAgent](/docs/smolagents/main/ko/reference/agents#smolagents.ToolCallingAgent)에서도 작동합니다.

하지만 일반적으로 다음과 같이 에이전트 초기화 시 `instructions` 매개변수를 전달하는 것이 더 간단합니다:
```py
agent = CodeAgent(tools=[], model=InferenceClientModel(model_id=model_id), instructions="Always talk like a 5 year old.")
```

### 4. 추가 계획[[extra-planning]]

일반적인 작업 단계들 중간중간에 에이전트가 추가로 계획을 세우는 단계를 넣을 수 있습니다. 이때는 도구를 사용하지 않고, LLM이 현재까지 파악한 정보를 정리하고 그 정보를 토대로 앞으로의 계획을 다시 점검하게 됩니다.

```py
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?",
)
```

<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/tutorials/building_good_agents.md" />

### 📚 에이전트 메모리 관리[[-manage-your-agents-memory]]
https://huggingface.co/docs/smolagents/main/ko/tutorials/memory.md

# 📚 에이전트 메모리 관리[[-manage-your-agents-memory]]


결국 에이전트는 도구와 프롬프트로 이루어진 단순한 구성요소로 정의됩니다.
그리고 무엇보다 중요한 것은 에이전트가 과거 단계의 메모리를 가지고 있어 계획, 실행, 오류의 이력을 추적한다는 점입니다.

### 에이전트 메모리 재생[[replay-your-agents-memory]]

과거 실행된 에이전트를 확인하기 위한 몇 가지 기능을 제공합니다.

[계측 가이드](./inspect_runs)에서 언급한 바와 같이, 에이전트 실행을 계측하여 특정 단계를 확대하거나 축소할 수 있는 우수한 UI로 시각화할 수 있습니다.

또한 다음과 같이 `agent.replay()`를 사용할 수도 있습니다.

에이전트를 실행한 후,
```py
from smolagents import InferenceClientModel, CodeAgent

agent = CodeAgent(tools=[], model=InferenceClientModel(), verbosity_level=0)

result = agent.run("What's the 20th Fibonacci number?")
```

이 마지막 실행을 다시 재생하고 싶다면, 다음 코드를 사용하면 됩니다.
```py
agent.replay()
```

### 에이전트 메모리 동적 변경[[dynamically-change-the-agents-memory]]

많은 고급 사용 사례에서는 에이전트의 메모리를 동적으로 수정해야 합니다.

에이전트의 메모리는 다음과 같이 접근할 수 있습니다.


```py
from smolagents import ActionStep

system_prompt_step = agent.memory.system_prompt
print("The system prompt given to the agent was:")
print(system_prompt_step.system_prompt)

task_step = agent.memory.steps[0]
print("\n\nThe first task step was:")
print(task_step.task)

for step in agent.memory.steps:
    if isinstance(step, ActionStep):
        if step.error is not None:
            print(f"\nStep {step.step_number} got this error:\n{step.error}\n")
        else:
            print(f"\nStep {step.step_number} got these observations:\n{step.observations}\n")
```

`agent.memory.get_full_steps()`를 사용하여 전체 단계를 딕셔너리 형태로 가져올 수 있습니다.

또한 단계 콜백을 사용하여 에이전트의 메모리를 동적으로 변경할 수도 있습니다.

단계 콜백은 인자로 `agent` 객체 자체에 접근할 수 있으므로, 위에서 설명한 것처럼 모든 메모리 단계에 접근하여 필요한 경우 수정할 수 있습니다. 예를 들어, 웹 브라우저 에이전트가 수행하는 각 단계의 스크린샷을 관찰하고 있다고 가정해 보겠습니다. 이 경우 최신 스크린샷은 유지하면서 토큰 비용을 절약하기 위해 이전 단계의 이미지를 메모리에서 제거할 수 있습니다.

이 경우 다음과 같은 코드를 사용할 수 있습니다.
_주의: 이 코드는 간결함을 위해 일부 임포트 및 객체 정의가 생략된 불완전한 예시입니다. 전체 작동 버전의 코드는 [원본 스크립트](https://github.com/huggingface/smolagents/blob/main/src/smolagents/vision_web_browser.py)에서 확인하세요._

```py
import helium
from PIL import Image
from io import BytesIO
from time import sleep

def update_screenshot(memory_step: ActionStep, agent: CodeAgent) -> None:
    sleep(1.0)  # JavaScript 애니메이션이 완료된 후에 스크린샷을 찍도록 합니다.
    driver = helium.get_driver()
    latest_step = memory_step.step_number
    for previous_memory_step in agent.memory.steps:  # 이전 스크린샷을 로그에서 제거하여 처리 과정을 간소화합니다.
        if isinstance(previous_memory_step, ActionStep) and previous_memory_step.step_number <= latest_step - 2:
            previous_memory_step.observations_images = None
    png_bytes = driver.get_screenshot_as_png()
    image = Image.open(BytesIO(png_bytes))
    memory_step.observations_images = [image.copy()]
```

그 다음 에이전트를 초기화할 때 이 함수를 다음과 같이 `step_callbacks` 인수에 전달해야 합니다.

```py
CodeAgent(
    tools=[WebSearchTool(), go_back, close_popups, search_item_ctrl_f],
    model=model,
    additional_authorized_imports=["helium"],
    step_callbacks=[update_screenshot],
    max_steps=20,
    verbosity_level=2,
)
```

전체 작동 예시는 [비전 웹 브라우저 코드](https://github.com/huggingface/smolagents/blob/main/src/smolagents/vision_web_browser.py)에서 확인할 수 있습니다.

### 에이전트를 단계별로 실행[[run-agents-one-step-at-a-time]]

이 기능은 도구 호출에 오랜 시간이 걸리는 경우에 유용합니다.
에이전트를 한 단계씩 실행하면서 각 단계에서 메모리를 업데이트할 수 있습니다.

```py
from smolagents import InferenceClientModel, CodeAgent, ActionStep, TaskStep

agent = CodeAgent(tools=[], model=InferenceClientModel(), verbosity_level=1)
agent.python_executor.send_tools({**agent.tools})
print(agent.memory.system_prompt)

task = "What is the 20th Fibonacci number?"

# 필요에 따라 다른 에이전트의 메모리를 불러와 메모리를 수정할 수 있습니다.
# agent.memory.steps = previous_agent.memory.steps

# 새로운 작업을 시작합니다!
agent.memory.steps.append(TaskStep(task=task, task_images=[]))

final_answer = None
step_number = 1
while final_answer is None and step_number <= 10:
    memory_step = ActionStep(
        step_number=step_number,
        observations_images=[],
    )
    # 한 단계를 실행합니다.
    final_answer = agent.step(memory_step)
    agent.memory.steps.append(memory_step)
    step_number += 1

    # 필요한 경우 메모리를 수정할 수도 있습니다
    # 예를 들어 최신 단계를 업데이트 하려면 다음과 같이 처리합니다:
    # agent.memory.steps[-1] = ...

print("The final answer is:", final_answer)
```


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/ko/tutorials/memory.md" />
