> ## Documentation Index
> Fetch the complete documentation index at: https://docs.junis.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Prompt Engineering for Agent Orchestration

> Master agent routing, tool calls, MCP, RAG, and data passing through system prompts - Production-tested patterns

# Prompt Engineering for Agent Orchestration

## 🎯 Overview

Junis uses **prompt-based orchestration** where you control agent behavior entirely through system prompts (instruction templates). No code changes needed - just configure your prompts in the Admin UI.

This guide provides **production-tested patterns** that work directly in your Junis system.

***

## 🧠 Core Concepts

### How Junis Routing Works

```
User Message → Orchestrator (analyzes) → Routes to Sub-Agent → Returns Response
```

**Key Point**: Orchestrator decides routing based on **keywords in its system prompt**.

### Where to Configure

1. **Admin UI** → **Agent Management** → Select Agent
2. **Edit Agent** → **Instruction Template** field
3. Paste your prompt → Save
4. **Done!** Agent automatically reloads

***

## 🔀 A. Sub-Agent Routing

### How It Works

**Mention sub-agent names in your Orchestrator's instruction template**, and the LLM will route requests to them based on keywords.

### ✅ Working Example (From Production)

This is the **actual default Orchestrator prompt** in Junis:

```markdown theme={null}
당신은 Junis의 메인 오케스트레이터입니다.

사용자 요청을 분석하고 적절하게 응답하세요:

1. 이메일 관련 요청 → EmailWorkflow 에이전트로 전송
   - "이메일 작성해줘", "메일 답장", "이메일 템플릿" 등
   - 예: "이메일 작성을 도와드리겠습니다. EmailWorkflow 에이전트로 연결합니다."

2. 일반 대화 → 직접 응답
   - 인사, 일상 대화, 간단한 질문 등
   - 친근하고 전문적인 톤으로 직접 응답하세요.
```

### 📋 Pattern Breakdown

**Structure**:

```
[Condition Description] → [Sub-Agent Name] 에이전트로 전송
   - [Keyword 1], [Keyword 2], ...
   - 예: [Example response]
```

**Why It Works**:

* ✅ **Explicit agent names** (EmailWorkflow, etc.)
* ✅ **Clear keywords** for pattern matching
* ✅ **Examples** guide the LLM's response style

### 🛠️ How to Set Up

#### Step 1: Create Sub-Agents

1. **Admin UI** → **Agent Management** → **Create Agent**
2. Create your sub-agents:
   * `EmailWorkflow` (LLM\_AGENT)
   * `DataWorkflow` (SEQUENTIAL\_AGENT)

#### Step 2: Link to Orchestrator

1. Select your Orchestrator agent
2. **Relationships** tab → **Add Relationship**
3. Add each sub-agent with order index (1, 2, 3...)

#### Step 3: Configure Orchestrator Prompt

1. Edit Orchestrator → **Instruction Template**
2. Paste routing logic (see example above)
3. **Save** → Cache automatically refreshes

### ✨ Advanced Routing Patterns

#### Multi-Language Routing

```markdown theme={null}
You are a multilingual orchestrator.

Route based on request type:

1. Code requests → CodeAssistant agent
   - "write code", "debug", "refactor", "implement"
   - Example: "I'll connect you to CodeAssistant for coding help."

2. Data analysis → DataAnalyst agent
   - "analyze data", "create chart", "statistics", "trend"
   - Example: "Routing to DataAnalyst for data insights."

3. General chat → Respond directly
   - Greetings, small talk, questions
   - Friendly and professional tone.
```

#### Priority-Based Routing

```markdown theme={null}
우선순위 기반 라우팅:

1. 긴급 요청 (최우선) → UrgentSupport 에이전트
   - "긴급", "빠르게", "지금 당장", "urgent" 등

2. 기술 문제 → TechSupport 에이전트
   - "에러", "버그", "오류", "작동하지 않음" 등

3. 일반 문의 → GeneralSupport 에이전트
   - 그 외 모든 요청
```

***

## 🛠️ B. Tool Calls & MCP Integration

### How It Works

**Mention tool/MCP names in your agent's instruction**, and the LLM will call them when needed.

### ✅ Working Example (Tool Call)

