วิธีใช้ Haystack 2.0 เชื่อมต่อ LLM ด้วย Python ใน 4 ขั้นตอน

ในบทความก่อน ผมพาทุกคนไปรู้จักกับการใช้ LangChain ซึ่งเป็น package ยอดนิยมสำหรับสร้าง LLM (large language model) application อย่าง chatbot

ในบทความนี้ ผมจะพาทุกคนไปรู้จักกับ Haystack 2.0 ซึ่งเป็นอีกหนึ่ง package ที่ทำงานได้เหมือนกับ LangChain

แม้ว่า LangChain เป็นที่นิยมและใช้งานง่าย แต่ก็แลกมาด้วยข้อจำกัดใน “การมองเห็น” เพราะ LangChain ซ่อนการทำงานหลาย ๆ อย่างไว้หลัง code ไม่กี่บรรัดเพื่อให้เราใช้งานง่าย เมื่อเกิด bug ขึ้นมา เราจะไม่รู้เลยว่า error อยู่ที่จุดไหน จนกว่าเราจะแกะการทำงานเบื้องหลัง code ที่เราเขียนออกมา

Haystack เป็น package ที่มี “การมองเห็น” ที่สูงกว่า เพราะมีการทำงานแบบแยกส่วนประกอบ หรือ component เหมือนกับรถยนต์ที่ประกอบขึ้นมาจากหลายชิ้นส่วน อย่างเครื่องยนต์ ถังน้ำมัน ล้อ และพวงมาลัย เราสามารถกำหนดได้ว่า เราอยากได้ชิ้นส่วนไหนแบบไหน และแต่ละชิ้นส่วนจะประกอบกันยังไง เมื่อเป็นเช่นนี้ เราจะรู้ได้ว่าข้อผิดพลาดอยู่ที่ไหน เพราะเราเป็นคนที่ประกอบทุกอย่างขึ้นมาเอง

ในบทความนี้ ผมจะพาทุกคนไปดูการใช้ Haystack เพื่อเชื่อมต่อกับ LLM ผ่านตัวอย่างการสร้าง AI ตอบคำถามเกี่ยวกับ mental model กัน

ถ้าพร้อมแล้ว ไปเริ่มกันเลย


  1. ⭐️ High-Level View
  2. 📜 Step 1. Create a Prompt Builder
  3. 🤖 Step 2. Create an LLM Instance
  4. 🪈 Step 3. Create a Pipeline
  5. 🏃 Step 4. Run
  6. 💪 Summary
  7. 😺 GitHub
  8. 📃 References

⭐️ High-Level View

ในการใช้ Haystack เชื่อมต่อกับ LLM เราจะใช้ component 3 อย่าง:

  1. Prompt builder สำหรับเก็บ prompt
  2. LLM instance สำหรับเรียก LLM
  3. Pipeline สำหรับเชื่อมทุก component เข้าด้วยกัน

โดยเราจะเรียกใช้งาน 3 components นี้ใน 4 ขั้นตอน:

  1. Create a prompt builder
  2. Create an LLM instance
  3. Create a pipeline
  4. Run

ไปดูตัวอย่างทั้ง 4 ขั้นตอนกัน


📜 Step 1. Create a Prompt Builder

ในขั้นแรก เราจะสร้าง prompt builder สำหรับเก็บ prompt กัน

เราจะเริ่มจากสร้าง system prompt และ user prompt:

Python
# System prompt
system_prompt = """
You are an expert curator of mental models across science, philosophy, and applied reasoning.
Your task is to explain mental models clearly and accurately using a fixed schema.
If the origin of a model is unclear or debated, state that explicitly.
Do not invent historical sources. Be concise and concrete.
"""
# User prompt
user_prompt = "Explain the following mental model: {{model_query}}"

Note: เราใช้ {{}} ใน user prompt เพื่อที่เราจะสร้างแทนที่ค่าใน user prompt ได้ในภายหลัง เช่น ถ้าเราต้องการถามเกี่ยวกับ “First-Principles Thinking” user prompt ของเราก็จะกลายเป็น:

"Explain the following mental model: First-Principles Thinking"

จากนั้น เราจะใส่ prompts ลงใน ChatPromptBuilder():

Python
# Import required packages
from Haystack.components.builders import ChatPromptBuilder
from Haystack.dataclasses import ChatMessage
# Create a prompt builder instance
prompt_builder = ChatPromptBuilder(
template=[
ChatMessage.from_system(system_prompt.strip()),
ChatMessage.from_user(user_prompt)
],
required_variables=["model_query"]
)

Note: เรากำหนด required_variables เพื่อกันไม่ให้ {{model_query}} เป็นค่าว่าง


🤖 Step 2. Create an LLM Instance

ในขั้นที่ 2 เราจะสร้าง LLM instance สำหรับเชื่อมต่อกับ LLM โดยในตัวอย่าง เราจะใช้ Gemini

เราจะเริ่มจากดึง API key ที่เก็บไว้ใน .env:

Python
# Import required packages
import os
# Retrieve the API key
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")

จากนั้น กำหนด structured output หรือหน้าตา output ที่เราต้องการ ด้วย Pydantic:

