> This is a page from the ElevenLabs documentation. For an index of the documentation, fetch https://elevenlabs.io/docs/llms.txt.

# 코드로 에이전트 관리

## 개요

에이전트는 여러 부분으로 구성됩니다. 구성은 큰 중첩 객체이며, 웹훅 및 클라이언트 도구는 별도로 생성한 뒤 ID로 연결하고, 워크플로는 동일한 도구 ID를 참조합니다. 이를 수동으로 처리하려면 각 도구를 만들고, 반환된 ID를 에이전트 구성과 워크플로 노드에 복사한 다음 에이전트를 생성하거나 업데이트해야 합니다. 누락된 ID는 에이전트가 실행된 후에야 발견되며, 같은 스크립트를 두 번 실행하면 중복 도구가 생성됩니다.

Python 및 JavaScript SDK의 `Agent` 빌더는 설정, 사용하는 [도구](/docs/ko/eleven-agents/customization/agents-as-code/tools), [워크플로](/docs/ko/eleven-agents/customization/agents-as-code/workflows)를 하나의 정의로 설명합니다. 이후 `agents.push()`가 모든 도구와 에이전트를 생성하거나 업데이트하고, 도구 ID를 자동으로 채웁니다.

다음과 같은 용도로 사용할 수 있습니다.

* 에이전트를 코드로 정의하고 다른 코드 변경과 마찬가지로 변경 사항을 검토합니다.
* API 키 없이 CI에서 에이전트를 검증합니다.
* 배포 스크립트를 안전하게 다시 실행합니다. 변경되지 않은 도구는 건드리지 않으며, 중복 생성도 없습니다.
* [CLI](/docs/ko/eleven-agents/operate/cli)와 같은 구조로 에이전트를 리포지토리에 보관하고, 어느 쪽으로든 작업합니다.

> **Note**
>
> 빌더는 SDK에서 실행됩니다. `push()`와 `pull()`은 기존 에이전트 및 도구 엔드포인트를 호출하며,
> 이들이 생성하는 모든 항목은 대시보드에서 열어 편집할 수 있습니다.

## 요구 사항

* Python: `elevenlabs` 패키지. 빌더는 `elevenlabs.agent_builder`에서, 도구는 `elevenlabs.agent_tools`에서, 워크플로는 `elevenlabs.agent_workflows`에서 가져옵니다.
* JavaScript: `@elevenlabs/elevenlabs-js` 패키지. 모든 항목은 패키지 루트에서 내보냅니다.

## 에이전트 정의 및 배포

`Agent(name, options)`는 에이전트 이름과 설정을 받습니다. 이 에이전트에는 워크플로에서 사용하는 웹훅 도구와 내장 통화 종료 도구가 있습니다.

```python
from elevenlabs import ElevenLabs
from elevenlabs.agent_builder import Agent
from elevenlabs.agent_tools import Schema, SystemTool, Tool
from elevenlabs.agent_workflows import Workflow

elevenlabs = ElevenLabs()

get_order = (
    Tool.webhook("get_order", "Look up an order by its number")
    .get("https://api.example.com/orders/{order_id}")
    .path_param("order_id", Schema.string().describe("The order number, e.g. A-1042"))
)

wf = Workflow()
(
    wf.converse("triage", "Find out what the caller needs")
    .when("Caller gave an order number")
    .tool("lookup", [get_order])
    .on_success()
    .converse("resolve", "Explain the order status")
)

agent = Agent(
    "Support line",
    prompt="You are a support agent for Acme.",
    first_message="Hi, how can I help?",
    llm="gemini-2.0-flash",
    voice_id="21m00Tcm4TlvDq8ikWAM",
    tools=[SystemTool.end_call()],
    workflow=wf,
)

result = elevenlabs.conversational_ai.agents.push(agent)
print(result.agent_id, result.tools["get_order"].action)  # "created"
```

