본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

단일 턴 Alpha2 입력 만들기

원문 보기 위키 갱신

title: "Conversation API (Python) – 권장 사용법"

linkTitle: "Conversation" weight: 11000 type: docs description: 도구 사용 여부에 따른 Python에서 Dapr Conversation API 사용의 권장 패턴을 소개합니다. 다중 턴 흐름과 안전 지침을 포함합니다. Dapr Conversation API는 현재 alpha 단계예요. 이 페이지에서는 Python SDK로 효과적으로 사용하기 위한 권장되고 최소한의 패턴을 제시해요:

  • 일반 요청 (도구 없음)
  • 도구를 포함한 요청 (함수를 도구로 사용)
  • 도구 실행을 포함한 다중 턴 흐름
  • 비동기(async) 변형
  • 도구 호출 실행을 위한 중요한 안전 참고 사항

출처: Dapr 문서

본문

사전 준비사항 (Prerequisites)

  • Dapr CLI 설치
  • 초기화된 Dapr 환경
  • Python 3.9+ 설치
  • Dapr Python 패키지 설치
  • Dapr 환경에 LLM 컴포넌트(예: OpenAI 또는 Azure OpenAI) 구성

전체 엔드투엔드 흐름과 프로바이더 설정은 다음을 참고하세요:

  • Conversation의 SDK 예제: TOOL-CALL-QUICKSTART.md
  • real_llm_providers_example.py

일반 대화 (도구 없음)

from dapr.clients import DaprClient
from dapr.clients.grpc import conversation


user_msg = conversation.create_user_message("What's Dapr?")
alpha2_input = conversation.ConversationInputAlpha2(messages=[user_msg])

with DaprClient() as client:
resp = client.converse_alpha2(
name="echo", # replace with your LLM component name
inputs=[alpha2_input],
temperature=1,
)

for msg in resp.to_assistant_messages():
if msg.of_assistant.content:
print(msg.of_assistant.content[0].text)

핵심 포인트:

  • 메시지를 만들려면 conversation.create_user_message을 사용해요.
  • ConversationInputAlpha2(messages=[...])로 감싸서 converse_alpha2에 전달해요.
  • 어시스턴트 출력을 순회하려면 response.to_assistant_messages()를 사용해요.

도구: 데코레이터 기반 (권장)

데코레이터 기반 도구는 깔끔하고 인체공학적인 접근 방식을 제공해요. 명확한 타입 힌트와 상세한 docstring으로 함수를 정의해야 해요. 이것은 LLM이 도구를 어떻게 또는 언제 호출할지 이해하는 데 중요해요. @conversation.tool로 데코레이트하고, 등록된 도구는 LLM에 전달되어 도구 호출을 통해 호출될 수 있어요.

from dapr.clients import DaprClient
from dapr.clients.grpc import conversation

@conversation.tool
def get_weather(location: str, unit: str = 'fahrenheit') -> str:
"""Get current weather for a location."""

return f"Weather in {location} (unit={unit})"

user_msg = conversation.create_user_message("What's the weather in Paris?")
alpha2_input = conversation.ConversationInputAlpha2(messages=[user_msg])

with DaprClient() as client:
response = client.converse_alpha2(
name="openai", # your LLM component
inputs=[alpha2_input],
tools=conversation.get_registered_tools(), # tools registered by @conversation.tool
tool_choice='auto',
temperature=1,
)


for msg in response.to_assistant_messages():
if msg.of_assistant.tool_calls:
for tc in msg.of_assistant.tool_calls:
print(f"Tool call: {tc.function.name} args={tc.function.arguments}")
elif msg.of_assistant.content:
print(msg.of_assistant.content[0].text)

참고:

  • 모든 @conversation.tool 데코레이트 함수를 수집하려면 conversation.get_registered_tools()를 사용해요.
  • 바인더는 함수 시그니처를 사용해서 파라미터를 검증/강제 변환(coerce)해요. 애노테이션을 정확하게 유지하세요.

최소 다중 턴 with 도구

도구를 사용하는 대화에서 가장 자주 쓰는 루프예요:

경고 (Warning)

신뢰하는 모든 도구가 아닌 이상, LLM이 반환한 도구 호출을 맹목적으로 자동 실행하지 마세요. 도구 이름과 인자를 신뢰할 수 없는 입력(untrusted input)으로 취급하세요.

  • 입력을 검증하고 가드레일(허용 목록 도구, 인자 스키마, 부작용 제약)을 적용하세요.
  • 비동기 또는 I/O 바운드 도구는 conversation.execute_registered_tool_async(..., timeout=...)를 선호하고 보수적인 타임아웃을 설정하세요.
  • 민감한 컨텍스트에서는 실행 전에 정책 레이어나 사용자 확인 단계를 추가하는 것을 고려하세요.
  • 도구 사용을 로깅하고 모니터링하며, 검증이 실패하면 fail closed 하세요.