```markdown theme={null}
당신은 브랜드 데이터 검색 전문가입니다.

사용 가능한 도구:
1. search_brand_in_systems - 여러 시스템에서 브랜드 정보 검색
2. get_bbpi_data - BBPI 데이터 조회
3. get_cr_segments - CR 세그먼트 데이터 조회

작업 절차:
1. 사용자가 브랜드 이름을 언급하면 search_brand_in_systems 도구 사용
2. 브랜드가 확인되면 get_bbpi_data로 상세 정보 조회
3. 결과를 친절하게 요약하여 제공

예시:
- 사용자: "아모레퍼시픽 정보 알려줘"
- 행동: search_brand_in_systems("아모레퍼시픽") 실행
```

### 📋 Pattern Breakdown

**Structure**:

```
사용 가능한 도구:
1. [tool_name] - [tool_description]
2. [tool_name] - [tool_description]

작업 절차:
1. [Condition] → [tool_name] 사용
2. [Next step] → [tool_name] 사용
```

### 🔧 How to Configure Tools

#### Step 1: Register Tool in Admin UI

1. **Admin UI** → **Tools Management**
2. Check available tools (system admin only)
3. Note the **exact function name**

#### Step 2: Add to Agent Config

1. **Agent Management** → Select agent → **Edit**
2. **Tools** field → Add tool names:
   ```json theme={null}
   ["search_brand_in_systems", "get_bbpi_data"]
   ```
3. **Save**

#### Step 3: Update Instruction Template

Include tool names and usage patterns in the instruction (see example above).

### ✨ MCP Integration Example

```markdown theme={null}
You are a development assistant with GitHub integration.

Available MCP platforms:
1. GitHub - Create issues, manage repositories, and track PRs

Tasks you can perform:
- "create an issue for X" → Use GitHub MCP to create issue
- "list open PRs" → Use GitHub MCP to retrieve pull requests
- "get repository info" → Use GitHub MCP to fetch repo details

Example workflow:
1. User: "Create an issue for bug in authentication"
2. Action: Call GitHub MCP create_issue function
3. Response: "Issue #123 created successfully in repository"
```

### 🔧 How to Configure MCP

#### Step 1: Enable MCP Platform

1. **Admin UI** → **MCP Platforms**
2. Check available platforms (GitHub, Firecrawl, etc.)
3. Configure credentials (API keys, OAuth tokens)

#### Step 2: Link MCP to Agent

1. **Agent Management** → Select agent → **MCP** tab
2. **Add MCP Platform** → Select platform
3. **Priority Order**: Lower number = higher priority

#### Step 3: Update Instruction Template

Mention MCP platform capabilities in your prompt (see example above).

***

## 📚 C. RAG Datastore Queries

### How It Works

**Mention data types or topics in your instruction**, and the LLM will query your RAG Datastore when needed.

### ✅ Working Example

```markdown theme={null}
당신은 회사 문서 검색 전문가입니다.

사용 가능한 지식 베이스:
- 회사 정책 및 규정 문서
- 제품 매뉴얼 및 사양서
- 고객 FAQ 및 문의 이력

작업 방식:
1. 사용자 질문 분석
2. 관련 문서 자동 검색 (RAG)
3. 검색 결과 기반 답변 생성

예시:
- 사용자: "휴가 정책 알려줘"
- 행동: 회사 정책 문서에서 휴가 관련 내용 검색 → 답변 생성
```

### 📋 Pattern Breakdown

**Structure**:

```
사용 가능한 지식 베이스:
- [Knowledge domain 1]
- [Knowledge domain 2]

작업 방식:
1. 질문 분석
2. 자동 검색 (RAG)
3. 답변 생성
```

### 🗂️ How to Set Up RAG

#### Step 1: Create DataStore

1. **Admin UI** → **Knowledge Base** → **Create DataStore**
2. **Name**: `company-policies` (use lowercase with hyphens)
3. **Upload documents**: PDFs, DOCX, TXT files

#### Step 2: Add RAG Tool to Agent

1. **Agent Management** → Select agent → **Edit**
2. **RAG Tools** field → Add:
   ```json theme={null}
   ["rag_company-policies"]
   ```
   **Format**: `rag_` prefix + DataStore name
3. **Save**

#### Step 3: Update Instruction Template

Mention knowledge domains in your prompt (see example above).

### ⚠️ Important Notes

* **Model Requirement**: RAG only works with **Gemini models** (e.g., `gemini/gemini-1.5-flash`)
* **DataStore Location**: Must be in `global` location (not regional)
* **Naming**: Use lowercase, hyphens only (e.g., `rag_brand-knowledge`)

