Dify 플러그인 제작 2. 모델 제공자 설정
Dify 플러그인 만들기 튜토리얼 시리즈의 두번째 글입니다. 첫번째 튜토리얼에서 만든 모델 제공자 플러그인에 실제로 모델 API를 붙여 봅니다.
튜토리얼 1. 준비 및 플러그인 생성
권장 독자
터미널 사용이 익숙한 파이썬 개발자
전체 시리즈의 학습 목표
사용자 환경에 필요한 모델 제공자 플러그인을 직접 만들 수 있다
본 글의 학습 목표
OpenAI compatible LLM 모델 설정
다루지 않는 내용
플러그인을 마켓플레이스에 배포
모델 제공자 이외의 플러그인 만들기
3. 모델 명세 작성
Dify에서 사용할 모델 명세를 작성합니다. 이 명세는 모델의 매개변수 설정에 사용됩니다.
여기서는 튜토리얼 작성 기준으로 최신 하이퍼클로바X 모델인 HCX-007과 HCX-005를 설정해보겠습니다. 두 모델에서 사용할 수 있는 기능과 가격 정보는 다음 문서를 참조합니다.
models/llm/ 폴더에 HCX-007.yaml 파일을 생성하고 다음 내용을 작성합니다. 설명은 주석으로 작성했습니다.
model: HCX-007 # 모델 이름
label:
en_US: HCX-007
model_type: llm
features:
# https://docs.dify.ai/en/develop-plugin/features-and-specs/plugin-types/model-designing-rules#modelfeature
- agent-thought
- tool-call
- stream-tool-call
# vision, multi-tool-call도 있음.
model_properties:
mode: chat
context_size: 128000 # 컨텍스트 크기
parameter_rules:
- name: max_completion_tokens # 최대 응답 토큰 수
label:
en_US: Max Completion Tokens
type: int
default: 4096
min: 1
max: 32768
required: true
help:
en_US: "Limit for reasoning + visible text tokens."
- name: temperature
use_template: temperature
# use_template은
# https://docs.dify.ai/en/develop-plugin/features-and-specs/plugin-types/model-designing-rules#param-use-template
# 를 참고하세요.
# 자주 쓰이는 temperature, top_p, frequency_penalty, presence_penalty, max_tokens
# 를 제공합니다.
default: 1.0
min: 0.0
max: 2.0
help:
en_US: "Model temperature"
- name: reasoning_effort # 추론 수준
label:
en_US: Reasoning Effort
type: string
required: false
default: medium
options:
- none
- low
- medium
- high
- name: response_format # 응답 형식
label:
en_US: Response Format
type: string
options:
- text
- json_object
default: text
help:
en_US: "text or structured output."
pricing:
# 가격 정보
# https://www.ncloud.com/v2/product/aiService/clovaStudio#pricing
input: "1.25"
output: "5.00"
unit: "0.001"
currency: KRWHCX-005도 같은 방식으로 작성해줍니다. 005는 reasoning(agent-thought)과 structured output을 지원하지 않는므로 두 부분은 삭제합니다. 대신 vision을 지원하므로 features 에 vision 을 추가합니다.
모델 명세를 전부 작성하고 models/llm/_position.yaml 파일을 생성합니다. 이것은 모델의 순서를 저장하는 파일입니다.
- HCX-007
- HCX-005
# 모델이 더 있으면 추가dify의 모델 선택 화면에서 007, 005 순으로 보이게 됩니다.
4. 모델 코드 작성
models/llm/llm.py를 만들고 다음 내용을 작성합니다.
from collections.abc import Generator
from typing import Optional, Union
from dify_plugin.entities.model.llm import LLMMode, LLMResult
from dify_plugin.entities.model.message import PromptMessage, PromptMessageTool
from dify_plugin import OAICompatLargeLanguageModel
class HyperCLOVAXLargeLanguageModel(OAICompatLargeLanguageModel):
def _invoke(
self,
model: str,
credentials: dict,
prompt_messages: list[PromptMessage],
model_parameters: dict,
tools: Optional[list[PromptMessageTool]] = None,
stop: Optional[list[str]] = None,
stream: bool = True,
user: Optional[str] = None,
) -> Union[LLMResult, Generator]:
self._add_parameters(credentials, model)
return super()._invoke(
model, credentials, prompt_messages, model_parameters, tools, stop, stream
)
# OAICompatLargeLanguageModel을 상속받으므로 _invoke()로 API 호출
def validate_credentials(self, model: str, credentials: dict) -> None:
self._add_parameters(credentials, model)
super().validate_credentials(model, credentials)
@staticmethod
def _add_parameters(credentials: dict, model: str) -> None:
"""
매개변수 설정
"""
# https://api.ncloud-docs.com/docs/clovastudio-openaicompatibility
# openai API 호환되는 엔드포인트를 써 줍니다.
credentials["endpoint_url"] = "https://clovastudio.stream.ntruss.com/v1/openai"
credentials["mode"] = LLMMode.CHAT.value
5. 제공자 설정
provider/{플러그인 이름}.py 파일을 수정합니다. 모델 API 키 검증을 수행하는 부분입니다.
import logging
from dify_plugin.entities.model import ModelType
from dify_plugin.errors.model import CredentialsValidateFailedError
from dify_plugin import ModelProvider
logger = logging.getLogger(__name__)
class HyperCLOVAXProvider(ModelProvider):
def validate_provider_credentials(self, credentials: dict) -> None:
"""
Validate provider credentials
if validate failed, raise exception
:param credentials: provider credentials, credentials form defined in `provider_credential_schema`.
"""
try:
model_instance = self.get_model_instance(ModelType.LLM)
model_instance.validate_credentials(
model="HCX-005", credentials=credentials
)
except CredentialsValidateFailedError as ex:
raise ex
except Exception as ex:
logger.exception(
f"{self.get_provider_schema().provider} credentials validate failed"
)
raise ex
다음으로 provider/{플러그인 이름}.yaml 파일을 수정합니다. 제공자의 API 키 등을 설정하는 부분입니다.
provider: hyperclovax
label:
en_US: hyperclovax
description:
en_US: hyperclovax models.
icon_small:
en_US: icon.svg
icon_large:
en_US: icon.svg
background: "#F0F0EB"
help:
title:
en_US: Get your API Key from hyperclovax
url:
en_US: https://www.ncloud.com/v2/product/aiService/clovaStudio
supported_model_types:
- llm # LLM 모델만 제공합니다.
configurate_methods:
- predefined-model
# Provider-level credential form definition
provider_credential_schema:
credential_form_schemas:
- variable: api_key
label:
en_US: API Key를 설정하세요.
type: secret-input
required: true
placeholder:
en_US: API Key
# Model configuration
models:
llm: # Configuration for LLM type models
predefined:
- "models/llm/*.yaml" # Pattern to locate model configuration files
position: "models/llm/_position.yaml" # File defining display order
# Implementation file locations
extra:
python:
provider_source: provider/ons-test-plugin.py # Provider class implementation
model_sources:
- "models/llm/llm.py" # Model implementation file
모델 제공자 플러그인이 완성되었습니다.
플러그인 디버깅을 실행하면, 모델 제공자 설정 화면에 플러그인이 나타납니다. 설정 버튼을 눌러 권한 이름과 API KEY를 적어주면 HCX-007과 HCX-005 를 사용할 수 있습니다.
다음 튜토리얼에서는 플러그인을 difypkg으로 패키징하는 방법을 알아보겠습니다. 수고하셨습니다.
다음 튜토리얼: 3. 패키징
오픈네트웍시스템 변재우