跳到正文
cccskills
免费在 GitHub 公开

dspy

DSPy is a Python framework from Stanford NLP that replaces hand-written prompts with code: you declare LLM tasks as typed signatures, compose them into modules, and let optimizers (BootstrapFewShot, MIPROv2, GEPA) tune the prompts and few-shot examples against your metric. Use when the user asks about DSPy, signatures, ChainOfThought, ReAct, teleprompters or optimizers, or wants to stop hand-tuning prompts.

中文简介正在准备中。当前显示原文说明。

集成工具OpenAI
查看安装方法

包含的文件(2)

  • SKILL.md6.5 KB
  • _scores.json2.5 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

DSPy — Programming (Not Prompting) LLMs

Overview

DSPy lets you describe what an LLM step takes in and returns (a signature), pick how it should run (Predict, ChainOfThought, ReAct), compose steps in a dspy.Module, and then optimize the whole program with a metric and a few examples. Models are called through LiteLLM-style identifiers such as openai/gpt-4o-mini or gemini/gemini-2.5-flash, so the same code moves between providers. This skill covers the current 3.x API; code written for 2.x (dspy.Assert, dspy.Suggest, dspy.OpenAI(...), dspy.settings.configure) needs porting.

Instructions

Install and configure

pip install -U dspy
export OPENAI_API_KEY=...   # or the key of whichever provider you use
import dspy
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))   # global default

Use with dspy.context(lm=other_lm): to override the model for one call.

Signatures and predictors

A signature is either a string ("question -> answer") or a class with typed fields. Use Literal[...] or other Python types to constrain outputs. Predictors: dspy.Predict, dspy.ChainOfThought (adds a reasoning output field), dspy.ReAct (tool-using agent), dspy.ProgramOfThought.

Modules

Subclass dspy.Module, call super().__init__(), create predictors in __init__, and write the logic in forward. For retrieval, dspy.retrievers.Embeddings(embedder=..., corpus=[...], k=3) is a local in-process retriever (needs numpy); dspy.Retrieve only works after you configure a retrieval model such as dspy.ColBERTv2 via dspy.configure(rm=...).

Evaluate and optimize

  1. Build dspy.Example(...).with_inputs("question") objects (inputs marked, other fields are labels).
  2. Write a metric (example, prediction, trace=None) -> bool | float.
  3. Measure the baseline with dspy.Evaluate(devset=devset, metric=metric, num_threads=8)(program).
  4. Optimize with a teleprompter: BootstrapFewShot (small data, a few dozen examples), MIPROv2 (instructions and demos, auto="light"|"medium"|"heavy"), GEPA (reflective prompt evolution; its metric may return feedback text), BootstrapFinetune for weights.
  5. Persist: optimized.save("program.json") and later program.load("program.json") on a freshly constructed module.

Runtime constraints

dspy.Assert and dspy.Suggest were removed in 3.x. Use dspy.Refine(module=..., N=3, reward_fn=fn, threshold=1.0) (retry with feedback until the reward passes) or dspy.BestOfN (sample N, keep the best) instead; reward_fn(inputs_dict, prediction) returns a float.

Examples

Example 1: Sentiment classifier with typed output

User request: "Classify product reviews as positive, negative or neutral with a confidence score."

from typing import Literal
import dspy

dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))

class ReviewSentiment(dspy.Signature):
    """Classify the sentiment of a customer review."""
    review: str = dspy.InputField()
    sentiment: Literal["positive", "negative", "neutral"] = dspy.OutputField()
    confidence: float = dspy.OutputField(desc="0.0 to 1.0")

classify = dspy.ChainOfThought(ReviewSentiment)
out = classify(review="It works but the manual is confusing")
print(out.reasoning, out.sentiment, out.confidence)

Result: a Prediction whose sentiment is one of the three literals (for example neutral), confidence is a float, and reasoning holds the model's step-by-step text. Prompt formatting is handled by DSPy.

Example 2: Question answering over your docs, then optimize

User request: "Build a QA module over our docs and tune it on 30 labeled questions."

import dspy
from dspy.teleprompt import MIPROv2

dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
corpus = open("docs/faq.txt").read().split("\n\n")
search = dspy.retrievers.Embeddings(
    embedder=dspy.Embedder("openai/text-embedding-3-small"), corpus=corpus, k=3)

class DocsQA(dspy.Module):
    def __init__(self):
        super().__init__()
        self.answer = dspy.ChainOfThought("context, question -> answer")
    def forward(self, question):
        return self.answer(context=search(question).passages, question=question)

def metric(example, pred, trace=None):
    return example.answer.lower() in pred.answer.lower()

trainset = [dspy.Example(question=q, answer=a).with_inputs("question") for q, a in labeled[:20]]
devset = [dspy.Example(question=q, answer=a).with_inputs("question") for q, a in labeled[20:]]

