파이프라인 직렬화

파이프라인 직렬화 (Pipeline YAML)

파이프라인을 YAML로 저장하고 다시 불러오는 직렬화(serialization)를 다뤄 볼게요. 직렬화된 파이프라인은 디스크나 데이터베이스에 저장할 수 있고, 네트워크로 보낼 수도 있어요. 특히 YAML은 사람이 보면서 바로 고치기 좋아서, Python 코드를 오가며 수정할 필요가 없어요.

출처: 공식문서

개요

이 튜토리얼에서는 아주 단순한 파이프라인을 Python으로 만들고, 이를 YAML로 직렬화한 뒤, YAML에서 수정하고 다시 Haystack Pipeline으로 복원(deserialize)하는 과정을 볼 거예요.

설치

pip install haystack-ai transformers-haystack

단순 파이프라인 만들기

사용자에게 topic을 받아 Qwen/Qwen2.5-1.5B-Instruct 모델로 그 주제에 대한 요약을 생성하는 파이프라인을 만들어요. 여기서는 Hugging Face의 비교적 작은 오픈소스 LLM을 로컬로 사용해요.

from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.transformers import TransformersChatGenerator

template = [
    ChatMessage.from_user(
        """
Please create a summary about the following topic:
{{ topic }}
"""
    )
]

builder = ChatPromptBuilder(template=template)
llm = TransformersChatGenerator(model="Qwen/Qwen2.5-1.5B-Instruct", generation_kwargs={"max_new_tokens": 150})

pipeline = Pipeline()
pipeline.add_component(name="builder", instance=builder)
pipeline.add_component(name="llm", instance=llm)

pipeline.connect("builder.prompt", "llm.messages")

테스트로 실행하면 요약 텍스트가 나와요.

topic = "Climate change"
result = pipeline.run(data={"builder": {"topic": topic}})
print(result["llm"]["replies"][0].text)

YAML로 직렬화하기

dumps()를 호출하면 파이프라인이 YAML 문자열로 변환돼요.

yaml_pipeline = pipeline.dumps()

print(yaml_pipeline)

결과 YAML에는 각 컴포넌트의 타입초기화 파라미터, 그리고 컴포넌트 간 연결(connections) 정보가 들어 있어요. 예를 들면 이런 구조예요.

components:
  builder:
    init_parameters:
      required_variables: null
      template:
      - content:
        - text: '

            Please create a summary about the following topic:

            {{ topic }}

            '
        meta: {}
        name: null
        role: user
      variables: null
    type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder
  llm:
    init_parameters:
      chat_template: null
      enable_thinking: false
      generation_kwargs:
        max_new_tokens: 150
        return_full_text: false
        stop_sequences: []
      huggingface_pipeline_kwargs:
        device: cpu
        model: Qwen/Qwen2.5-1.5B-Instruct
        task: text-generation
      streaming_callback: null
      token:
        env_vars:
        - HF_API_TOKEN
        - HF_TOKEN
        strict: false
        type: env_var
      tool_parsing_function: haystack_integrations.components.generators.transformers.chat.chat_generator.default_tool_parser
      tools: null
    type: haystack_integrations.components.generators.transformers.chat.chat_generator.TransformersChatGenerator
connection_type_validation: true
connections:
- receiver: llm.messages
  sender: builder.prompt
max_runs_per_component: 100
metadata: {}

YAML에서 파이프라인 편집하기

직렬화된 파이프라인은 YAML을 직접 고쳐서 바꿀 수 있어요. 아래 예시는 ChatPromptBuilder의 템플릿을 '주어진 sentence를 프랑스어로 번역'하도록 수정한 YAML이에요. 컴포넌트 타입이나 연결은 그대로 두고 템플릿 텍스트만 바꿨어요.

components:
  builder:
    init_parameters:
      required_variables: null
      template:
      - content:
        - text: 'Please translate the following to French: \n{{ sentence }}\n'
        meta: {}
        name: null
        role: user
      variables: null
    type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder
  llm:
    init_parameters:
      chat_template: "{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ '  ' }}{% endif %}{% endfor %}{{ eos_token }}"
      enable_thinking: false
      generation_kwargs:
        max_new_tokens: 150
        return_full_text: false
        stop_sequences: []
      huggingface_pipeline_kwargs:
        device: cpu
        model: Qwen/Qwen2.5-1.5B-Instruct
        task: text-generation
      streaming_callback: null
      token:
        env_vars:
        - HF_API_TOKEN
        - HF_TOKEN
        strict: false
        type: env_var
      tool_parsing_function: haystack_integrations.components.generators.transformers.chat.chat_generator.default_tool_parser
      tools: null
    type: haystack_integrations.components.generators.transformers.chat.chat_generator.TransformersChatGenerator
connection_type_validation: true
connections:
- receiver: llm.messages
  sender: builder.prompt
max_runs_per_component: 100
metadata: {}

YAML 파이프라인을 Python으로 복원하기

loads()를 호출하면 YAML을 다시 Haystack Pipeline으로 되돌릴 수 있어요.

from haystack import Pipeline

new_pipeline = Pipeline.loads(yaml_pipeline)

수정한 내용대로 이제 ChatPromptBuildersentence를 받아서 프랑스어로 번역해요.

new_pipeline.run(data={"builder": {"sentence": "I love capybaras"}})

더 알아보기