from dapr.clients import DaprClient
from dapr.clients.grpc import conversation

@conversation.tool
def get_weather(location: str, unit: str = 'fahrenheit') -> str:
return f"Weather in {location} (unit={unit})"

history: list[conversation.ConversationMessage] = [
conversation.create_user_message("What's the weather in San Francisco?")]

with DaprClient() as client:

resp1 = client.converse_alpha2(
name="openai",
inputs=[conversation.ConversationInputAlpha2(messages=history)],
tools=conversation.get_registered_tools(),
tool_choice='auto',
temperature=1,
)


for msg in resp1.to_assistant_messages():
history.append(msg)
for tc in msg.of_assistant.tool_calls:

tool_output = conversation.execute_registered_tool(
tc.function.name, tc.function.arguments
)
history.append(
conversation.create_tool_message(
tool_id=tc.id, name=tc.function.name, content=str(tool_output)
)
)


history.append(conversation.create_user_message("Should I bring an umbrella?"))
resp2 = client.converse_alpha2(
name="openai",
inputs=[conversation.ConversationInputAlpha2(messages=history)],
tools=conversation.get_registered_tools(),
temperature=1,
)

for msg in resp2.to_assistant_messages():
history.append(msg)
if not msg.of_assistant.tool_calls and msg.of_assistant.content:
print(msg.of_assistant.content[0].text)

팁:

  • 항상 어시스턴트 메시지를 history에 추가해요.
  • 각 도구 호출을 (검증과 함께) 실행하고 도구 출력을 포함한 도구 메시지를 추가해요.
  • 다음 턴에는 이 도구 결과가 포함되어 LLM이 그것을 가지고 추론할 수 있어요.

함수를 도구로: 대안

데코레이터가 실용적이지 않을 때 두 가지 옵션이 있어요. A) 타입이 지정된 함수에서 자동 스키마 생성:

from enum import Enum
from dapr.clients.grpc import conversation

class Units(Enum):
CELSIUS = 'celsius'
FAHRENHEIT = 'fahrenheit'

def get_weather(location: str, unit: Units = Units.FAHRENHEIT) -> str:
return f"Weather in {location}"

fn = conversation.ConversationToolsFunction.from_function(get_weather)
weather_tool = conversation.ConversationTools(function=fn)

B) 수동 JSON 스키마 (대체):

from dapr.clients.grpc import conversation

fn = conversation.ConversationToolsFunction(
name='get_weather',
description='Get current weather',
parameters={
'type': 'object',
'properties': {
'location': {'type': 'string'},
'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']},
},
'required': ['location'],
},
)
weather_tool = conversation.ConversationTools(function=fn)

비동기 변형 (Async variant)

필요에 따라 비동기 클라이언트와 비동기 도구 실행 헬퍼를 사용해요.

import asyncio
from dapr.aio.clients import DaprClient as AsyncDaprClient
from dapr.clients.grpc import conversation

@conversation.tool
def get_time() -> str:
return '2025-01-01T12:00:00Z'

async def main():
async with AsyncDaprClient() as client:
msg = conversation.create_user_message('What time is it?')
inp = conversation.ConversationInputAlpha2(messages=[msg])
resp = await client.converse_alpha2(
name='openai', inputs=[inp], tools=conversation.get_registered_tools()
)
for m in resp.to_assistant_messages():
if m.of_assistant.content:
print(m.of_assistant.content[0].text)

asyncio.run(main())

도구를 비동기로 실행해야 한다면(예: 네트워크 I/O) async 함수를 구현하고 타임아웃과 함께 conversation.execute_registered_tool_async를 사용해요.

안전과 검증 (필독)

LLM이 도구 호출을 제안할 수 있어요. 모델이 제공한 모든 파라미터를 신뢰할 수 없는 입력으로 취급하세요. 권장 사항:

  • 신뢰하는 함수만 도구로 등록해요. 명확성과 자동 스키마 생성을 위해 @conversation.tool 데코레이터를 선호해요.
  • 정확한 타입 애노테이션과 docstring을 사용해요. SDK는 함수 시그니처를 JSON 스키마로 변환하고 타입 강제 변환과 예상치 못한/유효하지 않은 필드 거부로 파라미터를 바인딩해요.
  • 부작용(파일시스템, 네트워크, 서브프로세스)을 일으킬 수 있는 도구에는 가드레일을 추가하세요. 허용 목록, 샌드박싱, 제한을 고려하세요.
  • 실행 전에 인자를 검증하세요. 예를 들어 파일 경로를 정리하거나 URL/도메인을 제한하세요.
  • 타임아웃과 동시성 제어를 고려하세요. async 도구에는 execute_registered_tool_async(..., timeout=...)에 타임아웃을 전달하세요.
  • 도구 사용을 로깅하고 모니터링하세요. fail closed: 검증이 실패하면 도구를 실행하지 말고 사용자에게 안전하게 알려주세요.

