### Full Setup Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Demonstrates a complete setup of LangChain services in a .NET application, including dependency injection, custom naming, and middleware configuration for models. ```csharp var builder = WebApplication.CreateBuilder(args); // Add LangChain services builder.Services.AddLangChainServe(); // Add database context if using persistence builder.Services.AddSingleton(); // Add custom conversation naming builder.Services.AddCustomNameGenerator(async (messages) => { // Custom naming logic return "Custom Name"; }); // Add other services builder.Services.AddHttpClient(); builder.Services.AddLogging(); var app = builder.Build(); // Configure middleware app.UseLangChainServe(options => { // Setup models from configuration var openAiKey = builder.Configuration["OpenAI:ApiKey"]; var anthropicKey = builder.Configuration["Anthropic:ApiKey"]; var openAiClient = new OpenAIClient(openAiKey).GetChatClient("gpt-4o-mini"); var anthropicClient = new AnthropicClient(anthropicKey).GetChatClient("claude-3-sonnet"); options.AddModel("openai", openAiClient.AsIChatClient()); options.AddModel("anthropic", anthropicClient.AsIChatClient()); options.DefaultModel = "openai"; }); app.MapHealthChecks("/health"); app.Run(); ``` -------------------------------- ### ServeExtensions Setup Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Example of setting up LangChainServe with custom name generator and models. ```csharp // Program.cs var builder = WebApplication.CreateBuilder(args); // Register services builder.Services.AddLangChainServe(); builder.Services.AddCustomNameGenerator(async (messages) => { if (messages.Count == 0) return "Empty"; var first = messages.First().Content; return first.Length > 50 ? first.Substring(0, 50) + "..." : first; }); var app = builder.Build(); // Configure middleware app.UseLangChainServe(options => { options.AddModel("gpt-4o-mini", gpt4MiniClient); options.AddModel("gpt-4o", gpt4Client); options.AddModel("claude-3-sonnet", claudeClient); options.DefaultModel = "gpt-4o-mini"; }); app.Run(); ``` -------------------------------- ### ReActAgentExecutor Setup Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Example of creating a ReAct agent executor with caching and tools. ```csharp var agent = Chain.ReActAgentExecutor( chatClient, reActPrompt: customPrompt, // null = use default maxActions: 10, inputKey: "task", outputKey: "result") .UseCache(enabled: true) .UseTool("name", "description", implementation); ``` -------------------------------- ### LLMChain Options Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Example with multiple LLM chain options. ```csharp var chain = Chain.LLM(chatClient, options: new ChatOptions { Temperature = 0.3, MaxOutputTokens = 1000, StopSequences = new[] { "\n\n", "[END]" } }); ``` -------------------------------- ### UseCache Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/agents.md Example demonstrating how to enable response caching for an agent. ```csharp var agent = Chain.ReActAgentExecutor(chatClient) .UseCache(true) .UseTool("calculator", "Calculate", async (input, ct) => /* ... */); ``` -------------------------------- ### Loading Memory in Chains Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/memory.md Example demonstrating how to load memory into a chain. ```csharp var memory = new ConversationBufferMemory(); var chain = Chain.LoadMemory(memory, outputKey: "history") | Chain.Template("History:\n{history}\n\nNew input: {text}") | Chain.LLM(chatClient); ``` -------------------------------- ### UseTool Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/agents.md Example demonstrating how to use the UseTool method to register calculator and search tools for an agent. ```csharp var agent = Chain.ReActAgentExecutor(chatClient) .UseTool("calculator", "Performs arithmetic operations", async (input, ct) => { // Parse input and calculate return result.ToString(); }) .UseTool("search", "Searches the web", async (input, ct) => { // Perform search return results; }); var answer = await agent.RunAsync("What is 10 + 5? Also search for AI"); ``` -------------------------------- ### Few-Shot Prompting Source: https://github.com/tryagi/langchain/blob/main/_autodocs/common-patterns.md An example of few-shot prompting where examples are included in the prompt to guide the model's response for sentiment classification. ```csharp var fewShotPrompt = @"Classify the sentiment of these reviews. Examples: Review: 'Excellent product!' → Positive Review: 'Terrible quality.' → Negative Review: 'It's okay, nothing special.' → Neutral Now classify: Review: {review} Sentiment:"; var chain = Chain.Set("The service was amazing and fast!", "review") | Chain.Template(fewShotPrompt) | Chain.LLM(chatClient); var sentiment = await chain.RunAsync("text"); ``` -------------------------------- ### Chain Execution Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/chain-factories.md Examples of executing chains with RunAsync. ```csharp // Get result as string var result = await chain.RunAsync("outputKey"); // Get typed result var result = await chain.RunAsync("outputKey"); // Get all context values var values = await chain.RunAsync(); ``` -------------------------------- ### Complete Server Setup Source: https://github.com/tryagi/langchain/blob/main/_autodocs/common-patterns.md Set up a LangChain serving endpoint with multiple models. ```csharp var builder = WebApplication.CreateBuilder(args); // Configure logging builder.Services.AddLogging(logging => { logging.AddConsole(); logging.SetMinimumLevel(LogLevel.Information); }); // Add LangChain serving builder.Services.AddLangChainServe(); var app = builder.Build(); // Setup models var openAiKey = builder.Configuration["OpenAI:ApiKey"] ?? Environment.GetEnvironmentVariable("OPENAI_API_KEY"); var anthropicKey = builder.Configuration["Anthropic:ApiKey"] ?? Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY"); var openAiClient = new OpenAIClient(openAiKey); var anthropicClient = new AnthropicClient(anthropicKey); app.UseLangChainServe(options => { options.AddModel("gpt-4o-mini", openAiClient.GetChatClient("gpt-4o-mini").AsIChatClient()); options.AddModel("gpt-4o", openAiClient.GetChatClient("gpt-4o").AsIChatClient()); options.AddModel("claude-3-sonnet", anthropicClient.GetChatClient("claude-3-sonnet").AsIChatClient()); options.DefaultModel = "gpt-4o-mini"; }); app.MapHealthChecks("/health"); app.Run(); ``` -------------------------------- ### Updating Memory After Response Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/memory.md Example demonstrating how to update memory after a chain has run. ```csharp var memory = new ConversationBufferMemory(); var chain = Chain.Set("What is AI?") | Chain.LLM(chatClient) | Chain.UpdateMemory(memory, requestKey: "text", responseKey: "text"); await chain.RunAsync(); ``` -------------------------------- ### AddDocumentsFromAsync Options Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Example of adding documents from a URL with specified options. ```csharp var collection = await vectorStore.AddDocumentsFromAsync( embeddingGenerator, dimensions: 1536, dataSource: DataSource.FromUrl("https://example.com/doc.pdf"), collectionName: "documents", textSplitter: new RecursiveCharacterTextSplitter(chunkSize: 2000), loaderSettings: new PdfLoaderSettings(), behavior: AddDocumentsToDatabaseBehavior.JustReturnCollectionIfCollectionIsAlreadyExists); ``` -------------------------------- ### Example of sending input to an LLM Source: https://github.com/tryagi/langchain/blob/main/_autodocs/chain-factories.md Example of sending input to a language model and retrieving its response. ```csharp var chain = Chain.Set("Why is the sky blue?") | Chain.LLM(chatClient, inputKey: "text", options: new ChatOptions { Temperature = 0.7 }); var answer = await chain.RunAsync("text"); ``` -------------------------------- ### Setup Source: https://github.com/tryagi/langchain/blob/main/_autodocs/endpoints.md Register and configure the serve middleware in your ASP.NET Core application. ```csharp // Program.cs var builder = WebApplication.CreateBuilder(args); builder.Services.AddLangChainServe(); var app = builder.Build(); app.UseLangChainServe(options => { options.AddModel("gpt-4", chatClient); options.AddModel("claude-3-sonnet", claudeClient); }); app.Run(); ``` -------------------------------- ### Batch Processing Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Demonstrates batch processing of documents, including loading, embedding, and adding them to a vector store collection. ```csharp // Process multiple documents at once var documents = await loader.LoadAsync(source); var collection = vectorStore.GetCollection("docs"); await collection.AddDocumentsAsync(embeddingGenerator, documents); // Batch add ``` -------------------------------- ### ConversationWindowBufferMemory Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/memory.md Example of initializing ConversationWindowBufferMemory with a specific K value. ```csharp var memory = new ConversationWindowBufferMemory { K = 10 }; // Only keeps the last 10 messages ``` -------------------------------- ### ConversationBufferMemory Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/memory.md Example demonstrating the usage of ConversationBufferMemory with a chain. ```csharp var memory = new ConversationBufferMemory { MemoryKey = "chat_history" }; var chain = Chain.LoadMemory(memory, outputKey: "history") | Chain.Template("Previous: {history}\n\nNew: {text}") | Chain.LLM(chatClient); ``` -------------------------------- ### MessageFormatter Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/memory.md Example of creating a MessageFormatter with custom prefixes and formatting messages. ```csharp var formatter = new MessageFormatter { HumanPrefix = "User", AiPrefix = "Assistant" }; var formatted = formatter.Format(chatHistory.Messages); // Output: "User: Hello\nAssistant: Hi there!" ``` -------------------------------- ### CrewAgent Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/agents.md Provides an example of how to instantiate and use CrewAgent objects to form a crew and run a task. ```csharp var researcher = new CrewAgent { Name = "Researcher", Role = "Data Analyst", Goal = "Find relevant information", ChatClient = chatClient }; var writer = new CrewAgent { Name = "Writer", Role = "Content Writer", Goal = "Write compelling content", ChatClient = chatClient }; var manager = new CrewAgent { Name = "Manager", Role = "Project Manager", Goal = "Coordinate team and deliver results", ChatClient = chatClient }; var crew = Chain.Crew(new[] { researcher, writer }, manager); var result = await crew.RunAsync("Create a blog post about AI"); ``` -------------------------------- ### Example of executing a custom action Source: https://github.com/tryagi/langchain/blob/main/_autodocs/chain-factories.md Example of executing a custom action with access to the chain context. ```csharp var chain = Chain.Set("test") | Chain.Do(ctx => Console.WriteLine(ctx["text"])); ``` -------------------------------- ### Example Usage of AddDocumentsFromAsync Source: https://github.com/tryagi/langchain/blob/main/_autodocs/vector-stores.md Example demonstrating how to use the AddDocumentsFromAsync method to load documents from a PDF and query the vector store. ```csharp var vectorStore = new InMemoryVectorStore(); var embeddingGenerator = openAiClient.GetEmbeddingClient("text-embedding-3-small") .AsIEmbeddingGenerator(); var collection = await vectorStore.AddDocumentsFromAsync( embeddingGenerator, dimensions: 1536, dataSource: DataSource.FromUrl("https://example.com/doc.pdf"), collectionName: "documents", textSplitter: new RecursiveCharacterTextSplitter(chunkSize: 2000, chunkOverlap: 200)); var results = await collection.GetSimilarDocuments( embeddingGenerator, "What is machine learning?", amount: 5); ``` -------------------------------- ### GroupChat Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/agents.md Demonstrates how to set up and run a GroupChat with multiple agents, including configuration for stop phrases and message limits. ```csharp var agent1 = Chain.ReActAgentExecutor(chatClient1); var agent2 = Chain.ReActAgentExecutor(chatClient2); var groupChat = Chain.GroupChat( new[] { agent1, agent2 }, stopPhrase: "DONE", messagesLimit: 20); var result = await groupChat.RunAsync("Debate the benefits of AI"); ``` -------------------------------- ### Memory Integration Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/README.md Shows the pattern for loading memory before chain operations and updating it afterward. ```csharp Chain.LoadMemory(memory) | /* ... chain operations ... */ | Chain.UpdateMemory(memory) ``` -------------------------------- ### Chain Composition Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/chain-factories.md Example of composing chains using the pipe operator. ```csharp var chain = Chain.Set("What is machine learning?") | Chain.LLM(chatClient) | Chain.TTS(ttsModel); var result = await chain.RunAsync("audio"); ``` -------------------------------- ### MEAI Provider Pattern Example Source: https://github.com/tryagi/langchain/blob/main/CLAUDE.md Shows how to use tryAGI SDKs directly with MEAI interfaces for chat and embedding. ```csharp var openAiClient = new OpenAIClient(apiKey); IChatClient chatClient = openAiClient.GetChatClient("gpt-4o-mini").AsIChatClient(); IEmbeddingGenerator> embeddingGenerator = openAiClient.GetEmbeddingClient("text-embedding-3-small").AsIEmbeddingGenerator(); ``` -------------------------------- ### CSharpSplitter Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/text-splitters.md Example of creating and using a CSharpSplitter with custom chunk size and overlap. ```csharp var splitter = new CSharpSplitter(chunkSize: 5000, chunkOverlap: 100); var chunks = splitter.SplitText(csharpSourceCode); ``` -------------------------------- ### Example of template substitution Source: https://github.com/tryagi/langchain/blob/main/_autodocs/chain-factories.md Example of performing variable substitution in a template string. ```csharp var chain = Chain.Set("Paris") | Chain.Template("The capital of France is {text}") | Chain.LLM(chatClient); ``` -------------------------------- ### MarkdownHeaderTextSplitter Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/text-splitters.md Example of creating and using a MarkdownHeaderTextSplitter with custom header splits and chunk size. ```csharp var splitter = new MarkdownHeaderTextSplitter( headersSplits: new[] { ("#", "Header 1"), ("##", "Header 2"), ("###", "Header 3") }, chunkSize: 2000); var chunks = splitter.SplitText(markdownText); ``` -------------------------------- ### ReAct Agent Source: https://github.com/tryagi/langchain/blob/main/_autodocs/README.md Example of setting up a ReAct agent with custom tools for calculator and search. ```csharp var agent = Chain.ReActAgentExecutor(chatClient) .UseTool("calculator", "Performs math", async (input, ct) => { // Parse and calculate return result.ToString(); }) .UseTool("search", "Searches the web", async (input, ct) => { // Search and return return results; }); var answer = await agent.RunAsync("What is 2+2? Also search for AI news"); ``` -------------------------------- ### Custom ReAct Prompt Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/agents.md Illustrates how to customize the prompt for a ReAct agent executor and how to use the UseTool method to add tools. ```csharp var customPrompt = @"You are an expert problem solver. Use these tools: {tools} Think step by step. Format your response as: Thought: What you're thinking Action: {tool_names} Action Input: The input Observation: The result Question: {input} {history}"; var agent = Chain.ReActAgentExecutor(chatClient, customPrompt, maxActions: 10) .UseTool("calculator", "Arithmetic", async (input, ct) => /* ... */) .UseTool("web_search", "Search web", async (input, ct) => /* ... */); var answer = await agent.RunAsync("What is 2^10 and what do we call that in computer science?"); ``` -------------------------------- ### Usage Tracking Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/types.md Example demonstrating how to instantiate a model and track its usage statistics after generating a response. ```csharp var llm = new OpenAiLatestFastChatModel(provider); var response = await llm.GenerateAsync("prompt"); Console.WriteLine($"Usage: {llm.Usage.TotalTokens} tokens, ${llm.Usage.Cost}"); ``` -------------------------------- ### Example of setting a constant value Source: https://github.com/tryagi/langchain/blob/main/_autodocs/chain-factories.md Example of setting a constant value into the chain context and then passing it to an LLM. ```csharp var chain = Chain.Set("What is LangChain?") | Chain.LLM(chatClient); ``` -------------------------------- ### Vector Stores (RAG) Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/README.md Example of creating embeddings from documents and performing a semantic search. ```csharp // Create embeddings var collection = await vectorStore.AddDocumentsFromAsync(...); // Search var results = await collection.GetSimilarDocuments(embeddingGenerator, query); ``` -------------------------------- ### Agents Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/README.md Basic structure for creating a ReAct agent executor and defining tools. ```csharp Chain.ReActAgentExecutor(chatClient) .UseTool("name", "description", implementation) .RunAsync(task) ``` -------------------------------- ### ServeOptions Configuration Source: https://github.com/tryagi/langchain/blob/main/_autodocs/endpoints.md Example of configuring LangChain Serve options, including adding models and setting a default model. ```csharp app.UseLangChainServe(options => { // Add models options.AddModel("gpt-4", gpt4ChatClient); options.AddModel("claude-3-sonnet", claudeChatClient); options.AddModel("llama-2", ollamaChatClient); // Default model (optional) options.DefaultModel = "gpt-4"; }); ``` -------------------------------- ### Azure OpenAI Provider Configuration Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Example of configuring and using the Azure OpenAI client. ```csharp var client = new OpenAIClient( new Uri(endpoint), new Azure.AzureKeyCredential(apiKey)); var chatClient = client.GetChatClient("deployment-name").AsIChatClient(); ``` -------------------------------- ### Multi-turn Conversation Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/endpoints.md Demonstrates how to create a conversation, send multiple messages, and retrieve the message history using C#. ```csharp using var httpClient = new HttpClient(); // Create conversation var createResponse = await httpClient.PostAsync( "http://localhost:5000/serve/conversations", new StringContent(JsonSerializer.Serialize(new { modelName = "gpt-4" }))); var conversation = JsonSerializer.Deserialize( await createResponse.Content.ReadAsStringAsync()); // Send message 1 await httpClient.PostAsync( $"http://localhost:5000/serve/conversations/{conversation.Id}/messages", new StringContent(JsonSerializer.Serialize(new { message = "What is AI?" }))); // Send message 2 (context is preserved) await httpClient.PostAsync( $"http://localhost:5000/serve/conversations/{conversation.Id}/messages", new StringContent(JsonSerializer.Serialize(new { message = "Tell me more about machine learning" }))); // Get all messages var messagesResponse = await httpClient.GetAsync( $"http://localhost:5000/serve/conversations/{conversation.Id}/messages"); var messages = JsonSerializer.Deserialize>( await messagesResponse.Content.ReadAsStringAsync()); foreach (var msg in messages) { Console.WriteLine($"{msg.Role}: {msg.Content}"); } ``` -------------------------------- ### SaveContext Method Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/memory.md Example demonstrating how to use the SaveContext method in BaseChatMemory to save a conversation turn. ```csharp var memory = new ConversationBufferMemory { InputKey = "question", OutputKey = "answer" }; var inputs = new InputValues(new Dictionary { { "question", "Hello" } }); var outputs = new OutputValues(new Dictionary { { "answer", "Hi there!" } }); await memory.SaveContext(inputs, outputs); ``` -------------------------------- ### POST /serve/conversations/{conversationId}/messages Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/endpoints.md Example cURL command to send a message to a conversation. ```bash curl -X POST http://localhost:5000/serve/conversations/550e8400-e29b-41d4-a716-446655440000/messages \ -H "Content-Type: application/json" \ -d '{ "message": "Explain quantum computing", "options": {"temperature": 0.5} }' ``` -------------------------------- ### OpenSearchVectorStore Source: https://github.com/tryagi/langchain/blob/main/_autodocs/vector-stores.md Example of initializing the OpenSearchVectorStore for OpenSearch-compatible vector storage. ```csharp var vectorStore = new OpenSearchVectorStore(openSearchConnection); ``` -------------------------------- ### InMemoryVectorStore Source: https://github.com/tryagi/langchain/blob/main/_autodocs/vector-stores.md Example of initializing the InMemoryVectorStore for testing and development purposes. ```csharp var vectorStore = new InMemoryVectorStore(); ``` -------------------------------- ### Working with ChainValues Source: https://github.com/tryagi/langchain/blob/main/_autodocs/types.md Example demonstrating how to initialize a chain, create ChainValues, and call the chain. ```csharp var chain = Chain.Set("hello") | Chain.LLM(chatClient); var values = new ChainValues(); var result = await chain.CallAsync(values); var response = result.Value["text"]; ``` -------------------------------- ### Chain Composition Example Source: https://github.com/tryagi/langchain/blob/main/CLAUDE.md Demonstrates how to compose LLM workflows using a chain of operations. ```csharp var chain = Set("question text") | RetrieveSimilarDocuments(vectorCollection, embeddingGenerator, amount: 5) | CombineDocuments(outputKey: "context") | Template(promptTemplate) | LLM(chatClient); var result = await chain.RunAsync("text"); ``` -------------------------------- ### Chain Composition Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/README.md Illustrates composing chains using the pipe operator `|`. ```csharp Chain.Set(value) | Chain.Template(template) | Chain.LLM(chatClient) ``` -------------------------------- ### Token Management for Performance Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Example of setting a maximum number of output tokens for an LLM chain to manage response size. ```csharp var chain = Chain.LLM(chatClient, options: new ChatOptions { MaxOutputTokens = 500 // Limit response size }); ``` -------------------------------- ### Logging Configuration Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Example of configuring detailed logging for the application, including console and debug output, and setting the minimum log level. ```csharp // Detailed logging builder.Services.AddLogging(logging => { logging.AddConsole(); logging.AddDebug(); logging.SetMinimumLevel(LogLevel.Debug); }); // In application code var logger = serviceProvider.GetRequiredService>(); logger.LogInformation("Chain execution started"); ``` -------------------------------- ### Timeout Configuration Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Example of setting up a CancellationTokenSource to enforce a timeout for chain execution. ```csharp var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var result = await chain.RunAsync( "input", cancellationToken: cts.Token); ``` -------------------------------- ### OpenAI Provider Configuration Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Example of configuring and using the OpenAI client for chat and embedding generation. ```csharp var client = new OpenAIClient(apiKey); var chatClient = client.GetChatClient("gpt-4o-mini").AsIChatClient(); var embeddingClient = client.GetEmbeddingClient("text-embedding-3-small").AsIEmbeddingGenerator(); ``` -------------------------------- ### Role-Based Prompting Source: https://github.com/tryagi/langchain/blob/main/_autodocs/common-patterns.md Assign a role to the LLM to guide its responses. ```csharp var rolePrompt = @"You are an expert software architect with 20 years of experience. A developer asks: {question} Provide your expert opinion:"; var chain = Chain.Set("Should we use microservices or monolithic architecture?") | Chain.Template(rolePrompt) | Chain.LLM(chatClient); ``` -------------------------------- ### SQLiteVecVectorStore Source: https://github.com/tryagi/langchain/blob/main/_autodocs/vector-stores.md Example of initializing the SQLiteVecVectorStore for persistent storage. ```csharp var vectorStore = new SqliteVecVectorStore("vectors.db"); ``` -------------------------------- ### Markdown Document Splitting Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/text-splitters.md Example of splitting markdown content using MarkdownHeaderTextSplitter with custom header splits and chunking parameters. ```csharp var markdownSplitter = new MarkdownHeaderTextSplitter( headersSplits: new[] { ("#", "Chapter"), ("##", "Section"), ("###", "Subsection") }, chunkSize: 3000, chunkOverlap: 300); var chunks = markdownSplitter.SplitText(markdownContent); ``` -------------------------------- ### Anthropic Provider Configuration Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Example of configuring and using the Anthropic client for chat. ```csharp var client = new AnthropicClient(apiKey); var chatClient = client.GetChatClient("claude-3-sonnet").AsIChatClient(); ``` -------------------------------- ### RAG Pattern Example - Option 2 (Manual) Source: https://github.com/tryagi/langchain/blob/main/CLAUDE.md Illustrates the RAG pattern by manually creating a vector store, adding documents, and then searching. ```csharp // Option 2: Manual — create collection, add documents, then search var store = new InMemoryVectorStore(); var collection = store.GetCollection("my-collection"); await collection.EnsureCollectionExistsAsync(); await collection.AddDocumentsAsync(embeddingGenerator, documents); var results = await collection.GetSimilarDocuments(embeddingGenerator, question, amount: 5); ``` -------------------------------- ### Basic Text Splitting Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/text-splitters.md Example of basic text splitting using CharacterTextSplitter with custom separator, chunk size, and chunk overlap. ```csharp var splitter = new CharacterTextSplitter( separator: "\n\n", chunkSize: 1000, chunkOverlap: 100); var chunks = splitter.SplitText(largeDocument); foreach (var chunk in chunks) { Console.WriteLine($"Chunk: {chunk.Substring(0, 50)}..."); } ``` -------------------------------- ### Basic LLM Chain Source: https://github.com/tryagi/langchain/blob/main/_autodocs/README.md A basic example of creating and running an LLM chain in C#. ```csharp var chatClient = openAiClient.GetChatClient("gpt-4o-mini").AsIChatClient(); var chain = Chain.Set("What is machine learning?") | Chain.LLM(chatClient); var answer = await chain.RunAsync("text"); Console.WriteLine(answer); ``` -------------------------------- ### Ollama (Local) Provider Configuration Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Example of configuring and using the Ollama client for local model interaction. ```csharp var client = new OllamaClient(new Uri("http://localhost:11434")); var chatClient = client.GetChatClient("llama2").AsIChatClient(); ``` -------------------------------- ### Multi-stage Reasoning Agent Source: https://github.com/tryagi/langchain/blob/main/_autodocs/agents.md Example of an agent using multiple tools for a multi-stage reasoning process. ```csharp var agent = Chain.ReActAgentExecutor(chatClient, maxActions: 15) .UseTool("research", "Gather information", async (input, ct) => { // Simulate research return $"Research results for '{input}'"; }) .UseTool("analyze", "Analyze data", async (input, ct) => { // Simulate analysis return $"Analysis of {input}"; }) .UseTool("synthesize", "Combine findings", async (input, ct) => { // Simulate synthesis return $"Synthesis: {input}"; }); var insight = await agent.RunAsync("Analyze market trends in tech"); ``` -------------------------------- ### Creating Custom Document Loader Source: https://github.com/tryagi/langchain/blob/main/_autodocs/document-loaders.md An example of how to create a custom document loader by implementing the IDocumentLoader interface. ```csharp public class CustomLoader : IDocumentLoader { public async Task> LoadAsync( DataSource dataSource, DocumentLoaderSettings? settings = null, CancellationToken cancellationToken = default) { var stream = await dataSource.GetStreamAsync(cancellationToken); // Parse stream and return documents return new List { new Document("parsed content", new Dictionary { { "source", dataSource.Value } }) }; } } ``` -------------------------------- ### ConversationSummaryBufferMemory Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/memory.md Example of initializing ConversationSummaryBufferMemory with a ChatClient and MaxTokenLimit. ```csharp var memory = new ConversationSummaryBufferMemory { ChatClient = chatClient, MaxTokenLimit = 1000 }; ``` -------------------------------- ### Basic Document Loading Source: https://github.com/tryagi/langchain/blob/main/_autodocs/document-loaders.md A basic example demonstrating how to load a document and access its content and metadata. ```csharp var loader = new PdfPigPdfLoader(); var documents = await loader.LoadAsync( DataSource.FromPath("/path/to/file.pdf")); foreach (var doc in documents) { Console.WriteLine(doc.PageContent); Console.WriteLine($"Source: {doc.Metadata["source"]}"); } ``` -------------------------------- ### RecursiveCharacterTextSplitter Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/text-splitters.md Example of using RecursiveCharacterTextSplitter with custom separators. ```csharp var splitter = new RecursiveCharacterTextSplitter( separators: new[] { "\n\n", "\n", ".", " " }, chunkSize: 2000, chunkOverlap: 100); var chunks = splitter.SplitText(document); ``` -------------------------------- ### ConversationSummaryMemory Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/memory.md Example of initializing ConversationSummaryMemory with a ChatClient and MemoryKey. ```csharp var memory = new ConversationSummaryMemory { ChatClient = chatClient, MemoryKey = "summary" }; ``` -------------------------------- ### HTTP API Setup Source: https://github.com/tryagi/langchain/blob/main/_autodocs/README.md Code for setting up the LangChain Serve HTTP API middleware in a .NET application. ```csharp // Setup var builder = WebApplication.CreateBuilder(args); builder.Services.AddLangChainServe(); var app = builder.Build(); app.UseLangChainServe(options => { options.AddModel("gpt-4", chatClient); options.AddModel("claude-3", claudeClient); }); app.Run(); ``` -------------------------------- ### Loading into Vector Store Source: https://github.com/tryagi/langchain/blob/main/_autodocs/document-loaders.md Example of loading documents directly into a vector store using a specific loader. ```csharp var vectorStore = new InMemoryVectorStore(); var embeddingGenerator = openAiClient.GetEmbeddingClient("text-embedding-3-small") .AsIEmbeddingGenerator(); var collection = await vectorStore.AddDocumentsFromAsync( embeddingGenerator, dimensions: 1536, dataSource: DataSource.FromUrl("https://example.com/document.pdf")); ``` -------------------------------- ### CharacterTextSplitter Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/text-splitters.md Example of using CharacterTextSplitter to split on double newlines. ```csharp // Split on double newlines var splitter = new CharacterTextSplitter( separator: "\n\n", chunkSize: 1000, chunkOverlap: 100); var chunks = splitter.SplitText(largeText); ``` -------------------------------- ### ReAct Agent Tools Source: https://github.com/tryagi/langchain/blob/main/_autodocs/types.md Example demonstrating how to define and use tools for a ReAct agent, including arithmetic operations. ```csharp var agent = Chain.ReActAgentExecutor(chatClient); agent.UseTool("add", "Adds two numbers", async (input, ct) => { var parts = input.Split(","); var result = int.Parse(parts[0]) + int.Parse(parts[1]); return result.ToString(); }); agent.UseTool("multiply", "Multiplies two numbers", async (input, ct) => { var parts = input.Split(","); var result = int.Parse(parts[0]) * int.Parse(parts[1]); return result.ToString(); }); var answer = await agent.RunAsync("What is 5 + 3 * 2?"); ``` -------------------------------- ### Querying Existing Collection Source: https://github.com/tryagi/langchain/blob/main/_autodocs/vector-stores.md Example of how to query an existing vector store collection for similar documents based on a search query. ```csharp var collection = vectorStore.GetCollection("documents"); var docs = await collection.GetSimilarDocuments( embeddingGenerator, "search query", amount: 10); ``` -------------------------------- ### RAG with Vector Store Source: https://github.com/tryagi/langchain/blob/main/_autodocs/README.md An example demonstrating Retrieval-Augmented Generation (RAG) using an in-memory vector store and a PDF loader. ```csharp var vectorStore = new InMemoryVectorStore(); var embeddingGenerator = openAiClient.GetEmbeddingClient("text-embedding-3-small") .AsIEmbeddingGenerator(); var collection = await vectorStore.AddDocumentsFromAsync( embeddingGenerator, dimensions: 1536, dataSource: DataSource.FromUrl("https://example.com/doc.pdf")); var chain = Chain.Set("What is AI?") | Chain.RetrieveSimilarDocuments(collection, embeddingGenerator, amount: 5) | Chain.CombineDocuments(outputKey: "context") | Chain.Template("Context:\n{context}\n\nQuestion: {text}") | Chain.LLM(chatClient); var answer = await chain.RunAsync("text"); ``` -------------------------------- ### Structured Tool Calling Source: https://github.com/tryagi/langchain/blob/main/_autodocs/common-patterns.md Demonstrates creating an agent with multiple tools, including a calculator, weather lookup, and web search. ```csharp var agent = Chain.ReActAgentExecutor(chatClient, maxActions: 10) .UseTool( "calculator", "Performs mathematical calculations", async (input, ct) => { // Parse expression and calculate var result = new DataTable().Compute(input, null); return result.ToString(); }) .UseTool( "weather", "Gets current weather for a city", async (input, ct) => { var weather = await GetWeatherAsync(input); return $"{input}: {weather.Temperature}°C, {weather.Condition}"; }) .UseTool( "web_search", "Searches the internet", async (query, ct) => { var results = await SearchWebAsync(query); return string.Join("\n", results.Take(3)); }); var answer = await agent.RunAsync("What's the weather in Paris and the capital of France?"); ``` -------------------------------- ### Error Response Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/endpoints.md Example of a JSON error response structure. ```json { "error": "Model not found", "code": "MODEL_NOT_FOUND", "timestamp": "2024-05-27T10:30:00Z" } ``` -------------------------------- ### Configuration Management Source: https://github.com/tryagi/langchain/blob/main/_autodocs/common-patterns.md Illustrates how to define and manage application settings, including API keys and operational parameters, using C# classes and dependency injection. ```csharp public class AppSettings { public string OpenAiApiKey { get; set; } public string AnthropicApiKey { get; set; } public int MaxAgentActions { get; set; } = 5; public int ChunkSize { get; set; } = 2000; public int ChunkOverlap { get; set; } = 200; } // Usage in DI builder.Services.Configure( builder.Configuration.GetSection("LangChain")); ``` -------------------------------- ### SplitDocuments Extension Method Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/text-splitters.md Example of using the SplitDocuments extension method with a CharacterTextSplitter. ```csharp var splitter = new CharacterTextSplitter(chunkSize: 1000); var documents = await loader.LoadAsync(source); var splitDocs = splitter.SplitDocuments(documents); ``` -------------------------------- ### Monitoring and Logging Source: https://github.com/tryagi/langchain/blob/main/_autodocs/common-patterns.md Demonstrates how to integrate logging into chain execution to track progress, record successes, and capture errors for debugging and monitoring purposes. ```csharp private readonly ILogger _logger; public async Task ExecuteChain(string input) { _logger.LogInformation("Starting chain execution with input: {Input}", input); try { var result = await chain.RunAsync("text"); _logger.LogInformation("Chain completed successfully"); return result; } catch (Exception ex) { _logger.LogError(ex, "Chain execution failed"); throw; } } ``` -------------------------------- ### Context Flow Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/README.md Demonstrates how data flows through chains using a Dictionary context and specifying input/output keys. ```csharp Chain.Set("query", outputKey: "question") // Sets context["question"] = "query" | Chain.LLM(chatClient, inputKey: "question", outputKey: "answer") // Reads from context["question"], writes to context["answer"] ``` -------------------------------- ### Using with Chains Source: https://github.com/tryagi/langchain/blob/main/_autodocs/vector-stores.md Illustrates how to use vector store retrieval within LangChain.NET chains for a more structured RAG process. ```csharp var chain = Chain.Set("What is RAG?") | Chain.RetrieveSimilarDocuments(collection, embeddingGenerator, amount: 5) | Chain.CombineDocuments(outputKey: "context") | Chain.Template("Context:\n{context}\n\nQuestion: {text}") | Chain.LLM(chatClient); var answer = await chain.RunAsync("text"); ``` -------------------------------- ### DELETE /serve/conversations/{conversationId} Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/endpoints.md Example cURL command to delete a conversation. ```bash curl -X DELETE http://localhost:5000/serve/conversations/550e8400-e29b-41d4-a716-446655440000 ``` -------------------------------- ### ServeOptions Class Source: https://github.com/tryagi/langchain/blob/main/_autodocs/configuration.md Configuration options for LangChainServe. ```csharp public class ServeOptions { public void AddModel(string modelName, IChatClient chatClient) public string? DefaultModel { get; set; } public IReadOnlyDictionary Models { get; } } ``` -------------------------------- ### Build and Test Commands Source: https://github.com/tryagi/langchain/blob/main/AGENTS.md Commands for building the solution, running integration and unit tests, and validating trimming/NativeAOT compatibility. ```bash # Build the entire solution dotnet build LangChain.slnx # Run all integration tests dotnet test src/Meta/test/LangChain.IntegrationTests.csproj # Run core unit tests dotnet test src/Core/test/LangChain.Core.UnitTests.csproj # Run splitter tests dotnet test src/Splitters/Abstractions/test/LangChain.Splitters.Abstractions.Tests.csproj # Run a specific test dotnet test src/Meta/test/LangChain.IntegrationTests.csproj --filter "FullyQualifiedName~WikiTests" # Validate trimming/NativeAOT compatibility dotnet build src/Helpers/TrimmingHelper/TrimmingHelper.csproj ``` -------------------------------- ### LangChain Usage Example Source: https://github.com/tryagi/langchain/blob/main/docs/index.md This C# code snippet demonstrates how to initialize models, create a vector database from a PDF, and use it to answer questions, both using async methods and chains. ```csharp // Price to run from zero(create embeddings and request to LLM): 0,015$ // Price to re-run if database is exists: 0,0004$ // Dependencies: LangChain, LangChain.Databases.Sqlite, LangChain.DocumentLoaders.Pdf // 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( embeddingModel, // Used to convert text to embeddings dimensions: 1536, // Should be 1536 for TextEmbeddingV3SmallModel dataSource: DataSource.FromUrl("https://canonburyprimaryschool.co.uk/wp-content/uploads/2016/01/Joanne-K.-Rowling-Harry-Potter-Book-1-Harry-Potter-and-the-Philosophers-Stone-EnglishOnlineClub.com_.pdf"), collectionName: "harrypotter", // Can be omitted, use if you want to have multiple collections textSplitter: null); // Default is CharacterTextSplitter(ChunkSize = 4000, ChunkOverlap = 200) // Now we have two ways: use the async methods or use the chains // 1. Async methods // Find similar documents for the question 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 the question var answer = await llm.GenerateAsync( $""" Use the following pieces of context to answer the question at the end. If the answer is not in context then just say that you don't know, don't try to make up an answer. Keep the answer as short as possible. {similarDocuments.AsString()} Question: {question} Helpful Answer: """, cancellationToken: CancellationToken.None).ConfigureAwait(false); Console.WriteLine($"LLM answer: {answer}"); // The cloaked figure. // 2. Chains var promptTemplate = @"Use the following pieces of context to answer the question at the end. If the answer is not in context then just say that you don't know, don't try to make up an answer. Keep the answer as short as possible. Always quote the context in your answer. {context} Question: {text} Helpful Answer:"; var chain = Set("Who was drinking a unicorn blood?") // set the question (default key is "text") | RetrieveSimilarDocuments(vectorCollection, embeddingModel, amount: 5) // take 5 most similar documents | CombineDocuments(outputKey: "context") // combine documents together and put them into context | Template(promptTemplate) // replace context and question in the prompt with their values | LLM(llm.UseConsoleForDebug()); // send the result to the language model var chainAnswer = await chain.RunAsync("text", CancellationToken.None); // get chain result Console.WriteLine("Chain Answer:"+ chainAnswer); // print the result Console.WriteLine($"LLM usage: {llm.Usage}"); // Print usage and price Console.WriteLine($"Embedding model usage: {embeddingModel.Usage}"); // Print usage and price ``` -------------------------------- ### ChainValues Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/types.md Example demonstrating how to create and access data within a ChainValues object. ```csharp var values = new ChainValues(new Dictionary { { "text", "Hello world" }, { "count", 42 } }); var value = values.Value["text"]; // "Hello world" ``` -------------------------------- ### Combining Load and Update Source: https://github.com/tryagi/langchain/blob/main/_autodocs/memory.md Demonstrates how to load memory, chain it with a template and LLM, and then update the memory with the response. ```csharp var memory = new ConversationBufferMemory(); var chain = Chain.LoadMemory(memory, outputKey: "history") | Chain.Template("Previous: {history}\n\nQuestion: {text}") | Chain.LLM(chatClient) | Chain.UpdateMemory(memory, requestKey: "text", responseKey: "text"); await chain.RunAsync("text"); ``` -------------------------------- ### Example of setting a computed value Source: https://github.com/tryagi/langchain/blob/main/_autodocs/chain-factories.md Example of setting a value computed by a lambda function into the chain context. ```csharp var chain = Chain.Set(() => DateTime.Now.ToString(), "timestamp") | Chain.LLM(chatClient); ``` -------------------------------- ### RAG Pattern Example - Option 1 (Convenience Method) Source: https://github.com/tryagi/langchain/blob/main/CLAUDE.md Illustrates the RAG pattern using a convenience method to create a vector store and load documents. ```csharp // Option 1: Convenience method — creates collection + loads documents in one call var vectorStore = new InMemoryVectorStore(); var vectorCollection = await vectorStore.AddDocumentsFromAsync( embeddingGenerator, dimensions: 1536, dataSource: DataSource.FromUrl(url)); var similarDocuments = await vectorCollection.GetSimilarDocuments(embeddingGenerator, question); ``` -------------------------------- ### Clear Method Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/memory.md Example demonstrating how to use the Clear method in BaseChatMemory to clear all stored conversation history. ```csharp var memory = new ConversationBufferMemory(); await memory.Clear(); ``` -------------------------------- ### Stateful Agents Source: https://github.com/tryagi/langchain/blob/main/_autodocs/common-patterns.md Illustrates how to maintain state across multiple tool calls within an agent, using a dictionary for storage. ```csharp var state = new Dictionary(); var memory = new ConversationBufferMemory(); var agent = Chain.ReActAgentExecutor(chatClient) .UseTool( "save_state", "Saves data to agent state", async (input, ct) => { var parts = input.Split("="); state[parts[0]] = parts[1]; return $"Saved {parts[0]} = {parts[1]}"; }) .UseTool( "get_state", "Retrieves saved data", async (key, ct) => { return state.ContainsKey(key) ? state[key].ToString() : "Not found"; }); ``` -------------------------------- ### Code Document Splitting Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/text-splitters.md Example of splitting source code using CSharpSplitter with custom chunk size and overlap. ```csharp var codeSplitter = new CSharpSplitter( chunkSize: 5000, chunkOverlap: 200); var codeChunks = codeSplitter.SplitText(sourceCode); ``` -------------------------------- ### Custom Length Function Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/text-splitters.md Example of using a custom length function with CharacterTextSplitter to count words instead of characters. ```csharp var splitter = new CharacterTextSplitter( chunkSize: 500, lengthFunction: text => text.Split().Length); // Count words instead of characters ``` -------------------------------- ### Splitting Documents for RAG Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/text-splitters.md Example of splitting PDF documents for Retrieval-Augmented Generation (RAG) using PdfPigPdfLoader and RecursiveCharacterTextSplitter. ```csharp var loader = new PdfPigPdfLoader(); var documents = await loader.LoadAsync(DataSource.FromPath("document.pdf")); var splitter = new RecursiveCharacterTextSplitter( chunkSize: 2000, chunkOverlap: 200); var chunks = splitter.SplitDocuments(documents); var vectorStore = new InMemoryVectorStore(); var collection = vectorStore.GetCollection("docs"); await collection.AddDocumentsAsync(embeddingGenerator, chunks); ``` -------------------------------- ### Build and Test Commands Source: https://github.com/tryagi/langchain/blob/main/CLAUDE.md Commands for building the solution, running integration and unit tests, and validating trimming/NativeAOT compatibility. ```bash # Build the entire solution dotnet build LangChain.slnx # Run all integration tests dotnet test src/Meta/test/LangChain.IntegrationTests.csproj # Run core unit tests dotnet test src/Core/test/UnitTests/LangChain.Core.UnitTests.csproj # Run splitter tests dotnet test src/Splitters/Abstractions/test/LangChain.Splitters.Abstractions.Tests.csproj # Run a specific test dotnet test src/Meta/test/LangChain.IntegrationTests.csproj --filter "FullyQualifiedName~WikiTests" # Validate trimming/NativeAOT compatibility (requires: dotnet tool install -g autosdk.cli --prerelease) autosdk trim src/libs/*//*.csproj ``` -------------------------------- ### Automatic Splitting in Vector Store Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/text-splitters.md Example of adding documents from a URL to a vector store with automatic splitting using PdfPigPdfLoader and RecursiveCharacterTextSplitter. ```csharp var collection = await vectorStore.AddDocumentsFromAsync( embeddingGenerator, dimensions: 1536, dataSource: DataSource.FromUrl("https://example.com/doc.pdf"), textSplitter: new RecursiveCharacterTextSplitter( chunkSize: 1500, chunkOverlap: 150)); ``` -------------------------------- ### Unit Testing Chains Source: https://github.com/tryagi/langchain/blob/main/_autodocs/common-patterns.md Write unit tests for LangChain chains using mocking. ```csharp [TestFixture] public class ChainTests { [Test] public async Task TestBasicChain() { var mockChatClient = new Mock(); mockChatClient .Setup(c => c.GetResponseAsync(It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(new ChatCompletion { Content = new[] { new ContentPart { Text = "Test response" } } }); var chain = Chain.Set("test") | Chain.LLM(mockChatClient.Object); var result = await chain.RunAsync("text"); Assert.AreEqual("Test response", result); } } ``` -------------------------------- ### Create Conversation and Send Messages Example Source: https://github.com/tryagi/langchain/blob/main/_autodocs/endpoints.md Bash script demonstrating how to create a conversation, send messages, and retrieve conversation history using cURL. ```bash # Create conversation CONV=$(curl -s -X POST http://localhost:5000/serve/conversations \ -H "Content-Type: application/json" \ -d '{"modelName":"gpt-4"}' | jq -r '.id') echo "Created conversation: $CONV" # Send first message curl -X POST http://localhost:5000/serve/conversations/$CONV/messages \ -H "Content-Type: application/json" \ -d '{"message":"Hello, what can you do?"}' # Get conversation history curl http://localhost:5000/serve/conversations/$CONV/messages ```