Chuyển tới nội dung chính

{/* Trang này được tạo tự động từ SKILL.md của kỹ năng bởi website/scripts/generate-skill-docs.py. Chỉnh sửa nguồn SKILL.md, không phải trang này. */}

Dspy

DSPy: chương trình LM khai báo, lời nhắc tự động tối ưu hóa, RAG.

Siêu dữ liệu kỹ năng

NguồnĐi kèm (được cài đặt theo mặc định)
Đường dẫn

skills/mlops/research/dspy ` | | Phiên bản |

1.0.0 ` | | Tác giả | Nghiên cứu dàn nhạc | | Giấy phép | MIT | | Phụ thuộc |

dspy

, `OpenAI

, Anthropic | | Nền tảng | Linux, macOS, Windows | | Thẻ |

Prompt Engineering

, `DSPy

, `Declarative Programming

, `RAG

, `Agents

, `Prompt Optimization

, `LM Programming

, `Stanford NLP

, `Automatic Optimization

, Modular AI |

Tham khảo: đầy đủ SKILL.md

thông tin

Sau đây là định nghĩa kỹ năng đầy đủ mà Hermes tải khi kỹ năng này được kích hoạt. Đây là những gì tác nhân coi là hướng dẫn khi kỹ năng được kích hoạt.

DSPy: Lập trình mô hình ngôn ngữ khai báo

Khi nào nên sử dụng kỹ năng này

Sử dụng DSPy khi bạn cần:

  • Xây dựng hệ thống AI phức tạp với nhiều thành phần và quy trình làm việc
  • Lập trình LM theo cách khai báo thay vì kỹ thuật nhắc nhở thủ công
  • Tự động tối ưu hóa lời nhắc bằng các phương pháp dựa trên dữ liệu
  • Tạo quy trình AI mô-đun có thể bảo trì và di động
  • Cải thiện kết quả mô hình một cách có hệ thống bằng trình tối ưu hóa
  • Xây dựng hệ thống, tác nhân hoặc bộ phân loại RAG với độ tin cậy tốt hơn`Sao GitHub: 22.000+ | Được tạo bởi: Stanford NLP

Cài đặt


# Stable release
pip install dspy

# Latest development version
pip install git+https://GitHub.com/stanfordnlp/dspy.git

# With specific LM providers
pip install dspy[OpenAI] # OpenAI
pip install dspy[Anthropic] # Anthropic Claude
pip install dspy[all] # All providers

`

## Bắt đầu nhanh

### Ví dụ cơ bản: Trả lời câu hỏi

``` python
import dspy

# Configure your language model
lm = dspy.Claude(model="Claude-sonnet-4-5-20250929")
dspy.settings.configure(lm=lm)

# Define a signature (input → output)
class QA(dspy.Signature):
"""Answer questions with short factual answers."""
question = dspy.InputField()
answer = dspy.OutputField(desc="often between 1 and 5 words")

# Create a module
qa = dspy.Predict(QA)

# Use it
response = qa(question="What is the cAPItal of France?")
print(response.answer) # "Paris"

`

### Chuỗi suy nghĩ suy luận

`Python
import dspy`lm = dspy.Claude(model="Claude-sonnet-4-5-20250929")
dspy.settings.configure(lm=lm)

# Use ChainOfThought for better reasoning
class MathProblem(dspy.Signature):
"""Solve math word problems."""
problem = dspy.InputField()
answer = dspy.OutputField(desc="numerical answer")

# ChainOfThought generates reasoning steps automatically
cot = dspy.ChainOfThought(MathProblem)

response = cot(problem="If John has 5 Apples and gives 2 to Mary, how many does he have?")
print(response.rationale) # Shows reasoning steps
print(response.answer) # "3"

`

## Khái niệm cốt lõi

### 1. Chữ ký

Chữ ký xác định cấu trúc nhiệm vụ AI của bạn (đầu vào → đầu ra):

`Python

# Inline signature (simple)
qa = dspy.Predict("question -> answer")

# Class signature (detailed)
class Summarize(dspy.Signature):
"""Summarize text into key points."""
text = dspy.InputField()
summary = dspy.OutputField(desc="bullet points, 3-5 items")

summarizer = dspy.ChainOfThought(Summarize)

`
``**Khi nào nên sử dụng từng loại:**
- **Nội tuyến**: Tạo mẫu nhanh, tác vụ đơn giản
- **Lớp**: Nhiệm vụ phức tạp, gợi ý gõ, tài liệu tốt hơn