파라미터 바인딩과 오류 처리에 대한 자세한 내용은 dapr/clients/grpc/conversation.py(예: tool(), ConversationTools, execute_registered_tool)의 인라인 주석도 참고하세요.

핵심 헬퍼 메서드 (빠른 참조)

이 섹션에서는 예제 전반에서 사용되는 dapr.clients.grpc.conversation에서 사용 가능한 헬퍼 유틸리티를 요약해요.

  • create_user_message(text: str) -> ConversationMessage: Alpha2용 사용자 역할 메시지를 만듭니다. 히스토리 목록에서 사용해요.

  • 예: history.append(conversation.create_user_message("Hello"))

  • create_system_message(text: str) -> ConversationMessage: 어시스턴트의 동작을 이끌기 위한 시스템 메시지를 만듭니다.

  • 예: history = [conversation.create_system_message("You are a concise assistant.")]

  • create_assistant_message(text: str) -> ConversationMessage: 테스트나 통제된 흐름에서 어시스턴트 텍스트를 주입할 때 유용해요.

  • create_tool_message(tool_id: str, name: str, content: Any) -> ConversationMessage: 도구의 출력을 다음 턴에 LLM이 읽을 수 있는 도구 메시지로 변환합니다.

  • content는 어떤 객체든 될 수 있으며, SDK가 안전하게 문자열화해요.

  • 예: history.append(conversation.create_tool_message(tool_id=tc.id, name=tc.function.name, content=conversation.execute_registered_tool(tc.function.name, tc.function.arguments)))

  • get_registered_tools() -> list[ConversationTools]: 현재 프로세스 내 레지스트리에 등록된 모든 도구를 반환합니다.

  • 다음을 통해 생성된 도구를 포함합니다: @conversation.tool 데코레이터(기본적으로 자동 등록), 그리고

  • ConversationToolsFunction.from_function with register=True (기본값).

  • 이 목록을 converse_alpha2(…, tools=…)에 전달해요.

  • register_tool(name: str, t: ConversationTools) / unregister_tool(name: str): 도구 레지스트리를 수동으로 관리해요(예: 고급 시나리오, 테스트, 정리).

  • 이름은 고유해야 하며, 오래 실행되는 프로세스에서는 충돌을 피하기 위해 등록 해제해야 해요.

  • execute_registered_tool(name: str, params: Mapping|Sequence|str|None) -> Any: 이름으로 등록된 도구를 동기적으로 실행합니다.

  • params는 kwargs(mapping), args(sequence), JSON 문자열, 또는 None을 허용해요. JSON 문자열이 제공되면(LLM이 흔히 반환) 자동으로 파싱해요.

  • 파라미터는 함수 시그니처/스키마에 대해 검증되고 강제 변환되며, 예상치 못한/유효하지 않은 필드는 오류를 발생시켜요.

  • 보안: params를 신뢰할 수 없는 것으로 취급하고 부작용에 대한 가드레일을 추가하세요.

  • execute_registered_tool_async(name: str, params: Mapping|Sequence|str|None, *, timeout: float|None=None) -> Any: 비동기 대응입니다. I/O 바운드 도구에 권장되는 타임아웃을 지원해요.

  • async 도구 또는 aio 클라이언트 사용 시 선호해요.

  • ConversationToolsFunction.from_function(func: Callable, register: bool = True) -> ConversationToolsFunction: 타입이 지정된 Python 함수(애노테이션 + 선택적 docstring)에서 JSON 스키마를 도출하고 선택적으로 도구를 등록합니다.

  • 일반적인 사용법: spec = conversation.ConversationToolsFunction.from_function(my_func); 그다음 자동 등록에 의존하거나 ConversationTools(function=spec)으로 감싸고 register_tool(spec.name, tool)을 호출하거나 [tool]을 직접 tools=에 전달해요.

  • ConversationResponseAlpha2.to_assistant_messages() -> list[ConversationMessage]: 응답 출력을 history에 바로 추가할 수 있는 어시스턴트 ConversationMessage 객체로 변환하는 편의 메서드입니다(있을 때 tool_calls 포함).

팁: @conversation.tool 데코레이터가 도구를 만드는 가장 쉬운 방법이에요. 함수에서 스키마를 자동 생성하고, 선택적 namespace/name 재정의를 허용하며, 도구를 자동 등록해요(등록을 미루려면 register=False로 설정할 수 있어요).

더 알아보기 (Learn more)