코드 인터프리터 도구(CodeInterpreterTool)
코드 인터프리터 도구(CodeInterpreterTool)
에이전트가 스스로 Python 코드를 짜서 실행하고, 결과를 다음 의사결정에 쓸 수 있다면 문제 해결 범위가 크게 넓어집니다. CrewAI의 CodeInterpreterTool이 바로 그 역할을 하도록 설계된 도구인데요. 다만 이 문서를 읽는 시점에는 이 도구가 crewai-tools에서 제거되어 있다는 점을 먼저 짚고 넘어갑니다.
출처: 공식문서
본문
폐기됨(Deprecated):
CodeInterpreterTool은crewai-tools에서 제거되었습니다.Agent의allow_code_execution및code_execution_mode파라미터도 폐기되었어요. 안전하고 격리된 코드 실행을 위해서는 전용 샌드박스 서비스 — E2B 또는 Modal — 를 사용하세요.
설명
CodeInterpreterTool은 CrewAI 에이전트가 스스로 생성한 Python 3 코드를 실행할 수 있게 해 줍니다. 에이전트가 코드를 만들고, 실행하고, 결과를 얻고, 그 정보를 바탕으로 다음 결정·행동을 내리는 것이 특히 가치 있어요.
사용 방법은 몇 가지입니다.
Docker 컨테이너(권장)
주요 옵션입니다. 코드는 안전하고 격리된 Docker 컨테이너 안에서 실행되어 내용이 무엇이든 안전을 보장합니다. 시스템에 Docker가 설치·실행 중이어야 해요. 없다면 여기에서 설치할 수 있습니다.
샌드박스 환경
Docker를 쓸 수 없을 때 — 설치돼 있지 않거나 어떤 이유로 접근 불가 — 코드는 샌드박스라고 하는 제한된 Python 환경에서 실행됩니다. 이 환경은 매우 제한적이며 많은 모듈과 내장 함수에 엄격한 제한이 적용돼요.
안전하지 않은 실행(Unsafe Execution)
프로덕션에는 비권장입니다. 이 모드는 sys, os... 같은 위험한 모듈 호출을 포함한 모든 Python 코드를 실행하게 합니다. 활성화 방법은 여기에서 확인하세요.
로깅
CodeInterpreterTool은 선택된 실행 전략을 STDOUT으로 기록합니다.
설치
pip install 'crewai[tools]'
예제
from crewai import Agent, Task, Crew, Process
from crewai_tools import CodeInterpreterTool
# Initialize the tool
code_interpreter = CodeInterpreterTool()
# Define an agent that uses the tool
programmer_agent = Agent(
role="Python Programmer",
goal="Write and execute Python code to solve problems",
backstory="An expert Python programmer who can write efficient code to solve complex problems.",
tools=[code_interpreter],
verbose=True,
)
# Example task to generate and execute code
coding_task = Task(
description="Write a Python function to calculate the Fibonacci sequence up to the 10th number and print the result.",
expected_output="The Fibonacci sequence up to the 10th number.",
agent=programmer_agent,
)
# Create and run the crew
crew = Crew(
agents=[programmer_agent],
tasks=[coding_task],
verbose=True,
process=Process.sequential,
)
result = crew.kickoff()
에이전트를 만들 때 코드 실행을 직접 활성화할 수도 있습니다.
from crewai import Agent
# Create an agent with code execution enabled
programmer_agent = Agent(
role="Python Programmer",
goal="Write and execute Python code to solve problems",
backstory="An expert Python programmer who can write efficient code to solve complex problems.",
allow_code_execution=True, # This automatically adds the CodeInterpreterTool
verbose=True,
)
unsafe_mode 활성화
from crewai_tools import CodeInterpreterTool
code = """
import os
os.system("ls -la")
"""
CodeInterpreterTool(unsafe_mode=True).run(code=code)
파라미터
CodeInterpreterTool은 초기화 시 다음 파라미터를 받습니다.
- user_dockerfile_path: 옵션. 코드 인터프리터 컨테이너에 쓸 커스텀 Dockerfile 경로.
- user_docker_base_url: 옵션. 컨테이너 실행에 쓸 Docker 데몬 URL.
- unsafe_mode: 옵션. Docker 컨테이너나 샌드박스 대신 호스트 머신에서 직접 코드를 실행할지 여부. 기본값은
False. 주의해서 쓰세요! - default_image_tag: 옵션. 기본 Docker 이미지 태그. 기본값은
code-interpreter:latest.
에이전트와 함께 쓸 때, 에이전트가 제공해야 할 것:
- code: 필수. 실행할 Python 3 코드.
- libraries_used: 옵션. 코드에서 쓰는 설치 필요 라이브러리 목록. 기본값은
[].
에이전트 통합 예제
from crewai import Agent, Task, Crew
from crewai_tools import CodeInterpreterTool
# Initialize the tool
code_interpreter = CodeInterpreterTool()
# Define an agent that uses the tool
data_analyst = Agent(
role="Data Analyst",
goal="Analyze data using Python code",
backstory="""You are an expert data analyst who specializes in using Python
to analyze and visualize data. You can write efficient code to process
large datasets and extract meaningful insights.""",
tools=[code_interpreter],
verbose=True,
)
# Create a task for the agent
analysis_task = Task(
description="""
Write Python code to:
1. Generate a random dataset of 100 points with x and y coordinates
2. Calculate the correlation coefficient between x and y
3. Create a scatter plot of the data
4. Print the correlation coefficient and save the plot as 'scatter.png'
Make sure to handle any necessary imports and print the results.
""",
expected_output="The correlation coefficient and confirmation that the scatter plot has been saved.",
agent=data_analyst,
)
# Run the task
crew = Crew(
agents=[data_analyst],
tasks=[analysis_task],
verbose=True,
process=Process.sequential,
)
result = crew.kickoff()
구현 세부사항
CodeInterpreterTool은 Docker로 안전한 코드 실행 환경을 만듭니다.
class CodeInterpreterTool(BaseTool):
name: str = "Code Interpreter"
description: str = "Interprets Python3 code strings with a final print statement."
args_schema: Type[BaseModel] = CodeInterpreterSchema
default_image_tag: str = "code-interpreter:latest"
def _run(self, **kwargs) -> str:
code = kwargs.get("code", self.code)
libraries_used = kwargs.get("libraries_used", [])
if self.unsafe_mode:
return self.run_code_unsafe(code, libraries_used)
else:
return self.run_code_safety(code, libraries_used)
도구는 다음 단계를 수행합니다.
- Docker 이미지가 있는지 확인하고 없으면 빌드합니다.
- 현재 작업 디렉토리를 마운트한 Docker 컨테이너를 만듭니다.
- 에이전트가 지정한 필수 라이브러리를 설치합니다.
- 컨테이너에서 Python 코드를 실행합니다.
- 코드 실행 출력을 반환합니다.
- 컨테이너를 중지·제거해 정리합니다.
보안 고려사항
기본적으로 CodeInterpreterTool은 격리된 Docker 컨테이너에서 코드를 실행해 보안 계층을 제공합니다. 그래도 몇 가지 유의할 점이 있습니다.
- Docker 컨테이너는 현재 작업 디렉토리에 접근할 수 있어, 민감한 파일이 접근될 가능성이 있습니다.
- Docker 컨테이너를 쓸 수 없어 코드를 안전하게 실행해야 한다면 샌드박스 환경에서 실행됩니다. 보안상 임의 라이브러리 설치는 허용되지 않습니다.
unsafe_mode파라미터는 코드를 호스트 머신에서 직접 실행하게 하므로 신뢰할 수 있는 환경에서만 써야 합니다.- 에이전트가 임의 라이브러리를 설치하게 할 때는 주의하세요. 악성 코드가 포함될 수 있습니다.
결론
CodeInterpreterTool은 CrewAI 에이전트가 비교적 안전한 환경에서 Python 코드를 실행할 수 있게 해 주는 강력한 방법이었습니다. 에이전트가 코드를 작성·실행하게 함으로써 문제 해결 능력을 크게 넓히는데, 특히 데이터 분석, 계산, 그 밖의 계산 작업에서 유용합니다. 다만 현재 버전에서는 제거되었으므로 E2B·Modal 같은 샌드박스 서비스를 대안으로 쓰세요.