### 2. Mô-đun

Mô-đun là các thành phần có thể tái sử dụng để chuyển đổi đầu vào thành đầu ra:

#### dspy.Predict
Mô-đun dự đoán cơ bản:

``` python
predictor = dspy.Predict("context, question -> answer")
result = predictor(context="Paris is the cAPItal of France",
question="What is the cAPItal?")

`

#### dspy.ChainOfThought
Tạo các bước lý luận trước khi trả lời:

`Python
cot = dspy.ChainOfThought("question -> answer")
result = cot(question="Why is the sky blue?")
print(result.rationale) # Reasoning steps
print(result.answer) # Final answer

`

#### dspy.ReAct
Lý luận giống như tác nhân với các công cụ:

`Python
from dspy.predict import ReAct`class SearchQA(dspy.Signature):
"""Answer questions using search."""
question = dspy.InputField()
answer = dspy.OutputField()

def search_tool(query: str) -> str:
"""Search Wikipedia."""

# Your search implementation
return results`react = ReAct(SearchQA, tools=[search_tool])
result = react(question="When was Python created?")

`

#### dspy.ProgramOfThought
Tạo và thực thi mã để suy luận:

``` python
pot = dspy.ProgramOfThought("question -> answer")
result = pot(question="What is 15% of 240?")

# Generates: answer = 240 * 0.15

`

### 3. Trình tối ưu hóa

Trình tối ưu hóa tự động cải thiện các mô-đun của bạn bằng cách sử dụng dữ liệu đào tạo:

#### BootstrapFewShot
Học từ các ví dụ:

``` python
from dspy.teleprompt import BootstrapFewShot

# Training data
trainset = [
dspy.Example(question="What is 2+2?", answer="4").with_inputs("question"),
dspy.Example(question="What is 3+5?", answer="8").with_inputs("question"),
]

# Define metric
def validate_answer(example, pred, trace=None):
return example.answer == pred.answer

# Optimize
optimizer = BootstrapFewShot(metric=validate_answer, max_bootstrapped_demos=3)
optimiZed_qa = optimizer.compile(qa, trainset=trainset)

# Now optimiZed_qa performs better!

`

#### MIPRO (Tối ưu hóa lời nhắc quan trọng nhất)
Lặp đi lặp lại cải thiện lời nhắc:

`Python
from dspy.teleprompt import MIPRO`optimizer = MIPRO(
metric=validate_answer,
num_candidates=10,
init_temperature=1.0
)

optimiZed_cot = optimizer.compile(
cot,
trainset=trainset,
num_trials=100
)

`

#### BootstrapFinetune
Tạo bộ dữ liệu để tinh chỉnh mô hình:

`Python
from dspy.teleprompt import BootstrapFinetune`optimizer = BootstrapFinetune(metric=validate_answer)
optimiZed_module = optimizer.compile(qa, trainset=trainset)

# Exports training data for fine-tuning

`

### 4. Xây dựng hệ thống phức hợp

#### Đường ống nhiều giai đoạn

`Python
import dspy`class MultiHopQA(dspy.Module):
def __init__(self):
super().__init__()
self.retrieve = dspy.Retrieve(k=3)
self.generate_query = dspy.ChainOfThought("question -> search_query")
self.generate_answer = dspy.ChainOfThought("context, question -> answer")

def forward(self, question):

# Stage 1: Generate search query
search_query = self.generate_query(question=question).search_query

# Stage 2: Retrieve context
passages = self.retrieve(search_query).passages
context = "\n".join(passages)

# Stage 3: Generate answer
answer = self.generate_answer(context=context, question=question).answer
return dspy.Prediction(answer=answer, context=context)

# Use the pipeline
qa_system = MultiHopQA()
result = qa_system(question="Who wrote the book that inspired the movie Blade Runner?")

`

#### Hệ thống RAG được tối ưu hóa

``` python
import dspy
from dspy.retrieve.ChromaDB_rm import ChromaDBRM

# Configure retriever
retriever = ChromaDBRM(
collection_name="documents",
persist_directory="./chroma_db"
)

class RAG(dspy.Module):
def __init__(self, num_passages=3):
super().__init__()
self.retrieve = dspy.Retrieve(k=num_passages)
self.generate = dspy.ChainOfThought("context, question -> answer")

def forward(self, question):
context = self.retrieve(question).passages
return self.generate(context=context, question=question)

# Create and optimize
rag = RAG()

