LangChain.Net 使用案例
·
1.1、DeepSeek 连接
案例一:
using LangChain.Providers;
using LangChain.Providers.DeepSeek;
using LangChain.Providers.DeepSeek.Predefined;
string apiKey = "sk-30c3xxxxx179e";
var model = new DeepSeekChatModel(new DeepSeekProvider(new DeepSeekConfiguration()
{
ApiKey = apiKey,
Endpoint= "https://api.deepseek.com"
}));
var result = await model.GenerateAsync("详细介绍事件总线,在项目中为什么要使用,如何使用");
Console.WriteLine(result);
Console.ReadLine();
案例二:设置历史数据
using LangChain.Providers;
using LangChain.Providers.DeepSeek;
using LangChain.Providers.DeepSeek.Predefined;
string apiKey = "sk-30c33cxxxxxxxxxxx6179e";
var model = new DeepSeekChatModel(new DeepSeekProvider(new DeepSeekConfiguration()
{
ApiKey = apiKey,
Endpoint= "https://api.deepseek.com"
}));
var result = await model.GenerateAsync(new ChatRequest()
{
Messages = new List<Message> {
new Message(){
Content="你是一名资深的系统架构师",
Role=MessageRole.System
},
new Message(){
Content="详细介绍事件总线,在项目中为什么要使用,如何使用",
Role=MessageRole.Human
}
}
});
Console.WriteLine(result);
Console.ReadLine();
案例三:流式输出
using LangChain.Providers;
using LangChain.Providers.DeepSeek;
using LangChain.Providers.DeepSeek.Predefined;
string apiKey = "sk-30c33xxxxxxxx592f3d6179e";
var model = new DeepSeekChatModel(new DeepSeekProvider(new DeepSeekConfiguration()
{
ApiKey = apiKey,
Endpoint= "https://api.deepseek.com"
}));
await foreach (var chunk in model.GenerateAsync(new ChatRequest()
{
Messages = new List<Message> {
new Message(){
Content="你是一名资深的系统架构师",
Role=MessageRole.System
},
new Message(){
Content="详细介绍事件总线,在项目中为什么要使用,如何使用",
Role=MessageRole.Human
}
}
}, new ChatSettings(){ UseStreaming = true }))
{
Console.Write(chunk);
}
1.2、模板
案例一:增加模板
using LangChain.Chains.LLM;
using LangChain.Prompts;
using LangChain.Providers;
using LangChain.Providers.DeepSeek;
using LangChain.Providers.DeepSeek.Predefined;
string apiKey = "sk-30c3xxxxxxxxxxxxxxx592f3d6179e";
var model = new DeepSeekChatModel(new DeepSeekProvider(new DeepSeekConfiguration()
{
ApiKey = apiKey,
Endpoint= "https://api.deepseek.com"
}));
var propmpt = new PromptTemplate(new PromptTemplateInput(
template:"请详细介绍{product}",
inputVariables: ["product"]
));
var chain = new LlmChain(new LlmChainInput(model, prompt: propmpt));
//var result = await chain.CallAsync(new ChainValues(new Dictionary<string, object>() {
// { "product","CAP" }
//}));
//Console.WriteLine(result.Value["text"]);
var result2 = await chain.RunAsync(input:new Dictionary<string, object>() {
{ "product","MySql索引" }
});
Console.WriteLine(result2);
模板二:模板多参数
using LangChain.Chains.LLM;
using LangChain.Prompts;
using LangChain.Providers;
using LangChain.Providers.DeepSeek;
using LangChain.Providers.DeepSeek.Predefined;
using LangChain.Schema;
string apiKey = "sk-30cxxxxxxxxxxxxx592f3d6179e";
var model = new DeepSeekChatModel(new DeepSeekProvider(new DeepSeekConfiguration()
{
ApiKey = apiKey,
Endpoint= "https://api.deepseek.com"
}));
var prompt = ChatPromptTemplate.FromPromptMessages(new List<BaseMessagePromptTemplate>() {
SystemMessagePromptTemplate.FromTemplate("请将{input}翻译为{output}"),
HumanMessagePromptTemplate.FromTemplate("{text}")
});
var chat = new LlmChain(new LlmChainInput(model, prompt) {
Verbose = true,
});
var result = await chat.CallAsync(new ChainValues(new Dictionary<string, object>(3) {
{ "input","中文"},
{ "output","英文"},
{ "text","早上好,很高兴见到你" }
}));
Console.WriteLine(result.Value["text"]);
Console.ReadLine();
1.3、历史记录
using LangChain.Memory;
using LangChain.Providers;
using LangChain.Providers.DeepSeek;
using LangChain.Providers.DeepSeek.Predefined;
using static LangChain.Chains.Chain;
internal class Program
{
private static async Task Main(string[] args)
{
string apiKey = "sk-30xxxxxxxxxxxxxxxf3d6179e";
var model = new DeepSeekChatModel(new DeepSeekProvider(new DeepSeekConfiguration()
{
ApiKey = apiKey,
Endpoint = "https://api.deepseek.com"
}));
var template = @"以下是人类和人工智能之间的友好对话。
{history}
Human: {input}
AI:
";
var memory = PickMemoryStrategy(model);
var chain = LoadMemory(memory, outputKey: "history")
| Template(template)
| LLM(model)
| UpdateMemory(memory, requestKey: "input", responseKey: "text");
while (true)
{
Console.WriteLine();
Console.Write("Human: ");
var input = Console.ReadLine() ?? string.Empty;
if (input == "exit")
{
break;
}
//通过将用户的输入添加到原始链中来构建新链
var currentChain = Set(input, "input")
| chain;
// 从AI获得响应
var response = await currentChain.RunAsync("text");
Console.Write("AI: ");
Console.WriteLine(response);
}
}
/// <summary>
/// 获取其他历史记录
/// </summary>
/// <returns></returns>
private static BaseChatMessageHistory GetChatMessageHistory()
{
//获取其他历史记录
return new ChatMessageHistory();
}
private static BaseChatMemory PickMemoryStrategy(IChatModel model)
{
MessageFormatter messageFormatter = new MessageFormatter {
AiPrefix = "AI",
HumanPrefix = "Human"
};
BaseChatMessageHistory chatHistory= GetChatMessageHistory();
string memoryClassName = PromptForChoice(new[]
{
nameof(ConversationBufferMemory),
nameof(ConversationWindowBufferMemory),
nameof(ConversationSummaryMemory),
nameof(ConversationSummaryBufferMemory)
});
switch (memoryClassName)
{
case nameof(ConversationBufferMemory):
return GetConversationBufferMemory(chatHistory, messageFormatter);
case nameof(ConversationWindowBufferMemory):
return GetConversationWindowBufferMemory(chatHistory, messageFormatter);
case nameof(ConversationSummaryMemory):
return GetConversationSummaryMemory(chatHistory, messageFormatter, model);
case nameof(ConversationSummaryBufferMemory):
return GetConversationSummaryBufferMemory(chatHistory, messageFormatter, (IChatModelWithTokenCounting)model);
default:
throw new InvalidOperationException($"Unexpected memory class name: '{memoryClassName}'");
}
}
private static string PromptForChoice(string[] choiceTexts)
{
while (true)
{
Console.Clear();
Console.WriteLine("从以下选项中选择:");
int choiceNumber = 1;
foreach (string choiceText in choiceTexts)
{
Console.WriteLine($" {choiceNumber}: {choiceText}");
choiceNumber++;
}
Console.WriteLine();
Console.Write("Enter choice: ");
string choiceEntry = Console.ReadLine() ?? string.Empty;
if (int.TryParse(choiceEntry, out int choiceIndex))
{
string choiceText = choiceTexts[choiceIndex];
Console.WriteLine();
Console.WriteLine($"You selected '{choiceText}'");
return choiceText;
}
}
}
private static BaseChatMemory GetConversationBufferMemory(BaseChatMessageHistory chatHistory, MessageFormatter messageFormatter)
{
return new ConversationBufferMemory(chatHistory)
{
Formatter = messageFormatter
};
}
private static BaseChatMemory GetConversationWindowBufferMemory(BaseChatMessageHistory chatHistory, MessageFormatter messageFormatter)
{
return new ConversationWindowBufferMemory(chatHistory)
{
WindowSize = 3,
Formatter = messageFormatter
};
}
private static BaseChatMemory GetConversationSummaryMemory(BaseChatMessageHistory chatHistory, MessageFormatter messageFormatter, IChatModel model)
{
return new ConversationSummaryMemory(model, chatHistory)
{
Formatter = messageFormatter
};
}
private static BaseChatMemory GetConversationSummaryBufferMemory(BaseChatMessageHistory chatHistory, MessageFormatter messageFormatter, IChatModelWithTokenCounting model)
{
return new ConversationSummaryBufferMemory(model, chatHistory)
{
MaxTokenCount = 25,
Formatter = messageFormatter
};
}
}
1.4、多模态
using LangChain.Abstractions.Chains.Base;
using LangChain.Chains.LLM;
using LangChain.Chains.Sequentials;
using LangChain.Prompts;
using LangChain.Providers;
using LangChain.Providers.DeepSeek;
using LangChain.Providers.DeepSeek.Predefined;
using LangChain.Schema;
string apiKey = "sk-30c3xxxxxxxxxxxxxxx92f3d6179e";
var model = new DeepSeekChatModel(new DeepSeekProvider(new DeepSeekConfiguration()
{
ApiKey = apiKey,
Endpoint = "https://api.deepseek.com"
}));
var firstTemplate = "What is a good name for a company that makes {product}?";
var firstPrompt = new PromptTemplate(new PromptTemplateInput(firstTemplate,new List<string> { "product" }));
// 创建第一个 LLM 链,配置如下:
// - 使用上面定义的 OpenAI 模型和提示模板
// - 开启详细日志输出(Verbose = true)
// - 指定输出键为 "company_name"(便于后续链获取结果)
var chainOne = new LlmChain(new LlmChainInput(model, firstPrompt) {
Verbose=true,
OutputKey= "company_name"
});
// 第二个提示模板:用于生成公司描述,包含占位符 {company_name}
var secongTemplate = "Write a 50 words description for the following company:{company_name}";
// company_name : 声明需要从上游链获取的参数
var secondPrompt = new PromptTemplate(new PromptTemplateInput(secongTemplate, new List<string> { "company_name" }));
var chainTwo = new LlmChain(new LlmChainInput(model, secondPrompt));
// - chains: 按顺序执行的链数组(chainOne → chainTwo)
// - inputVariables: 整个链的初始输入参数(此处为 product)
// - outputVariables: 最终输出的结果键(此处包含 chainOne 输出的 company_name 和 chainTwo 输出的 text)
var overallChain = new SequentialChain(new SequentialChainInput(
new IChain[]{ chainOne, chainTwo },
new[] { "product" }, // 初始输入参数
new[] { "company_name", "text" } // 最终输出值对应的键
));
// 执行链式调用,传入初始参数 product="colourful socks"
var result = await overallChain.CallAsync(new ChainValues(
new Dictionary<string, object> {
{ "product", "colourful socks" } // 设置输入参数
}
));
// 输出第二个链生成的公司描述(通过键 "text" 获取结果)
Console.WriteLine(result.Value["text"]);
Console.WriteLine("SequentialChain sample finished.");
Console.ReadLine();
1.5、导入向量库
案例一:导入文档
using LangChain.Databases.Sqlite;
using LangChain.DocumentLoaders;
using LangChain.Extensions;
using LangChain.Providers;
using LangChain.Providers.Ollama;
using LangChain.Splitters.Text;
var provider =new OllamaProvider();
var embeddingModel = new OllamaEmbeddingModel(provider,id: "all-minilm:latest");
var llm = new OllamaChatModel(provider,id: "llama3:latest");
var vectorDatabase = new SqLiteVectorDatabase(dataSource: "vectors.db");
// 使用文本分割器
var textSplitter = new RecursiveCharacterTextSplitter(
chunkSize: 1000,
chunkOverlap: 200
);
var vectorCollection = await vectorDatabase.AddDocumentsFromAsync<PdfPigPdfLoader>(
embeddingModel,
dimensions:1384,
dataSource:DataSource.FromPath("D:\\123.pdf"),
//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",
textSplitter: textSplitter,
behavior: AddDocumentsToDatabaseBehavior.AlwaysAddDocuments);
var question = "介绍菜品管理";
var similarDocuments = await vectorCollection.GetSimilarDocuments(embeddingModel, question,amount:10);
var answer = await llm.GenerateAsync(
$"""
使用以下上下文来回答最后的问题。
如果答案与上下文不符,那么就说你不知道,不要试图编造答案。
请确保答案尽可能简短。所有内容中文回答
{similarDocuments.AsString()}
问题: {question}
回答:
""");
Console.WriteLine($"LLM answer: {answer}");
Console.ReadLine();
案例二:读取向量库
using LangChain.Databases.Sqlite;
using LangChain.Extensions;
using LangChain.Providers;
using LangChain.Providers.Ollama;
var provider = new OllamaProvider();
var embeddingModel = new OllamaEmbeddingModel(provider, id: "all-minilm:latest");
var llm = new OllamaChatModel(provider, id: "llama3:latest");
// 连接到现有的向量数据库
var vectorDatabase = new SqLiteVectorDatabase(dataSource: "vectors.db");
// 获取现有的集合(不需要添加新文档)
var vectorCollection = await vectorDatabase.GetCollectionAsync("harrypotter");
var question = "介绍菜品管理";
var similarDocuments = await vectorCollection.GetSimilarDocuments(embeddingModel, question, amount: 5); // 减少数量以提高精度
// 输出相似文档用于调试
//Console.WriteLine($"检索到的相关文档: {similarDocuments.AsString()}");
var answer = await llm.GenerateAsync(
$"""
使用以下上下文来回答最后的问题。
如果答案与上下文不符,那么就说你不知道,不要试图编造答案。
请确保答案尽可能简短。所有内容中文回答
{similarDocuments.AsString()}
问题: {question}
回答:
""");
Console.WriteLine($"LLM 回答: {answer}");
Console.ReadLine();
1.6、HuggingFace
using LangChain.Providers;
using LangChain.Providers.HuggingFace;
using LangChain.Providers.HuggingFace.Predefined;
var apiKey = "hf_LDCUmQqaHxxxxxxxxxxxoMVMQhceoS";
using var client = new HttpClient();
var provider = new HuggingFaceProvider(apiKey:apiKey,client);
var gpt2Model = new Gpt2Model(provider);
var gp2ModelResponse = await gpt2Model.GenerateAsync("给一家生产彩色袜子的公司起个好名字是什么?");
Console.WriteLine("### GP2 Response");
Console.WriteLine(gp2ModelResponse);
const string imageToTextModel = "Salesforce/blip-image-captioning-base";
var model = new HuggingFaceImageToTextModel(provider, imageToTextModel);
var path = Path.Combine(Path.GetTempPath(), "solar_system.png");
var imageData = await File.ReadAllBytesAsync(path);
var binaryData = new BinaryData(imageData, "image/jpg");
var imageToTextResponse = await model.GenerateTextFromImageAsync(new ImageToTextRequest
{
Image = binaryData
});
Console.WriteLine("\n\n### ImageToText Response");
Console.WriteLine(imageToTextResponse.Text);
Console.ReadLine();
1.7、Web Api请求大模型
Program.cs
using LangChain.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddOpenAi();
builder.Services.AddAnthropic();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
api:
[ApiController]
[Route("[controller]")]
public class OpenAiSampleController : ControllerBase
{
private readonly OpenAiProvider _openAi;
public OpenAiSampleController(OpenAiProvider openAi)
{
_openAi = openAi;
}
[HttpGet(Name = "GetOpenAiResponse")]
public async Task<string> Get()
{
var llm = new OpenAiChatModel(_openAi, id: ChatClient.LatestFastModel);
var response = await llm.GenerateAsync("What is a good name for a company that sells colourful socks?");
return response.LastMessageContent;
}
}
[ApiController]
[Route("[controller]")]
public class AnthropicSampleController : ControllerBase
{
private readonly AnthropicChatModel _anthropicModel;
public AnthropicSampleController(AnthropicChatModel anthropicModel)
{
_anthropicModel = anthropicModel;
}
[HttpGet(Name = "GetAnthropicResponse")]
public async Task<string> Get()
{
var response = await _anthropicModel.GenerateAsync("What is a good name for a company that sells colourful socks?");
return response.LastMessageContent;
}
}
更多推荐


所有评论(0)