***

## 🔄 D. Output Format & Key Passing

### How It Works

**Define output format in parent agent**, then **reference output key in child agent** to receive structured data.

### ✅ Working Example (Parent Agent)

```markdown theme={null}
당신은 데이터 수집 코디네이터입니다.

작업:
1. 여러 소스에서 브랜드 데이터 수집
2. 결과를 JSON 형식으로 출력

출력 형식 (중요):
{
  "brand_name": "브랜드명",
  "bbpi_data": { BBPI 상세 정보 },
  "cr_data": { CR 세그먼트 정보 },
  "salesforce_data": { Salesforce CRM 정보 }
}

이 출력은 ReportCompiler 에이전트가 사용합니다.
```

**DB Configuration**:

* **Output Key**: `collected_brand_data`

### ✅ Working Example (Child Agent)

```markdown theme={null}
당신은 데이터 분석 보고서 컴파일러입니다.

입력 데이터:
- 이전 에이전트의 collected_data 출력을 받습니다.

작업:
1. collected_data에서 핵심 정보 추출
2. 분석 보고서 형식으로 재구성
3. 마크다운 또는 HTML로 최종 보고서 생성

출력 형식:
# [데이터 이름] 분석 보고서

## 1. 데이터 분석
[collected_data.analysis 내용]

## 2. 세그먼트 정보
[collected_data.segments 내용]

## 3. CRM 정보
[collected_data.crm_data 내용]
```

**DB Configuration**:

* **Include Contents**: `collected_brand_data`

### 📋 Pattern Breakdown

**Parent Agent**:

```
출력 형식 (중요):
{
  "key1": "value description",
  "key2": { nested object },
  ...
}

이 출력은 [ChildAgent] 에이전트가 사용합니다.
```

**Child Agent**:

```
입력 데이터:
- 이전 에이전트의 [output_key] 출력을 받습니다.

작업:
1. [output_key]에서 [data] 추출
2. [Process]
```

### 🔧 How to Configure

#### Step 1: Parent Agent Setup

1. **Agent Management** → Select parent agent → **Edit**
2. **Instruction Template**: Define output format
3. **Output Key** field: `collected_brand_data`
4. **Output Schema** (optional): Define JSON schema
5. **Save**

#### Step 2: Child Agent Setup

1. **Agent Management** → Select child agent → **Edit**
2. **Instruction Template**: Mention input data source
3. **Include Contents** field: `collected_brand_data`
4. **Save**

#### Step 3: Link Agents

1. Create **Sequential Agent** (e.g., `DataWorkflow`)
2. Add relationships:
   * Order 1: `DataCollector` (parent)
   * Order 2: `ReportCompiler` (child)

### ✨ Advanced: Schema Validation

**Define output schema for strict validation**:

```json theme={null}
{
  "type": "object",
  "properties": {
    "brand_name": { "type": "string" },
    "bbpi_data": { "type": "object" },
    "cr_data": { "type": "object" }
  },
  "required": ["brand_name", "bbpi_data"]
}
```

Add this to **Output Schema** field in Admin UI.

***

## 🎭 E. Flexible Application Patterns

### Conditional Logic

```markdown theme={null}
당신은 스마트 라우터입니다.

조건부 라우팅:

IF 사용자 요청에 "긴급" 또는 "urgent" 포함:
  → UrgentHandler 에이전트로 즉시 전달

ELSE IF 사용자가 파일 첨부:
  → FileProcessor 에이전트로 전달

ELSE IF 질문이 회사 정책 관련:
  → 지식 베이스 검색 수행

ELSE:
  → 일반 응답 제공
```

### Multi-Step Workflows

```markdown theme={null}
당신은 워크플로우 관리자입니다.

단계별 작업 프로세스:

1단계: 데이터 검증
   - 사용자 입력 확인
   - 필수 필드 체크
   - 유효성 검사

2단계: 외부 시스템 조회
   - Salesforce에서 고객 정보 조회 (MCP)
   - DataLab에서 거래 이력 조회 (Tool)

3단계: 분석 및 보고서 생성
   - 수집된 데이터 통합
   - 인사이트 도출
   - PDF 보고서 생성 (Tool: claude_pdf_processor)

4단계: 결과 전달
   - GitHub 이슈 생성 또는 커밋
   - 사용자에게 완료 알림
```