# Optimize with training data
from dspy.teleprompt import BootstrapFewShot`optimizer = BootstrapFewShot(metric=validate_answer)
optimiZed_rag = optimizer.compile(rag, trainset=trainset)

`

## Cấu hình nhà cung cấp LM

### Claude nhân loại

`Python
import dspy`lm = dspy.Claude(
model="Claude-sonnet-4-5-20250929",
API_key="your-API-key", # Or set Anthropic_API_KEY env var
max_tokens=1000,
temperature=0.7
)
dspy.settings.configure(lm=lm)

`

### OpenAI

`Python
lm = dspy.OpenAI(
model="GPT-4",
API_key="your-API-key",
max_tokens=1000
)
dspy.settings.configure(lm=lm)

`

### Mô hình địa phương (OLlama)

`Python
lm = dspy.OLlamaLocal(
model="Llama3.1",
base_url="http://localhost:11434"
)
dspy.settings.configure(lm=lm)

`

### Nhiều mô hình

`Python

# Different models for different tasks
cheap_lm = dspy.OpenAI(model="GPT-3.5-turbo")
strong_lm = dspy.Claude(model="Claude-sonnet-4-5-20250929")

# Use cheap model for retrieval, strong model for reasoning
with dspy.settings.context(lm=cheap_lm):
context = retriever(question)

with dspy.settings.context(lm=strong_lm):
answer = generator(context=context, question=question)

`

## Các mẫu phổ biến

### Mẫu 1: Đầu ra có cấu trúc

``` python
from pydantic import BaseModel, Field`class PersonInfo(BaseModel):
name: str = Field(description="Full name")
age: int = Field(description="Age in years")
occupation: str = Field(description="Current job")

class ExtractPerson(dspy.Signature):
"""Extract person information from text."""
text = dspy.InputField()
person: PersonInfo = dspy.OutputField()

extractor = dspy.TypedPredictor(ExtractPerson)
result = extractor(text="John Doe is a 35-year-old software engineer.")
print(result.person.name) # "John Doe"
print(result.person.age) # 35

`

### Mẫu 2: Tối ưu hóa dựa trên khẳng định

`Python
import dspy
from dspy.primitives.assertions import assert_transform_module, backtrack_handler`class MathQA(dspy.Module):
def __init__(self):
super().__init__()
self.solve = dspy.ChainOfThought("problem -> solution: float")

def forward(self, problem):
solution = self.solve(problem=problem).solution

# Assert solution is numeric
dspy.Assert(
isinstance(float(solution), float),
"Solution must be a number",
backtrack=backtrack_handler
)

return dspy.Prediction(solution=solution)

`

### Mẫu 3: Tự chủ

`Python
import dspy
from collections import Counter`class ConsistentQA(dspy.Module):
def __init__(self, num_samples=5):
super().__init__()
self.qa = dspy.ChainOfThought("question -> answer")
self.num_samples = num_samples`def forward(self, question):

# Generate multiple answers
answers = []
for _ in range(self.num_samples):
result = self.qa(question=question)
answers.append(result.answer)

# Return most common answer
most_common = Counter(answers).most_common(1)[0][0]
return dspy.Prediction(answer=most_common)

`

### Mẫu 4: Truy xuất bằng sắp xếp lại

``` python
class RerankedRAG(dspy.Module):
def __init__(self):
super().__init__()
self.retrieve = dspy.Retrieve(k=10)
self.rerank = dspy.Predict("question, passage -> relevance_score: float")
self.answer = dspy.ChainOfThought("context, question -> answer")

def forward(self, question):

# Retrieve candidates
passages = self.retrieve(question).passages

# Rerank passages
scored = []
for passage in passages:
score = float(self.rerank(question=question, passage=passage).relevance_score)
scored.append((score, passage))

# Take top 3
top_passages = [p for _, p in sorted(scored, reverse=True)[:3]]
context = "\n\n".join(top_passages)

# Generate answer
return self.answer(context=context, question=question)

`

## Đánh giá và đo lường

### Số liệu tùy chỉnh

``` python
def exact_match(example, pred, trace=None):
"""Exact match metric."""
return example.answer.lower() == pred.answer.lower()

def f1_score(example, pred, trace=None):
"""F1 score for text overlap."""
pred_tokens = set(pred.answer.lower().split())
gold_tokens = set(example.answer.lower().split())

if not pred_tokens:
return 0.0`precision = len(pred_tokens & gold_tokens) / len(pred_tokens)
recall = len(pred_tokens & gold_tokens) / len(gold_tokens)

if precision + recall == 0:
return 0.0`return 2 * (precision * recall) / (precision + recall)