Python
# Import required packages
from pydantic import BaseModel, Field
from typing import List, Literal
# Define the output schema
class MentalModel(BaseModel):
# Mental model name
model_name: str = Field(
description="The commonly accepted name of the mental model"
)
# Origin or source
origin: str = Field(
description="Where the model comes from (a person, book, field, or cultural origin)"
)
# Brief description
description: str = Field(
description="A brief explanation of what the mental model is and why it matters"
)
# Example
example: str = Field(
description="A concrete real-world example illustrating the mental model"
)
# Tags
tags: List[str] = Field(
description="Short tags such as decision-making, systems thinking, learning, and philosophy"
)

หน้าตา structured output ที่เราจะได้:

{
"model_name": "",
"origin": "",
"description": "",
"example": "",
"tags": []
}

สุดท้าย เราจะใส่ API key และ structured output ลงใน LLM instance:

Python
# Import required packages
from Haystack.utils import Secret
from Haystack_integrations.components.generators.google_genai import GoogleGenAIChatGenerator
# Create an LLM instance
llm_with_structured_output = GoogleGenAIChatGenerator(
model="gemini-2.5-flash",
api_key=Secret.from_token(GEMINI_API_KEY),
generation_kwargs={
"temperature": 0.5,
"response_format": MentalModel
}
)

🪈 Step 3. Create a Pipeline

ในขั้นที่ 3 เราจะเชื่อมต่อ prompt builder และ LLM instance เข้าด้วยกัน

เริ่มจากสร้าง pipeline:

Python
# Import the required package
from Haystack import Pipeline
# Create a pipeline instance
chain = Pipeline()

เพิ่ม prompt builder และ LLM instance ลงใน pipeline:

Python
# Add the prompt builder and LLM instances
chain.add_component(
"prompt_builder", # Name
prompt_builder # Instance
)
chain.add_component(
"llm", # Name
llm_with_structured_output # Instance
)

แล้วเชื่อมต่อ prompt builder และ LLM instance เข้าด้วยกัน:

Python
# Connect the components
chain.connect(
"prompt_builder.prompt", # Sender: prompt from prompt builder
"llm.messages" # Receiver: message from LLM instance
)

Note: เรากำหนดให้ prompt builder ส่ง system และ user prompts ให้เป็น input สำหรับ LLM instance:

Prompt FROM prompt builder
↓
Messages TO LLM instance

🏃 Step 4. Run

ในขั้นสุดท้าย เราจะรัน pipeline และดึงผลลัพธ์ที่ต้องการออกมา

ตัวอย่างเช่น ถามเกี่ยวกับ “Compound Interest”:

Python
# Run the pipeline with a mental-model query
raw_result = chain.run(
data={
"prompt_builder": {"model_query": "Compound Interest"}
}
)

ดึงผลลัพธ์ที่ต้องการ:

Python
# Extract the structured-output text from the raw result
reply_json = raw_result["llm"]["replies"][0].text
# Validate the structured output
result = MentalModel.model_validate_json(reply_json)
# Print the validated structured output
print(result.model_dump())

ผลลัพธ์:

{
"model_name": "Compound Interest",
"origin": (
"Finance, Mathematics. The concept dates back to ancient Mesopotamia, "
"with formalization in mathematics and finance over centuries."
),
"description": (
"Compound interest is the interest on a loan or deposit calculated "
"based on both the initial principal and the accumulated interest from "
"previous periods. It matters because it illustrates exponential growth, "
"where small, consistent gains over time lead to significantly larger "
"returns, making it a powerful force in finance and many other systems."
),
"example": (
"If you invest $1,000 at a 5% annual interest rate, after one year "
"you have $1,050. In the second year, you earn 5% not just on the "
"initial $1,000, but on the full $1,050, resulting in $1,102.50. "
"This 'interest on interest' accelerates growth significantly over "
"decades compared to simple interest."
),
"tags": [
"Finance",
"Growth",
"Long-term thinking",
"Mathematics",
"Systems thinking",
],
}

💪 Summary

ในบทความนี้ เราได้ทำความรู้จักกับ Haystack ซึ่งเป็น package สำหรับสร้าง LLM application กัน

เราได้เรียนเกี่ยวกับ 3 components สำหรับเชื่อมต่อกับ LLM:

  1. Prompt builder
  2. LLM instance
  3. Pipeline

และการเชื่อมต่อกับ LLM ใน 4 ขั้นตอน:

  1. Create a prompt builder
  2. Create an LLM instance
  3. Create a pipeline
  4. Run

😺 GitHub

ดูตัวอย่าง code ทั้งหมดได้ที่ GitHub


📃 References

Comments

One response to “วิธีใช้ Haystack 2.0 เชื่อมต่อ LLM ด้วย Python ใน 4 ขั้นตอน”

  1. … reposted this!

  2. … reposted this!

  3. … reposted this!

  4. … reposted this!

  5. […] ในบทความก่อน ผมได้แนะนำให้ทุกคนได้รู้จักกับ Haystack 2.0 ซึ่งเป็น package สำหรับสร้าง LLM (large language model) application ใน Python […]

Leave a Reply

Discover more from Shi no Shigoto | AI, Data, & Psychology

Subscribe now to keep reading and get access to the full archive.

Continue reading