### Dynamic Tool Selection

```markdown theme={null}
당신은 유연한 도구 사용자입니다.

상황에 맞는 도구 선택:

데이터 소스 우선순위:
1. 먼저 내부 데이터베이스 검색 (get_internal_data 툴)
2. 없으면 Salesforce 조회 (Salesforce MCP)
3. 그래도 없으면 웹 검색 수행 (Web Search 활성화 필요)

항상 가장 정확한 데이터 소스를 먼저 시도하세요.
```

### Error Handling

```markdown theme={null}
당신은 안정적인 에이전트입니다.

에러 처리:

IF 도구 호출 실패:
  → 사용자에게 친절히 설명
  → 대체 방법 제안

IF 데이터 없음:
  → "해당 정보를 찾을 수 없습니다" 명확히 전달
  → 추가 정보 요청 또는 다른 접근 방법 제시

IF 외부 시스템 오류:
  → 재시도 1회
  → 실패 시 수동 대응 안내
```

***

## ✅ Best Practices

### 1. Be Explicit

❌ **Bad**: "Handle email requests"
✅ **Good**: "이메일 작성, 답장, 전달 요청 → EmailWorkflow 에이전트로 전송"

### 2. Provide Examples

Include example user inputs and agent responses in your prompts.

### 3. Use Clear Formatting

Structure your prompts with:

* Numbered lists
* Clear headers
* Example blocks

### 4. Test Incrementally

1. Test Orchestrator routing first
2. Add one sub-agent at a time
3. Verify each tool/MCP call individually
4. Test complete workflow last

### 5. Monitor & Iterate

* Check **Usage Logs** in Admin UI
* Review agent routing events
* Refine prompts based on real usage

***

## 🐛 Troubleshooting

### Agent Not Routing

**Problem**: Orchestrator responds directly instead of routing.

**Solution**:

* ✅ Check sub-agent **name** matches exactly in prompt
* ✅ Verify agent **relationship** exists in Admin UI
* ✅ Ensure sub-agent is **active** (not disabled)

### Tool Not Called

**Problem**: Agent doesn't call the tool.

**Solution**:

* ✅ Verify tool is added to **Tools** field in agent config
* ✅ Mention tool **name** and **usage** in instruction
* ✅ Check tool is registered in system (Tools Management)

### MCP Call Fails

**Problem**: MCP platform error or timeout.

**Solution**:

* ✅ Verify MCP credentials in **MCP Platforms** settings
* ✅ Check MCP platform is **linked** to agent (MCP tab)
* ✅ Test MCP connection manually in Admin UI

### RAG Returns No Results

**Problem**: RAG query returns empty or irrelevant results.

**Solution**:

* ✅ Verify DataStore has **indexed documents**
* ✅ Check agent uses **Gemini model** (RAG only works with Gemini)
* ✅ Ensure RAG tool name format: `rag_[datastore-name]`
* ✅ Improve query phrasing in prompt

### Output Key Not Passed

**Problem**: Child agent doesn't receive parent output.

**Solution**:

* ✅ Parent agent must set **Output Key** field
* ✅ Child agent must set **Include Contents** field with same key
* ✅ Agents must be in **Sequential** flow (not Parallel)

***

## 📖 Related Documentation

<CardGroup cols={3}>
  <Card title="Agent System Overview" icon="sitemap" href="/getting-started/agent-system">
    Learn agent types and architecture
  </Card>

  <Card title="Tools Development" icon="wrench" href="/guides/tools/overview">
    Create custom tools
  </Card>

  <Card title="MCP Integration" icon="plug" href="/guides/mcp/overview">
    Connect external platforms
  </Card>
</CardGroup>

***

## 🎯 Summary

**You now know how to**:

✅ **A. Route to sub-agents** by mentioning agent names in prompts
✅ **B. Call tools & MCP** by listing available functions
✅ **C. Query RAG Datastores** by mentioning knowledge domains
✅ **D. Pass data with output keys** between agents
✅ **E. Apply flexible patterns** with conditional logic

**Next Steps**:

1. Open **Admin UI** → **Agent Management**
2. Create a simple Orchestrator with 2 sub-agents
3. Test routing with different user inputs
4. Gradually add tools, MCP, and RAG

**Remember**: No code changes needed - just configure prompts and save! 🚀