`

### Đánh giá

`Python
from dspy.evaluate import Evaluate

# Create evaluator
evaluator = Evaluate(
devset=testset,
metric=exact_match,
num_threads=4,
display_progress=True
)

# Evaluate model
score = evaluator(qa_system)
print(f"Accuracy: \{score}")

# Compare optimiZed vs unoptimiZed
score_before = evaluator(qa)
score_after = evaluator(optimiZed_qa)
print(f"Improvement: \{score_after - score_before:.2%}")

`

## Các phương pháp hay nhất

### 1. Bắt đầu đơn giản, lặp lại

`Python

# Start with Predict
qa = dspy.Predict("question -> answer")

# Add reasoning if needed
qa = dspy.ChainOfThought("question -> answer")

# Add optimization when you have data
optimiZed_qa = optimizer.compile(qa, trainset=data)

`

### 2. Sử dụng chữ ký mô tả

``` python

# ❌ Bad: Vague
class Task(dspy.Signature):
input = dspy.InputField()
output = dspy.OutputField()

# ✅ Good: Descriptive
class SummarizeArticle(dspy.Signature):
"""Summarize news articles into 3-5 key points."""
article = dspy.InputField(desc="full article text")
summary = dspy.OutputField(desc="bullet points, 3-5 items")

`

### 3. Tối ưu hóa với dữ liệu đại diện

``` python

# Create diverse training examples
trainset = [
dspy.Example(question="factual", answer="...).with_inputs("question"),
dspy.Example(question="reasoning", answer="...").with_inputs("question"),
dspy.Example(question="calculation", answer="...").with_inputs("question"),
]

# Use validation set for metric
def metric(example, pred, trace=None):
return example.answer in pred.answer

`

### 4. Lưu và tải các mô hình đã tối ưu hóa

``` python

# Save
optimiZed_qa.save("models/qa_v1.JSON")

# Load
loaded_qa = dspy.ChainOfThought("question -> answer")
loaded_qa.load("models/qa_v1.JSON")

`

### 5. Giám sát và gỡ lỗi

``` python

# Enable tracing
dspy.settings.configure(lm=lm, trace=[])

# Run prediction
result = qa(question="...")

# Inspect trace
for call in dspy.settings.trace:
print(f"Prompt: \{call['prompt']}")
print(f"Response: \{call['response']}")

`

## So sánh với các phương pháp tiếp cận khác

| Tính năng | Nhắc thủ công | LangChain | DSPy |
|----------|--------|-------------|------|
| Kỹ thuật nhanh chóng | Hướng dẫn sử dụng | Hướng dẫn sử dụng | Tự động |
| Tối Ưu Hóa | Dùng thử và sai sót | Không có | Dựa trên dữ liệu |
| Tính mô đun | Thấp | Trung bình | Cao |
| Loại An toàn | Không | Hạn chế |(Chữ ký) |
| Tính di động | Thấp | Trung bình | Cao |
| Đường cong học tập | Thấp | Trung bình | Trung bình-Cao |

**Khi nào nên chọn DSPy:**
- Bạn có dữ liệu đào tạo hoặc có thể tạo ra nó
- Bạn cần cải tiến kịp thời một cách có hệ thống
- Bạn đang xây dựng các hệ thống nhiều giai đoạn phức tạp
- Bạn muốn tối ưu hóa trên các LM khác nhau**Khi nào nên chọn phương án thay thế:**
- Nguyên mẫu nhanh (nhắc thủ công)
- Chuỗi đơn giản với các công cụ hiện có (LangChain)
- Cần có logic tối ưu hóa tùy chỉnh

## Tài nguyên
- **Tài liệu**: https://dspy.ai
- **GitHub**: https://GitHub.com/stanfordnlp/dspy (22k+ sao)
- **Discord**: https://Discord.gg/XCGy2WDCQB
- **Twitter**: @DSPYOSS
- **Giấy**: "DSPy: Biên dịch các lệnh gọi mô hình ngôn ngữ khai báo thành các quy trình tự cải tiến"

## Xem thêm
-
`references/modules.md

- Hướng dẫn module chi tiết (Dự đoán, ChainOfThought, ReAct, ProgramOfThought)
-
`references/optimizers.md

- Thuật toán tối ưu hóa (BootstrapFewShot, MIPRO, BootstrapFinetune)
-
`references/examples.md

- Ví dụ thực tế (RAG, tác nhân, bộ phân loại)