DeepSeek-R1과 같은 추론 모델을 자동화 에이전트 파이프라인에 연결할 때, 멀티턴 함수 호출(Function Calling)은 크게 두 가지 치명적인 병목 현상에 부딪힙니다. 범용 클라이언트 라이브러리가 모델의 사고 과정(Chain of Thought)을 임의로 제거하여 HTTP 400 에러를 유발하거나, 느슨한 스키마 정의로 인해 인자 형식 불일치 및 환각(Hallucination)이 발생하는 문제입니다.
365Finds의 기술적 판단은 확고합니다. 프로덕션 환경의 에이전트 파이프라인은 반드시 DeepSeek의 Beta 엔드포인트(https://api.deepseek.com/beta)에 연결하여 "strict": true를 활성화해야 하며, 메시지 상태 관리 시 reasoning_content를 명시적으로 보존하는 직렬화 로직을 구축해야 합니다. 기본 OpenAI SDK의 추상화 계층에 무비판적으로 의존하거나 "Beta"라는 명칭 때문에 적용을 미루는 것은 에이전트 파이프라인 장애를 유발하는 대표적인 설계 결함입니다.
근본 원인: 멀티턴 에이전트 루프가 중단되는 이유
추론 모드(Thinking Mode)가 켜진 DeepSeek 모델이 외부 도구 호출을 결정하면, API 응답 구조는 일반적인 텍스트 생성과 확연히 다릅니다.
message.reasoning_content: 도구를 왜 호출해야 하며 매개변수를 어떻게 도출했는지 설명하는 모델 내부의 사고 과정(Chain of Thought).message.tool_calls: 실행할 함수 이름과 JSON 문자열 형태의 인자 목록.message.content: 도구 실행 결과를 대기하기 위해 텍스트 생성을 보류하므로 빈 문자열 또는 null 값 유지.
HTTP 400 검증 실패의 함정
도구 호출이 없는 일반적인 대화에서는 DeepSeek API가 이전 턴의 reasoning_content 누락을 허용합니다. 하지만 요청 본문에 tools 매개변수가 포함되는 순간, DeepSeek의 프로토콜 계층은 엄격한 상태 검증을 수행합니다. 즉, 사고 모드로 생성된 직전 assistant 메시지는 대화 이력에 포함되어 재전송될 때 반드시 원래의 reasoning_content를 유지해야 합니다.
클라이언트 라이브러리가 이 비표준 필드를 삭제한 채 다음 요청을 전송하면 DeepSeek 게이트웨이는 즉시 오류를 반환합니다.
{
"error": {
"message": "The reasoning_content in the thinking mode must be passed back to the API.",
"type": "invalid_request_error",
"code": "invalid_request_error"
}
}
LangChain 어댑터, 독자적인 대화 메모리 모듈, 기본 openai 라이브러리의 메시지 직렬화 로직 등 대다수의 오픈소스 프레임워크는 OpenAI 기본 스펙에 없는 속성을 자동으로 걸러냅니다. 따라서 백엔드가 로컬 함수를 실행하고 role: "tool" 메시지를 붙여 2차 호출을 시도하는 순간 시스템이 붕괴됩니다.
Beta 엔드포인트를 통한 엄격한 JSON Schema(Strict Mode) 강제
추론 모델은 복잡한 논리 설계에 탁월하지만, 제약 없는 JSON 생성 환경에서는 존재하지 않는 매개변수 생성, 필수 필드 누락, 마크다운 코드 블록 삽입 등의 스키마 이탈을 일으키기 쉽습니다.
DeepSeek는 모델 디코딩 단계에서 문법적 제약을 가해 생성된 인자가 정의된 JSON Schema와 100% 일치하도록 강제하는 네이티브 **Strict Mode(Beta)**를 제공합니다.
필수 설정 조건
엄격한 유효성 검증을 활성화하려면 다음 세 가지 요건을 충족해야 합니다.
- Beta Base URL 설정: API 클라이언트의 접속 엔드포인트를 기본 주소가 아닌
https://api.deepseek.com/beta로 지정합니다. - 함수별
"strict": true선언:tools배열 내 개별 function 정의 블록에"strict": true속성을 명시합니다. - 엄격한 스키마 규칙 준수:
- 객체 레벨마다
"additionalProperties": false를 반드시 선언합니다. properties에 정의된 모든 키 이름을required: [...]배열에 누락 없이 기재합니다.- 비즈니스 로직상 선택적 필드라 하더라도
required목록에서 제외하지 말고, 널 허용 유니언 타입(예:["string", "null"])과 기본값 null을 함께 지정해야 합니다.
- 객체 레벨마다
프로덕션 구현: Pydantic V2 기반의 내결함성 에이전트 루프
다음 Python 코드는 OpenAI SDK와 Pydantic V2를 활용하여 DeepSeek Beta 엔드포인트에 접속하고, 엄격한 스키마 생성, reasoning_content 보존, 그리고 자동 오류 복구 기능을 갖춘 에이전트 루프를 구현한 예제입니다.
import json
import os
from typing import Any, Dict, List, Optional
from openai import OpenAI
from pydantic import BaseModel, Field, ValidationError
# 1. DeepSeek Beta 엔드포인트를 타깃으로 클라이언트 초기화
client = OpenAI(
api_key=os.environ.get("DEEPSEEK_API_KEY"),
base_url="https://api.deepseek.com/beta",
)
# 2. Pydantic을 이용한 도구 입력 매개변수 모델 정의
class DatabaseQueryInput(BaseModel):
table_name: str = Field(description="조회 대상 데이터베이스 테이블 이름")
query_filter: str = Field(description="SQL 문법 형식의 WHERE 조건절")
limit: Optional[int] = Field(default=10, description="반환할 최대 레코드 수")
# 3. Pydantic 모델을 DeepSeek Strict Mode 규격 스키마로 변환
def generate_strict_tool_schema(name: str, description: str, model_cls: type[BaseModel]) -> Dict[str, Any]:
schema = model_cls.model_json_schema()
properties = schema.get("properties", {})
required_keys = list(properties.keys())
clean_properties = {}
for key, val in properties.items():
prop = val.copy()
if "anyOf" in prop:
prop["type"] = [item.get("type") for item in prop.pop("anyOf") if item.get("type")]
clean_properties[key] = prop
return {
"type": "function",
"function": {
"name": name,
"description": description,
"strict": True,
"parameters": {
"type": "object",
"properties": clean_properties,
"required": required_keys,
"additionalProperties": False,
},
},
}
tools = [
generate_strict_tool_schema(
name="query_database",
description="사내 데이터 분석 플랫폼의 레코드를 엄격하게 조회합니다.",
model_cls=DatabaseQueryInput,
)
]
# 로컬 도구 모의 실행
def execute_database_query(arguments: DatabaseQueryInput) -> str:
return json.dumps({
"status": "success",
"rows": [
{"id": 101, "cluster": "Enterprise-Cluster-A", "status": "active"},
{"id": 102, "cluster": "Staging-Node-B", "status": "idle"},
][:arguments.limit]
})
# 4. reasoning_content 누락 방지 전용 메시지 직렬화 함수
def append_assistant_message(messages: List[Dict[str, Any]], assistant_message: Any) -> None:
serialized = {
"role": "assistant",
"content": assistant_message.content or "",
}
# 핵심: 사고 과정 필드가 존재하면 무조건 보존
if hasattr(assistant_message, "reasoning_content") and assistant_message.reasoning_content:
serialized["reasoning_content"] = assistant_message.reasoning_content
if assistant_message.tool_calls:
serialized["tool_calls"] = [
{
"id": tc.id,
"type": tc.type,
"function": {
"name": tc.function.name,
"arguments": tc.function.arguments,
},
}
for tc in assistant_message.tool_calls
]
messages.append(serialized)
# 5. 멀티턴 에이전트 실행 엔진
def run_agent_loop(prompt: str) -> str:
messages: List[Dict[str, Any]] = [
{"role": "user", "content": prompt}
]
max_turns = 5
for turn in range(max_turns):
response = client.chat.completions.create(
model="deepseek-reasoner",
messages=messages,
tools=tools,
tool_choice="auto",
)
assistant_msg = response.choices[0].message
# reasoning_content를 유지한 채 이력에 추가
append_assistant_message(messages, assistant_msg)
# 모델이 도구 호출을 종료하면 최종 답변 반환
if not assistant_msg.tool_calls:
return assistant_msg.content or "작업 완료(텍스트 응답 없음)."
# 요청된 개별 도구 호출 실행
for tool_call in assistant_msg.tool_calls:
tool_id = tool_call.id
func_name = tool_call.function.name
raw_args = tool_call.function.arguments
if func_name == "query_database":
try:
parsed_args = DatabaseQueryInput.model_validate_json(raw_args)
tool_output = execute_database_query(parsed_args)
except ValidationError as val_err:
# 유효성 검증 오류를 tool 역할로 회신하여 모델의 자가 교정 유도
tool_output = json.dumps({
"status": "error",
"validation_error": val_err.errors(),
"hint": "인자 타입이 스키마 요구사항과 일치하도록 수정하여 재시도하십시오."
})
except Exception as exc:
tool_output = json.dumps({"status": "error", "message": str(exc)})
else:
tool_output = json.dumps({"status": "error", "message": f"알 수 없는 도구: {func_name}"})
# 도구 실행 결과를 대화 맥락에 추가
messages.append({
"role": "tool",
"tool_call_id": tool_id,
"content": tool_output,
})
return "에이전트 최대 반복 횟수를 초과했습니다."
if __name__ == "__main__":
test_prompt = "사내 분석 데이터베이스에서 활성 상태의 엔터프라이즈 클러스터 정보를 조회해 주세요."
print("실행 결과:", run_agent_loop(test_prompt))
365Finds 기술 판단 및 트레이드오프
| 항목 | 업계 일반 방식 | 365Finds 권장안 | 아키텍처적 근거 |
|---|---|---|---|
| API 접속 엔드포인트 | 기본 https://api.deepseek.com | https://api.deepseek.com/beta | Strict Mode 적용 시 디코딩 단계에서 포맷 오류를 차단함; 비엄격 모드 재시도 비용이 마이그레이션 비용보다 큼. |
| 메시지 직렬화 | SDK 내장 model_dump() | reasoning_content 보존 커스텀 어댑터 | 표준 SDK는 커스텀 필드를 누락시키며, 멀티턴 도구 호출 시 100% 확률로 HTTP 400 에러를 유발함. |
| 사고 이력 관리 | 무제한으로 모든 턴의 사고 로그 누적 | 도구 실행 완료 후 이전 단계의 사고 로그 정리 | 현재 실행 중인 도구의 직전 사고 과정은 필수이지만, 10턴 이상 누적 시 컨텍스트 윈도우가 급격히 소진됨. |
| 추론 모드 제어 | 전체 파이프라인 상시 활성화 | 단순 라우팅 단계에서는 명시적 비활성화 | 1:1 매핑 수준의 단순 파라미터 추출 작업은 thinking: {"type": "disabled"}로 레이턴시를 최대 70% 단축 가능. |
운영 트레이드오프: 컨텍스트 예산과 프롬프트 캐싱(Prompt Caching)
멀티턴 도구 호출에서 reasoning_content를 다시 전달하면 요청당 입력 토큰 총량이 증가합니다. 그러나 DeepSeek 인프라는 강력한 프롬프트 캐싱(Prompt Caching) 메커니즘을 지원합니다. 대화 이력의 접두부(Prefix)가 유지되므로 캐시 적중 토큰은 최대 90% 할인된 가격이 적용됩니다.
따라서 실제 병목은 API 과금이 아니라 컨텍스트 윈도우 한도 초과입니다. 도구 호출이 5회 이상 반복되는 긴 작업에서는 중간 사고 과정만으로 수만 토큰이 누적될 수 있습니다. 365Finds는 선행 도구 호출이 완전히 완료되어 다음 업무 단계로 진입할 때 이전 단계의 사고 과정을 선별적으로 가지치기하되, 현재 활성 상태인 도구 호출의 직전 reasoning_content는 반드시 유지할 것을 권장합니다.