```typescript
import {
  Agent,
  ElevenLabsClient,
  Schema,
  SystemTool,
  Tool,
  Workflow,
} from "@elevenlabs/elevenlabs-js";

const elevenlabs = new ElevenLabsClient();

const getOrder = Tool.webhook("get_order", "Look up an order by its number")
  .get("https://api.example.com/orders/{order_id}")
  .pathParam("order_id", Schema.string().describe("The order number, e.g. A-1042"));

const wf = new Workflow();
wf.converse("triage", "Find out what the caller needs")
  .when("Caller gave an order number")
  .tool("lookup", [getOrder])
  .onSuccess()
  .converse("resolve", "Explain the order status");

const agent = new Agent("Support line", {
  prompt: "You are a support agent for Acme.",
  firstMessage: "Hi, how can I help?",
  llm: "gemini-2.0-flash",
  voiceId: "21m00Tcm4TlvDq8ikWAM",
  tools: [SystemTool.endCall()],
  workflow: wf,
});

const result = await elevenlabs.conversationalAi.agents.push(agent);
console.log(result.agentId, result.tools.get_order.action); // "created"
```

워크플로의 도구 노드는 ID 대신 `Tool` 객체 자체를 받습니다. `push()`는 `get_order`를 생성한 다음 새 ID를 노드에 기록합니다. 워크플로에서만 사용하는 도구는 `tools`에도 별도로 나열할 필요가 없습니다.

