LangChain .NET Documentation

repository·main·Indexed 21 days ago

https://github.com/tryagi/langchain

A C# implementation of the LangChain framework for building LLM-powered applications. It provides composable abstractions such as chains, vector databases, and document loaders to create RAG pipelines. The project includes a global .NET CLI tool for tasks like text summarization, content generation, and model management, supporting providers such as OpenAI, OpenRouter, and Anthropic.

Tokens
2.5K
Snippets
13
Records
15
Agent score
77%

What's inside LangChain .NET

  1. Use Smart Tasks and Model Switching

    main

    You can switch the active model for subsequent commands using the model command. This allows you to use more powerful models (like gpt-4-turbo) for complex tasks.

    Example workflow:

    1. Switch to a specific model: langchain model gpt-4-turbo
    2. Run a generation task: langchain generate --input "Give me a solution for the next problem: $PROBLEM"
    langchain model gpt-4-turbo
    langchain generate --input "Give me a solution for the next problem: $PROBLEM"
  2. Build a RAG pipeline using Chains

    main

    LangChain .NET supports a functional, composable syntax for building pipelines called Chains. Chains allow you to pipe operations together using the | operator, creating a declarative workflow.

    Common chain components include:

    • Set(value): Sets the initial input value.
    • RetrieveSimilarDocuments(collection, embeddingModel, amount): Fetches relevant documents from a vector collection.
    • CombineDocuments(outputKey): Merges retrieved documents into a single string assigned to a specific key.
    • Template(promptTemplate): Injects variables into a prompt string.
    • LLM(model): Sends the final prompt to the language model.

    To execute a chain, use await chain.RunAsync(inputKey).

    var promptTemplate = @"Use the following context: {context}\nQuestion: {text}\nAnswer:";
    
    var chain = 
        Set("Who was drinking a unicorn blood?")
        | RetrieveSimilarDocuments(vectorCollection, embeddingModel, amount: 5)
        | CombineDocuments(outputKey: "context")
        | Template(promptTemplate)
        | LLM(llm.UseConsoleForDebug());
    
    var chainAnswer = await chain.RunAsync("text");
  3. Get started with LangChain .NET

    main

    LangChain .NET is a C# implementation of LangChain designed for building applications with Large Language Models (LLMs) through composability. It aims to provide abstractions similar to the original LangChain while remaining open to new entities and third-party libraries.

    To get started, you can consult the official wiki or explore the provided examples and integration tests in the repository.

    • Official Wiki: https://tryagi.github.io/LangChain/
    • Examples: Check the ./examples directory in the repository.
    • Integration Tests: See src/tests/LangChain.IntegrationTests/ReadmeTests.cs for authoritative usage patterns.
  4. Build a RAG pipeline using Async methods

    main

    You can build a Retrieval-Augmented Generation (RAG) pipeline by manually orchestrating models, vector databases, and document loaders using asynchronous methods.

    This approach involves:

    1. Initializing an LLM and an Embedding model via a provider (e.g., OpenAiProvider).
    2. Creating a vector database (e.g., SqLiteVectorDatabase).
    3. Loading documents from a source (e.g., a PDF URL) using a loader (e.g., PdfPigPdfLoader) and storing them in a collection.
    4. Retrieving similar documents using GetSimilarDocuments.
    5. Passing the retrieved context to the LLM via GenerateAsync.
    // Initialize models
    var provider = new OpenAiProvider(
        Environment.GetEnvironmentVariable("OPENAI_API_KEY") ??
        throw new InconclusiveException("OPENAI_API_KEY is not set"));
    var llm = new OpenAiLatestFastChatModel(provider);
    var embeddingModel = new TextEmbeddingV3SmallModel(provider);
    
    // Create vector database from Harry Potter book pdf
    using var vectorDatabase = new SqLiteVectorDatabase(dataSource: "vectors.db");
    var vectorCollection = await vectorDatabase.AddDocumentsFromAsync<PdfPigPdfLoader>(
        embeddingModel, 
        dimensions: 1536, 
        dataSource: DataSource.FromUrl("https://example.com/book.pdf"),
        collectionName: "harrypotter",
        textSplitter: null);
    
    // Find similar documents
    const string question = "Who was drinking a unicorn blood?";
    var similarDocuments = await vectorCollection.GetSimilarDocuments(embeddingModel, question, amount: 5);
    
    // Use similar documents and LLM to answer
    var answer = await llm.GenerateAsync($"... {similarDocuments.AsString()} ... Question: {question}");
  5. Authenticate LangChain CLI with OpenAI

    main

    Before using the CLI, you must authenticate with an LLM provider. To use OpenAI, run the auth command and provide your OPENAI_API_KEY.

    By default, the CLI uses gpt-3.5-turbo. You can specify a different model using the --model parameter.

    langchain auth openai OPENAI_API_KEY
  6. Specify tools and toolsets in the CLI

    main

    When using the CLI, you can specify a tool either by its name or by including optional toolsets inside square brackets []. If multiple toolsets are provided, they should be comma-separated.

    Format:

    • Simple tool: ToolName
    • Tool with toolsets: ToolName[toolset1,toolset2]
    Filesystem[path1,path2]
    GitHub[repo_name]
    Fetch
  7. Common CLI options for LangChain .NET

    main

    The LangChain .NET CLI provides several common options that can be used across different commands to control input, output, debugging, and model configuration.

    Input Options

    • --input, -i: Specifies the input text. Defaults to an empty string.
    • --input-file: Specifies the path to an input file.

    Output Options

    • --output-file: Specifies the path where the output should be saved.

    Configuration and Debugging

    • --debug: A boolean flag to enable showing debug information. Defaults to false.
    • --model: Specifies the model to use for the command. Defaults to o3-mini.
    • --provider: Specifies the provider to use for the command.
    # Example usage of common flags
    langchain-cli <command> --input "Hello world" --model "gpt-4o" --provider "OpenAI" --debug
    
    # Example usage with files
    langchain-cli <command> --input-file ./data.txt --output-file ./result.txt
  8. Available LLM Providers

    main

    The LangChain CLI supports the following model providers for task execution:

    • OpenAi: OpenAI models.
    • OpenRouter: Models accessed via the OpenRouter aggregator.
    • Anthropic: Anthropic Claude models.
    • Free: Local or free-tier models that do not require a paid API key.
    OpenAi
    OpenRouter
    Anthropic
    Free
  9. Supported output formats for the LangChain CLI

    main

    The LangChain CLI supports several output formats for displaying or processing data. When configuring output via the CLI, you can choose from the following options:

    • Text: Standard text output.
    • Lines: Output separated by lines.
    • Json: Structured JSON format.
    • Markdown: Formatted Markdown output.
    • ConventionalCommit: Formatted according to Conventional Commits standards.
    Text,
    Lines,
    Json,
    Markdown,
    ConventionalCommit