การกำหนดลายเซ็นและโมดูล
ไวยากรณ์ลายเซ็น ChainOfThought, ReAct และโมดูล DSPy แบบกำหนดเอง
การกำหนดลายเซ็นและโมดูล เป็นบทเรียน AI Prompt Engineering ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Prompt Engineering และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Prompt Engineering มีบทเรียนทั้งหมด 4 บทเรียน
signature คือสัญญาที่ระบุชนิดข้อมูล
signature ของ DSPy คือคลาส Python ที่ประกาศอินพุตและเอาต์พุตของขั้นตอนการให้เหตุผล ให้มองว่าเป็นสัญญาของฟังก์ชันที่ระบุชนิดข้อมูลสำหรับการเรียก LLM
คำอธิบายเอกสารจะกลายเป็นคำอธิบายงาน ส่วนคำกำกับฟิลด์จะบอก DSPy ว่าต้องสร้างอะไร คุณไม่ต้องเขียนข้อความพรอมป์ต์จริง เพราะ DSPy จะอนุมานข้อความนั้นจากการประกาศนี้
การกำหนด signature พื้นฐาน
signature ขั้นต่ำจะสืบทอดจาก dspy.Signature และกำกับฟิลด์ด้วย InputField หรือ OutputField คำอธิบายเอกสารของคลาสจะระบุคำสั่งของงาน
import dspy
class QASignature(dspy.Signature):
"""Answer the question based on the given context."""
context: str = dspy.InputField(desc='Relevant background text')
question: str = dspy.InputField(desc='The question to answer')
answer: str = dspy.OutputField(desc='A concise answer')
# Inspect what DSPy sees
print(QASignature.instructions) # The docstring
print(list(QASignature.input_fields.keys())) # ['context', 'question']
print(list(QASignature.output_fields.keys())) # ['answer']ฟิลด์เอาต์พุตหลายรายการ
signature สามารถมีฟิลด์เอาต์พุตหลายรายการได้ DSPy จะสั่งให้โมเดลสร้างเอาต์พุตทั้งหมดในการเรียกครั้งเดียว เหมาะสำหรับการดึงข้อมูลที่มีโครงสร้าง
import dspy
class EntityExtraction(dspy.Signature):
"""Extract named entities from the text."""
text: str = dspy.InputField()
people: list[str] = dspy.OutputField(desc='List of person names mentioned')
organizations: list[str] = dspy.OutputField(desc='List of organization names')
locations: list[str] = dspy.OutputField(desc='List of place names')
extractor = dspy.Predict(EntityExtraction)
result = extractor(text='Elon Musk founded SpaceX in Hawthorne, California.')
print(result.people, result.organizations, result.locations)โมดูล Predict
dspy.Predict คือโมดูลที่เรียบง่ายที่สุด โดยรับ signature แล้วขอให้ LM สร้างเอาต์พุตโดยตรง ไม่มีการเพิ่มโครงสร้างการให้เหตุผล มีเพียงพรอมป์ต์ที่มีโครงสร้างและสอดคล้องกับ signature
ใช้ Predict เมื่องานตรงไปตรงมาและไม่จำเป็นต้องมีขั้นตอนการให้เหตุผลอย่างชัดเจน
import dspy
class Classify(dspy.Signature):
"""Classify the sentiment of the review."""
review: str = dspy.InputField()
sentiment: str = dspy.OutputField(desc='positive, negative, or neutral')
# Predict wraps the signature with a direct prompt
classifier = dspy.Predict(Classify)
result = classifier(review='The food was amazing and the service was excellent!')
print(result.sentiment) # positiveโมดูล ChainOfThought
dspy.ChainOfThought จะเพิ่มฟิลด์ reasoning ระหว่างกลางให้กับ signature โมเดลจะเขียนเหตุผลของตนเองก่อน แล้วจึงสร้างคำตอบสุดท้าย
วิธีนี้ช่วยเพิ่มความแม่นยำของปัญหาหลายขั้นตอนได้อย่างสม่ำเสมอ โดยที่คุณไม่ต้องเขียนคำสั่งพรอมป์ต์สำหรับการให้เหตุผลเป็นลำดับด้วยตนเอง
import dspy
class MathSolver(dspy.Signature):
"""Solve the math problem."""
problem: str = dspy.InputField()
answer: str = dspy.OutputField(desc='The numerical answer')
# ChainOfThought adds a 'reasoning' step automatically
solver = dspy.ChainOfThought(MathSolver)
result = solver(problem='If a train travels 60 mph for 2.5 hours, how far does it go?')
print(result.reasoning) # Step-by-step reasoning
print(result.answer) # 150 milesโมดูล ReAct
dspy.ReAct ใช้วงจรการให้เหตุผลและการลงมือทำ โมเดลจะสลับระหว่างขั้นตอนการให้เหตุผลกับการเรียกใช้เครื่องมือ จึงเหมาะอย่างยิ่งสำหรับตัวแทนที่ต้องค้นหา คำนวณ หรือดึงข้อมูล
คุณจัดเตรียมรายการเครื่องมือ (ฟังก์ชัน Python ที่มีคำอธิบายเอกสาร) แล้ว DSPy จะจัดการสลับการทำงานให้โดยอัตโนมัติ
import dspy
def search_web(query: str) -> str:
"""Search the web and return relevant results."""
# In production, call a real search API
return f'Search results for: {query}'
def calculate(expression: str) -> str:
"""Evaluate a mathematical expression."""
return str(eval(expression))
class ResearchQA(dspy.Signature):
"""Answer the question using web search and calculation as needed."""
question: str = dspy.InputField()
answer: str = dspy.OutputField()
agent = dspy.ReAct(ResearchQA, tools=[search_web, calculate])
result = agent(question='What is 15% of 847?')
print(result.answer)การนำโมดูลมาประกอบเป็นโปรแกรม
พลังที่แท้จริงเกิดจากการนำโมดูลมาประกอบเป็นโปรแกรมหลายขั้น สืบทอดจาก dspy.Module กำหนดโมดูลย่อยใน __init__ และใช้งาน forward() เพื่อเชื่อมโมดูลเหล่านั้นเข้าด้วยกัน
import dspy
class RetrieveAndAnswer(dspy.Module):
def __init__(self):
super().__init__()
self.retrieve = dspy.Retrieve(k=3) # Retrieves top-3 passages
self.generate = dspy.ChainOfThought('context, question -> answer')
def forward(self, question):
passages = self.retrieve(question).passages
context = '\n'.join(passages)
return self.generate(context=context, question=question)
# This is a complete RAG pipeline in ~10 lines
rag = RetrieveAndAnswer()
result = rag(question='What are the main causes of climate change?')
print(result.answer)รูปแบบย่อของ signature แบบเขียนในบรรทัด
สำหรับกรณีง่าย ๆ DSPy รองรับสตริง signature แบบเขียนในบรรทัด: 'input1, input2 -> output1, output2' วิธีนี้สะดวกสำหรับการสร้างต้นแบบอย่างรวดเร็วโดยไม่ต้องกำหนดคลาสเต็มรูปแบบ
import dspy
# Full class signature
class Translate(dspy.Signature):
"""Translate text to French."""
text: str = dspy.InputField()
translation: str = dspy.OutputField()
# Equivalent inline shorthand
translator_v1 = dspy.Predict(Translate)
translator_v2 = dspy.Predict('text -> translation') # Less metadata
# Both work the same way
result = translator_v1(text='Hello world')
print(result.translation)คำอธิบายฟิลด์มีความสำคัญ
พารามิเตอร์ desc ใน InputField และ OutputField จะถูกใส่ไว้ในพรอมป์ต์ที่สร้างขึ้น คำอธิบายที่ดีจะชี้นำโมเดลได้อย่างแม่นยำ
ให้มอง desc เป็นเอกสารระดับฟิลด์ที่ปรากฏในพรอมป์ต์ข้างชื่อฟิลด์
import dspy
class Summarize(dspy.Signature):
"""Summarize the article for a busy executive."""
article: str = dspy.InputField(
desc='The full article text to summarize'
)
summary: str = dspy.OutputField(
desc='3-5 bullet points highlighting key decisions and numbers'
)
confidence: float = dspy.OutputField(
desc='Your confidence in the summary accuracy from 0.0 to 1.0'
)
summarizer = dspy.Predict(Summarize)
# DSPy constructs a prompt using all the desc values automaticallyการบันทึกและโหลดโปรแกรม
หลังการเพิ่มประสิทธิภาพ ให้บันทึกโปรแกรมที่คอมไพล์แล้ว เพื่อไม่ต้องเรียกใช้การเพิ่มประสิทธิภาพใหม่ทุกครั้ง DSPy จะแปลงสถานะที่เพิ่มประสิทธิภาพแล้วเป็นไฟล์ JSON
import dspy
class QA(dspy.Signature):
"""Answer questions accurately."""
question: str = dspy.InputField()
answer: str = dspy.OutputField()
program = dspy.ChainOfThought(QA)
# After optimization, save the compiled state
program.save('optimized_qa.json')
# Load it later without re-running optimization
loaded_program = dspy.ChainOfThought(QA)
loaded_program.load('optimized_qa.json')
result = loaded_program(question='What is the speed of light?')
print(result.answer)การยืนยันเงื่อนไขสำหรับจำกัดเอาต์พุต
การยืนยันเงื่อนไขของ DSPy ช่วยให้คุณประกาศข้อจำกัดของเอาต์พุตได้ หากโมเดลไม่ปฏิบัติตามข้อจำกัด DSPy จะลองใหม่โดยอัตโนมัติพร้อมข้อเสนอแนะเพื่อแก้ไข โดยไม่ต้องเขียนตรรกะสำหรับการลองใหม่ด้วยตนเอง
import dspy
class ShortAnswer(dspy.Signature):
"""Answer in at most 10 words."""
question: str = dspy.InputField()
answer: str = dspy.OutputField()
class ConstrainedQA(dspy.Module):
def __init__(self):
super().__init__()
self.predict = dspy.Predict(ShortAnswer)
def forward(self, question):
result = self.predict(question=question)
# Assert: answer must be at most 10 words
dspy.Assert(
len(result.answer.split()) <= 10,
'The answer must be 10 words or fewer.'
)
return resultตรวจสอบความรู้: ChainOfThought
dspy.ChainOfThought เพิ่มอะไรเมื่อเทียบกับ dspy.Predict หากใช้ signature เดียวกัน
ทบทวน: signature และโมดูล
signature ของ DSPy คือการประกาศคลาสที่ระบุชนิดข้อมูล ซึ่งอธิบายว่างานแต่ละขั้นของ LLM ควรทำอะไร ทั้งอินพุต เอาต์พุต และคำสั่งในคำอธิบายเอกสาร โมดูลอย่าง Predict, ChainOfThought และ ReAct ใช้กลยุทธ์การให้เหตุผลที่แตกต่างกันกับ signature คุณนำหลายโมดูลมาประกอบภายในคลาสย่อยของ dspy.Module เพื่อสร้างกระบวนการประมวลผลหลายขั้น ค่า desc ของฟิลด์จะชี้นำโมเดลภายในพรอมป์ต์ที่สร้างโดยอัตโนมัติ และการยืนยันเงื่อนไขจะบังคับใช้ข้อจำกัดของเอาต์พุตพร้อมการลองใหม่โดยอัตโนมัติ
เรียนรู้ AI Prompt Engineering ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 53
- บทเรียน
- 199
คำถามที่พบบ่อย
บทเรียน “การกำหนดลายเซ็นและโมดูล” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การกำหนดลายเซ็นและโมดูล” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Prompt Engineering ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Prompt Engineering มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การกำหนดลายเซ็นและโมดูล”
ไวยากรณ์ลายเซ็น ChainOfThought, ReAct และโมดูล DSPy แบบกำหนดเอง คุณปฏิบัติ AI Prompt Engineering ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Prompt Engineering หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Prompt Engineering บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การกำหนดลายเซ็นและโมดูล” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Prompt Engineering นี้ได้ไหม
ได้ บทเรียน AI Prompt Engineering ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- บทนำสู่เฟรมเวิร์ก DSPy
- การกำหนดลายเซ็นและโมดูล
- การคอมไพล์และปรับพรอมต์ให้เหมาะที่สุด
- การประเมินไปป์ไลน์ DSPy