에이전트 ID가 없으면 `agents.create()`와 마찬가지로 `push()`를 호출할 때마다 새 에이전트를 생성합니다. 반환된 ID를 보관하고 이후 배포 시 전달하거나, 자동으로 ID를 기록하는 [프로젝트](#keep-agents-in-version-control)를 사용하세요.

```python
elevenlabs.conversational_ai.agents.push(agent, agent_id=result.agent_id)
```

```typescript
await elevenlabs.conversationalAi.agents.push(agent, { agentId: result.agentId });
```

Python의 `AsyncElevenLabs`에도 `await`할 수 있는 동일한 `push()`와 `pull()`이 있습니다.

## 에이전트 옵션

타입이 지정된 옵션은 대부분의 에이전트에서 변경하는 설정을 다룹니다. 각 옵션은 에이전트 구성의 필드에 매핑됩니다.

| Python                  | JavaScript            | 설정 대상                                                                                        |
| ----------------------- | --------------------- | -------------------------------------------------------------------------------------------- |
| `prompt`                | `prompt`              | 시스템 프롬프트, `conversation_config.agent.prompt.prompt`.                                         |
| `first_message`         | `firstMessage`        | 에이전트가 처음 말하는 내용, `conversation_config.agent.first_message`.                                  |
| `language`              | `language`            | `"en"`과 같은 에이전트 언어, `conversation_config.agent.language`.                                    |
| `llm`, `temperature`    | `llm`, `temperature`  | [LLM](/docs/ko/eleven-agents/customization/llm) 및 해당 온도, `conversation_config.agent.prompt`. |
| `voice_id`, `tts_model` | `voiceId`, `ttsModel` | 음성과 텍스트 음성 변환 모델, `conversation_config.tts`.                                                 |
| `tags`                  | `tags`                | 에이전트 태그.                                                                                     |
| `tools`                 | `tools`               | 에이전트가 사용할 수 있는 `Tool` 객체. [도구](#tools)를 참조하세요.                                               |
| `tool_ids`              | `toolIds`             | 있는 그대로 연결할 기존 도구의 ID. `push()`는 이를 생성하거나 변경하지 않습니다.                                          |
| `workflow`              | `workflow`            | [워크플로](/docs/ko/eleven-agents/customization/agents-as-code/workflows).                       |
| `conversation_config`   | `conversationConfig`  | 기타 모든 대화 설정. [기타 설정](#other-settings)을 참조하세요.                                                |
| `platform_settings`     | `platformSettings`    | 개인정보 보호 또는 위젯 설정과 같은 플랫폼 설정.                                                                 |

`update()`는 에이전트 생성 후 옵션을 변경하며, `add_tool()` / `addTool()`은 도구 하나를 추가합니다.

```python
agent.update(first_message="Hello! What can I do for you?", temperature=0.3)
agent.add_tool(SystemTool.skip_turn())
```

```typescript
agent.update({ firstMessage: "Hello! What can I do for you?", temperature: 0.3 });
agent.addTool(SystemTool.skipTurn());
```

### 기타 설정

`conversation_config` / `conversationConfig` 및 `platform_settings` / `platformSettings`는 타입 지정 옵션에서 다루지 않는 모든 설정을 `agents.create()`와 동일한 형태로 받습니다. Python에서는 SDK가 생성한 모델이나 snake_case 키가 있는 딕셔너리를 사용할 수 있습니다. 타입 지정 옵션과 병합되므로 둘 다 사용할 수 있습니다.

```python
agent = Agent(
    "Support line",
    prompt="You are a support agent for Acme.",
    conversation_config={"turn": {"turn_timeout": 7}},
    platform_settings={"privacy": {"record_voice": False}},
)
```

```typescript
const agent = new Agent("Support line", {
  prompt: "You are a support agent for Acme.",
  conversationConfig: { turn: { turnTimeout: 7 } },
  platformSettings: { privacy: { recordVoice: false } },
});
```

`prompt`와 `conversation_config.agent.prompt.prompt`처럼 원시 설정과 타입 지정 옵션이 같은 필드를 설정하면, 하나가 조용히 우선 적용되는 대신 검증에서 `option_conflict`를 보고합니다.

## 도구

`tools`는 [코드로 도구 관리](/docs/ko/eleven-agents/customization/agents-as-code/tools)의 모든 도구 유형을 받으며, 각 유형은 서로 다른 방식으로 처리됩니다.

| 도구             | `push()`의 동작                                                                          |
| -------------- | ------------------------------------------------------------------------------------- |
| 웹훅 및 클라이언트 도구  | 도구를 생성하거나 업데이트한 후 ID로 에이전트에 연결합니다.                                                    |
| 시스템 도구         | 에이전트의 내장 도구에 추가합니다. 시스템 도구는 에이전트 구성의 일부이므로 도구 요청을 만들지 않습니다.                           |
| 워크플로에서 사용하는 도구 | 도구를 생성하거나 업데이트한 후, 이를 사용하는 각 도구 노드 및 각 에이전트 노드의 `tool_ids` / `toolIds`에 해당 ID를 기록합니다. |

`agent.tools()`는 에이전트와 워크플로에서 사용하는 모든 웹훅 및 클라이언트 도구, 즉 `push()`가 생성하고 업데이트하는 집합을 반환합니다. 서로 다른 두 도구는 이름을 공유할 수 없지만, 동일한 `Tool` 객체는 여러 위치에서 사용할 수 있습니다. 한 번만 배포되고 하나의 ID를 받습니다.

### push가 도구를 매칭하는 방식

도구 이름은 워크스페이스 내에서 고유하지 않으므로, `push()`는 전체 워크스페이스에서 이름으로 도구를 찾지 않습니다. 에이전트 ID가 있으면 해당 에이전트가 이미 사용하는 도구를 나열하고 이름으로 매칭합니다. 다른 에이전트만 사용하는 같은 이름의 도구는 절대 건드리지 않으므로, 의도하지 않은 에이전트를 변경할 수 없습니다. [프로젝트](#keep-agents-in-version-control)를 사용하면 대신 프로젝트에 기록된 ID로 도구를 매칭합니다.

각 도구에 대해 `push()`는 다음을 수행합니다.

1. 기존 도구가 이미 정의와 일치하면 그대로 둡니다.
2. 다르면 업데이트합니다.
3. 일치하는 도구가 없으면 생성합니다.

### 배포 결과

`push()`는 에이전트와 각 도구에 대해 수행한 작업을 도구 이름을 키로 하여 반환합니다.

| 필드                     | 값                                                        |
| ---------------------- | -------------------------------------------------------- |
| `agent_id` / `agentId` | 에이전트 ID.                                                 |
| `action`               | `"created"` 또는 `"updated"`.                              |
| `tools[name].id`       | 도구 ID.                                                   |
| `tools[name].action`   | `"created"`, `"updated"`, `"unchanged"` 또는 `"detached"`. |

`"detached"` 도구는 이번 배포 전에는 에이전트가 사용했지만 이제는 사용하지 않는 도구입니다. 다른 에이전트가 계속 사용할 수 있으므로 에이전트에서는 제거되지만 삭제되지는 않습니다.

### 실패한 배포

`push()`는 요청을 보내기 전에 에이전트를 검증하므로, 유효하지 않은 에이전트는 아무것도 기록하지 않습니다. 일부 도구가 생성된 후처럼 요청이 중간에 실패하면 `push()`는 `AgentPushError`를 발생시키거나 throw합니다. 이 오류의 `result`에는 이미 기록된 도구와 그 ID가 나열되므로, 추적되지 않은 항목이 남지 않습니다. 원래 오류가 그 원인입니다.

```python
from elevenlabs.agent_builder import AgentPushError

try:
    elevenlabs.conversational_ai.agents.push(agent, agent_id=agent_id)
except AgentPushError as err:
    print(err)  # what failed, and why
    for name, tool in err.result.tools.items():
        print(name, tool.id, tool.action)
```

```typescript
import { AgentPushError } from "@elevenlabs/elevenlabs-js";

try {
  await elevenlabs.conversationalAi.agents.push(agent, { agentId });
} catch (err) {
  if (err instanceof AgentPushError) {
    console.error(err.message); // what failed, and why
    for (const [name, tool] of Object.entries(err.result.tools))
      console.error(name, tool.id, tool.action);
  } else {
    throw err;
  }
}
```

### 배포 옵션

| Python                | JavaScript           | 동작                                                                                      |
| --------------------- | -------------------- | --------------------------------------------------------------------------------------- |
| `agent_id`            | `agentId`            | 이 에이전트를 업데이트합니다. 없으면 새 에이전트가 생성됩니다.                                                     |
| `project`             | `project`            | [프로젝트](#keep-agents-in-version-control)를 사용해 ID를 매칭하고 기록합니다. `agent_id`와 함께 사용할 수 없습니다. |
| `branch_id`           | `branchId`           | 기본 브랜치 대신 이 [브랜치](/docs/ko/eleven-agents/operate/versioning)를 업데이트합니다.                  |
| `version_description` | `versionDescription` | 버전 관리가 활성화된 에이전트의 새 버전을 설명합니다.                                                          |
| `request_options`     | `requestOptions`     | `push()`가 수행하는 모든 요청에 전달됩니다.                                                            |

## 직접 요청 만들기

`push()`는 선택 사항입니다. `build()`는 도구 이름을 키로 하여 에이전트가 사용하는 도구의 ID를 전달받고, `agents.create()` 및 `agents.update()`용 요청 본문을 반환합니다. 먼저 원하는 방식으로 도구를 생성하려면 이를 사용하세요.

```python
order_tool = elevenlabs.conversational_ai.tools.create(request=get_order.build())

created = elevenlabs.conversational_ai.agents.create(**agent.build(tool_ids={"get_order": order_tool.id}))
```

```typescript
const orderTool = await elevenlabs.conversationalAi.tools.create(getOrder.build());

const created = await elevenlabs.conversationalAi.agents.create(
  agent.build({ toolIds: { get_order: orderTool.id } })
);
```

맵에 도구 ID가 없으면 `build()`는 해당 도구의 이름을 포함한 `unresolved_tool` 문제를 보고합니다.

## 에이전트를 버전 관리에 보관하기

`AgentProject`는 [CLI](/docs/ko/eleven-agents/operate/cli)의 프로젝트 구조를 읽고 쓰므로, 동일한 리포지토리를 SDK 및 `elevenlabs agents push`와 함께 사용할 수 있습니다.

| 파일               | 내용                               |
| ---------------- | -------------------------------- |
| `agents.json`    | 각 에이전트의 구성 파일과 배포 후 ID 및 브랜치.    |
| `tools.json`     | 각 웹훅 및 클라이언트 도구의 구성 파일과 배포 후 ID. |
| `agent_configs/` | 에이전트별 파일 하나, API의 와이어 형식.        |
| `tool_configs/`  | 도구별 파일 하나, API의 와이어 형식.          |

프로젝트를 `push()`에 전달하면 보관 중인 에이전트 ID가 아닌 프로젝트에 기록된 ID로 에이전트와 도구를 매칭합니다. 전송한 구성과 새 ID를 프로젝트에 다시 기록하므로, 같은 스크립트를 다시 실행하면 다른 에이전트를 만드는 대신 기존 에이전트를 업데이트합니다.

```python
from elevenlabs.agent_builder import AgentProject

project = AgentProject.open(".")  # an empty directory works too
elevenlabs.conversational_ai.agents.push(agent, project=project)
```

```typescript
import { AgentProject } from "@elevenlabs/elevenlabs-js";

const project = await AgentProject.open("."); // Node.js; an empty directory works too
await elevenlabs.conversationalAi.agents.push(agent, { project });
```

### 프로젝트에 저장된 에이전트 편집

`project.agent(name)`은 구성 파일에서 에이전트를 `Agent`로 로드합니다. `tools.json`에 나열된 도구는 `Tool` 객체로 반환되고, 다른 도구의 ID는 `tool_ids` / `toolIds`에 그대로 유지됩니다. 빌더가 모델링하지 않는 설정도 보존되므로, 다시 배포해도 변경한 항목만 바뀝니다.

```python
support = project.agent("Support line")
support.update(first_message="Hello!")
elevenlabs.conversational_ai.agents.push(support, project=project)
```

```typescript
const support = project.agent("Support line");
support.update({ firstMessage: "Hello!" });
await elevenlabs.conversationalAi.agents.push(support, { project });
```

`agent.workflow`를 통해 에이전트 워크플로를 [워크플로 빌더](/docs/ko/eleven-agents/customization/agents-as-code/workflows)로 편집할 수 있으며, 해당 도구 노드는 동일한 `Tool` 객체를 가리킵니다.

### 대시보드에서 에이전트 가져오기

`agents.pull(agent_id)`는 기존 에이전트를 웹훅 및 클라이언트 도구가 `Tool` 객체인 `Agent`로 로드합니다. 프로젝트를 사용하면 에이전트와 도구를 프로젝트에도 기록하고 ID를 저장하므로, 대시보드에서 만든 에이전트를 리포지토리로 옮길 수 있습니다.

```python
support = elevenlabs.conversational_ai.agents.pull("agent_123", project=project)
```

```typescript
const support = await elevenlabs.conversationalAi.agents.pull("agent_123", { project });
```

### CI에서 검증

검증에는 API 키가 필요하지 않으므로, CI 작업은 각 풀 리퀘스트에서 프로젝트의 모든 에이전트를 확인하고 병합 시 배포할 수 있습니다.

```python
from elevenlabs.agent_builder import AgentProject

project = AgentProject.open(".")
for agent in project.agents():
    agent.validate()
```

```typescript
import { AgentProject } from "@elevenlabs/elevenlabs-js";

const project = await AgentProject.open(".");
for (const agent of project.agents()) agent.validate();
```

> **Note**
>
> 현재 프로젝트는 JSON 구성 파일만 지원합니다. `agents.json`이 YAML 또는 TOML 구성을 가리키는 경우,
> 프로젝트를 열면 `AgentProjectError`가 발생합니다.

## 검증

`validate()`는 도구 ID 없이도 에이전트와 에이전트가 사용하는 모든 항목을 확인합니다. `build()`와 `push()`는 먼저 이를 호출합니다. 모든 문제를 나열한 단일 `AgentValidationError`를 발생시키거나 throw하며, 각 문제에는 `code`, `message`, 관련 부분의 `path`가 포함됩니다.

```python
from elevenlabs.agent_builder import AgentValidationError

try:
    agent.validate()
except AgentValidationError as err:
    for issue in err.issues:
        print(issue.code, issue.path, issue.message)
```

```typescript
import { AgentValidationError } from "@elevenlabs/elevenlabs-js";

try {
  agent.validate();
} catch (err) {
  if (err instanceof AgentValidationError) {
    for (const issue of err.issues) console.error(issue.code, issue.path, issue.message);
  } else {
    throw err;
  }
}
```

| 코드                        | 문제                                                                                                     |
| ------------------------- | ------------------------------------------------------------------------------------------------------ |
| `missing_name`            | 에이전트에 이름이 없습니다.                                                                                        |
| `option_conflict`         | 타입 지정 옵션과 원시 구성이 같은 필드를 설정합니다.                                                                         |
| `invalid_config`          | 원시 설정에 API 스키마가 허용하지 않는 값이 있습니다.                                                                       |
| `duplicate_tool_name`     | 서로 다른 두 도구의 이름이 같습니다.                                                                                  |
| `invalid_tool`            | 도구가 [도구 검증](/docs/ko/eleven-agents/customization/agents-as-code/tools#validation)을 통과하지 못했습니다.         |
| `invalid_workflow`        | 워크플로가 [워크플로 검증](/docs/ko/eleven-agents/customization/agents-as-code/workflows#validation)을 통과하지 못했습니다. |
| `system_tool_in_workflow` | 워크플로 도구 노드가 시스템 도구를 사용합니다. 대신 시스템 도구를 에이전트의 `tools`에 추가하세요.                                            |
| `unresolved_tool`         | `build()`에 에이전트가 사용하는 도구의 ID가 제공되지 않았습니다.                                                              |

프롬프트가 없는 에이전트는 검증 실패를 일으키지 않는 `missing_prompt` 경고로 보고됩니다. 경고를 받으려면 `validate()`에 `on_warning` / `onWarning`을 전달하세요.