evaluate = dspy.Evaluate(devset=devset, metric=metric, num_threads=8)
print("baseline", evaluate(DocsQA()).score)
tuned = MIPROv2(metric=metric, auto="light").compile(DocsQA(), trainset=trainset)
print("tuned", evaluate(tuned).score)
tuned.save("docs_qa.json")

Result: two scores (percent on the dev set) so you can see whether optimization helped, and a docs_qa.json holding the tuned instructions and demos.

Guidelines

  • Define the metric and a held-out dev set before optimizing; without them there is nothing to optimize against and no way to detect overfitting.
  • Optimizers make many LM calls. Start with auto="light", set num_threads carefully against rate limits, and expect a real API bill on large trainsets.
  • Never hard-code API keys; DSPy reads provider variables such as OPENAI_API_KEY, or pass api_key=os.environ[...] to dspy.LM.
  • Calls are cached on disk by default; pass cache=False to dspy.LM when benchmarking or sampling several times.
  • Loading a saved program needs the same module class definition; save the code in version control with the JSON.
  • Do not use DSPy for a single fixed prompt that already works; it pays off when you have a metric, data, and a pipeline of several LM steps.
  • Pin the dspy version in production: the API moved noticeably between 2.x and 3.x.

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Scripts and configures production rendering in Autodesk 3ds Max with the V-Ray and Corona renderers: output size and files, render elements, denoising, light mix, batch and command-line rendering, and network rendering. Use when a user asks to set up a production render, render several cameras in one batch, render from the command line or on a render farm, add render passes for compositing, or cut render time for archviz and product shots.

中文简介正在准备中。当前显示原文说明。

TerminalSkills/skills1722026年10月14日 更新

Covers scripting Autodesk 3ds Max, the 3D modeling and rendering application, with MAXScript and Python (pymxs): scene manipulation, object creation, material assignment, camera and light setup, batch operations, and file I/O. Use when tasks involve automating repetitive 3ds Max workflows, batch processing scenes, running scripts headless with 3dsmaxbatch, creating custom tools, or scripting scene setup for archviz, product visualization, or VFX.

中文简介正在准备中。当前显示原文说明。

TerminalSkills/skills1722026年10月14日 更新

3proxy

免费

3proxy is a small open-source proxy server that runs HTTP/HTTPS, SOCKS4/5, SNI and TCP/UDP port-mapping proxies from one config file. Use when a user asks to set up an HTTP or SOCKS5 proxy, add proxy users and passwords, write 3proxy access rules, chain or rotate upstream (parent) proxies, limit bandwidth, connections or monthly traffic per user, run 3proxy in Docker, or fix a 3proxy.cfg that will not start.

中文简介正在准备中。当前显示原文说明。

TerminalSkills/skills1722026年10月14日 更新

Builds Agent2Agent (A2A) servers and clients, the open protocol (originally from Google, now under the Linux Foundation) that lets AI agents from different frameworks call each other. Use when the user wants to create an A2A-compliant agent, build an Agent Card, implement task management, connect agents across frameworks, set up agent discovery, handle streaming responses, implement push notifications, or orchestrate multi-agent workflows. Trigger words: a2a, agent to agent, agent2agent, a2a protocol, a2a server, a2a client, agent card, agent interoperability, agent collaboration, multi-agent, agent discovery, a2a sdk, a2a task.

中文简介正在准备中。当前显示原文说明。

TerminalSkills/skills1722026年10月14日 更新

Plans a controlled experiment (A/B test) so its result can be trusted: writes the hypothesis, picks one primary metric and the guardrails, computes sample size and run time, specifies how visitors are assigned and when exposure is logged, and reads out the result with a confidence interval. Use when someone says "set up an A/B test", "split test this page", "how many visitors do I need", "how long should the experiment run", "is this result significant", "can I stop the test early", or wants to test a headline, price, layout or onboarding change against the current version.

中文简介正在准备中。当前显示原文说明。

TerminalSkills/skills1722026年10月14日 更新

ably

免费

Ably is a hosted realtime messaging service: clients publish and subscribe to named channels over WebSockets, see who is present, replay message history, and resume after a dropped connection. Use when a user asks to "add realtime updates", "push live notifications to the browser", "show who is online", "add a chat room with typing indicators", "publish from a serverless function", or "authenticate Ably clients without exposing the API key". Covers the ably 2.x JavaScript SDK (Realtime and REST), JWT token authentication, presence, history and rewind, batch publishing, and the @ably/chat 1.x SDK.

中文简介正在准备中。当前显示原文说明。

TerminalSkills/skills1722026年10月14日 更新

查看 TerminalSkills 的全部技能

报告此技能的问题