DSpyNet 1.0.0

dotnet add package DSpyNet --version 1.0.0
                    
NuGet\Install-Package DSpyNet -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DSpyNet" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DSpyNet" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="DSpyNet" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add DSpyNet --version 1.0.0
                    
#r "nuget: DSpyNet, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package DSpyNet@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=DSpyNet&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=DSpyNet&version=1.0.0
                    
Install as a Cake Tool

DSpyNet ๐Ÿง 

DSpyNet is a C# .NET port of the Stanford DSPy framework.

It allows you to program language models rather than prompt them. Instead of tweaking string prompts manually, you define Signatures (Input/Output contracts) and Modules, and let Optimizers (Teleprompters) automatically tune the prompts and select the best few-shot examples for your specific metrics.

Built on top of Microsoft Semantic Kernel.


๐Ÿš€ Features & Comparison

DSpyNet adapts the dynamic nature of Python's DSPy to the strongly-typed world of .NET.

Feature Original DSPy (Python) DSpyNet (C#) Status
Core Abstraction Declarative Pydantic Models C# Classes with Attributes ([DspInput]) โœ… Implemented
LLM Backend dspy.LM (Custom/LiteLLM) Microsoft.SemanticKernel (ILM Interface) โœ… Implemented
Basic Modules Predict, ChainOfThought Predict<T>, ChainOfThought<T> โœ… Implemented
Complex Modules ReAct, ProgramOfThought Not yet implemented โŒ Planned
Optimizers BootstrapFewShot BootstrapFewShot (Teacher/Student) โœ… Implemented
Advanced Optimizers MIPROv2 (Bayesian/Optuna) MIPRO (Random Search Strategy) โš ๏ธ Partial
Prompt Engineering COPRO, SignatureOptimizer Not yet implemented โŒ Planned
Metrics Python Functions C# Delegates Func<Example, Prediction, bool> โœ… Implemented
Tracing Global Context Manager AsyncLocal Execution State โœ… Implemented
Serialization Pickle / JSON JSON State Serialization โœ… Implemented

๐Ÿ“ฆ Installation

Currently, this is a source-only library. Include the DSpyNet project in your solution.

Dependencies:

  • .NET 8.0+
  • Microsoft.SemanticKernel
  • Microsoft.Extensions.Logging

โšก Quick Start

1. Define a Signature

Instead of writing a prompt text, define what you need using a C# class.

using DSpyNet.DSPy.Core;

[DspInstruction("Translate the text to the target language.")]
public class TranslationSignature : IDSpySignature
{
    [DspInput(Prefix = "Text to translate:")]
    public string InputText { get; set; }

    [DspInput(Prefix = "Target Language:")]
    public string Language { get; set; }

    [DspOutput(Prefix = "Translation:")]
    public string TranslatedText { get; set; }
}

2. Configure Semantic Kernel

DSpyNet wraps Semantic Kernel to communicate with LLMs.

var builder = Kernel.CreateBuilder();
builder.AddOpenAIChatCompletion("gpt-4o", "YOUR_API_KEY");
var kernel = builder.Build();

// Convert to DSpy ILM
var lm = kernel.ToDSpyLM();

3. Run a Module

Create a predictor based on your signature and run it.

var predictor = new Predict<TranslationSignature>(lm);

var result = await predictor.InvokeAsync(new 
{ 
    InputText = "Hello world", 
    Language = "Spanish" 
});

var prediction = (Prediction)result;
Console.WriteLine(prediction.Get<string>("TranslatedText")); 
// Output: Hola Mundo

๐Ÿง  Optimization (Teleprompters)

The power of DSPy is compiling your program to optimize it. The BootstrapFewShot optimizer runs a "Teacher" model over your training data, validates the outputs using your metric, and automatically saves the best examples to the prompt (Few-Shot Learning).

// 1. Define Training Data
var trainset = new List<Example>
{
    Example.From(("Question", "2+2?"), ("Answer", "4")),
    Example.From(("Question", "Capital of France?"), ("Answer", "Paris"))
};

// 2. Define a Metric (Correctness check)
Metric exactMatch = (gold, pred) => 
    gold.Get<string>("Answer") == pred.Get<string>("Answer");

// 3. Setup Modules
var student = new ChainOfThought<QASignature>(lm);

// 4. Compile (Optimize)
var optimizer = new BootstrapFewShot<ChainOfThought<QASignature>>(
    metric: exactMatch, 
    maxBootstrappedDemos: 4
);

// This returns a NEW module with optimized prompts and demos embedded
var compiledProgram = await optimizer.CompileAsync(student, trainset);

// 5. Run Optimized Program
var result = await compiledProgram.InvokeAsync(new { Question = "What is 5 + 5?" });

๐Ÿ— Architecture Details

Mutability in a Static Language

In Python, DSPy modifies classes on the fly. In C#, classes are static. DSpyNet solves this by separating Schema (Type) from State (Data).

  • Signature (Class): Defines the structure, types, and default instructions (Immutable).
  • SignatureState (Object): Holds the actual instruction text and the list of Few-Shot examples (Mutable).

Optimizers (like MIPRO or Bootstrap) clone the Module, modify the SignatureState (changing instructions or adding demos), and return a new instance of the module.

Serialization

You can save optimized modules to disk and load them in production:

// Save optimized state
await compiledProgram.SaveAsync("optimized_math_bot.json");

// Load later
var productionBot = new ChainOfThought<MathSignature>(lm);
await productionBot.LoadAsync("optimized_math_bot.json");

๐Ÿงช Integration Tests

The repository includes a RealExampleIntegrationTests project. It contains examples of:

  • News Generation: Generating social media posts from raw text.
  • Content Guard: Analyzing sentiment and safety using Chain of Thought.
  • Intent Classification: Optimizing a classification task using BootstrapFewShot.

To run them, you need to set up your API keys (e.g., OpenAI or RouterAI) in the test base class.


๐Ÿค Contributing

This is an active port. Missing features (ReAct, Code Execution, Advanced Bayesian Optimization) are planned. PRs are welcome!

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 81 1/16/2026
0.1.0-alpha 81 1/16/2026