LangChain.dart 學(xué)習(xí)筆記

?? 目錄

  1. 簡(jiǎn)介
  2. 核心概念
  3. 包結(jié)構(gòu)
  4. 支持的集成
  5. 快速開(kāi)始
  6. 核心模塊詳解
  7. 實(shí)戰(zhàn)示例
  8. 最佳實(shí)踐
  9. 學(xué)習(xí)資源
    10.[call me wechat??]: tradingba

?? 簡(jiǎn)介

什么是 LangChain.dart?

LangChain.dart 是由 Harrison Chase 創(chuàng)建的流行 Python 框架 LangChain 的非官方 Dart 移植版本。它為開(kāi)發(fā)者提供了一套開(kāi)箱即用的組件,用于構(gòu)建基于大語(yǔ)言模型(LLM)的應(yīng)用程序。

核心優(yōu)勢(shì)

  • ?? 統(tǒng)一接口: 提供統(tǒng)一的 API 與各種 LLM 提供商交互(OpenAI、Google、Mistral、Ollama 等)
  • ?? 鏈?zhǔn)秸{(diào)用: 支持通過(guò) LCEL(LangChain Expression Language)將組件鏈接在一起
  • ?? 跨平臺(tái): 支持 Dart 和 Flutter,可運(yùn)行在 Android、iOS、Linux、macOS、Web、Windows
  • ?? 模塊化設(shè)計(jì): 可按需導(dǎo)入所需組件
  • ?? 豐富的集成: 支持主流 LLM 服務(wù)和工具

應(yīng)用場(chǎng)景

  • ?? 聊天機(jī)器人(Chatbots)
  • ? 問(wèn)答系統(tǒng)(Q&A with RAG)
  • ?? 智能代理(Agents)
  • ?? 文本摘要(Summarization)
  • ?? 翻譯(Translation)
  • ?? 信息提?。‥xtraction)
  • ?? 推薦系統(tǒng)(Recommendation Systems)

?? 核心概念

LangChain.dart 的組件可以分為三個(gè)核心模塊:

1. ?? Model I/O(模型輸入輸出)

  • 功能: 與各種 LLM 提供商交互的統(tǒng)一 API
  • 包含:
    • 提示模板(Prompt Templates)
    • 示例選擇器(Example Selectors)
    • 輸出解析器(Output Parsers)
  • 優(yōu)勢(shì): 輕松切換不同的 LLM 提供商

2. ?? Retrieval(檢索)

  • 功能: 實(shí)現(xiàn) RAG(檢索增強(qiáng)生成)
  • 包含:
    • 文檔加載器(Document Loaders)
    • 文本分割器(Text Splitters)
    • 嵌入模型(Embedding Models)
    • 向量存儲(chǔ)(Vector Stores)
    • 檢索器(Retrievers)

3. ?? Agents(代理)

  • 功能: 基于 LLM 的智能決策機(jī)器人
  • 能力: 可以使用工具(web 搜索、計(jì)算器、數(shù)據(jù)庫(kù)查詢(xún)等)來(lái)完成任務(wù)

4. ?? LCEL(LangChain Expression Language)

組件間的連接語(yǔ)言,使用管道(pipe)操作符將不同組件串聯(lián)起來(lái)。


?? 包結(jié)構(gòu)

LangChain.dart 采用模塊化設(shè)計(jì),由多個(gè)包組成:

核心包

1. langchain_core

  • 用途: 核心抽象和 LCEL
  • 適用: 構(gòu)建框架或與 LangChain.dart 互操作
  • 依賴(lài): langchain 已包含此包,無(wú)需顯式依賴(lài)

2. langchain

  • 用途: 高級(jí)鏈、代理、檢索算法
  • 適用: 構(gòu)建 LLM 應(yīng)用
  • 安裝:
    dependencies:
      langchain: ^0.8.0+1
    

3. langchain_community

  • 用途: 第三方集成和社區(qū)貢獻(xiàn)組件
  • 適用: 需要使用社區(qū)提供的集成時(shí)
  • 安裝:
    dependencies:
      langchain_community: ^0.8.0+1
    

集成包

常用的第三方集成獨(dú)立包:

包名 用途
langchain_openai OpenAI 集成(GPT-4o, o1, 嵌入, 工具, 視覺(jué), DALL·E 3等)
langchain_google Google 集成(Gemini, PaLM 2, 嵌入, 向量搜索等)
langchain_anthropic Anthropic 集成(Claude 3.5 Sonnet, Opus, Haiku等)
langchain_ollama Ollama 集成(Llama 3.2, Gemma 2, Phi-3.5等)
langchain_mistralai Mistral AI 集成
langchain_firebase Firebase 集成(VertexAI for Firebase)
langchain_chroma Chroma 向量數(shù)據(jù)庫(kù)集成
langchain_pinecone Pinecone 向量數(shù)據(jù)庫(kù)集成
langchain_supabase Supabase 向量數(shù)據(jù)庫(kù)集成

API 客戶(hù)端包

可獨(dú)立使用的 API 客戶(hù)端:

包名 用途
openai_dart OpenAI API 客戶(hù)端
googleai_dart Google AI API 客戶(hù)端
anthropic_sdk_dart Anthropic API 客戶(hù)端
ollama_dart Ollama API 客戶(hù)端
mistralai_dart Mistral AI API 客戶(hù)端
vertex_ai GCP Vertex AI API 客戶(hù)端
chromadb Chroma DB API 客戶(hù)端
tavily_dart Tavily API 客戶(hù)端
openai_realtime_dart OpenAI Realtime API 客戶(hù)端

?? 支持的集成

Chat Models(聊天模型)

模型 流式 工具 視覺(jué) 說(shuō)明
ChatOpenAI langchain_openai ? ? ? OpenAI Chat API 及兼容服務(wù)
ChatGoogleGenerativeAI langchain_google ? ? ? Google AI (Gemini API)
ChatAnthropic langchain_anthropic ? ? ? Anthropic Messages API (Claude)
ChatOllama langchain_ollama ? ? ? Ollama Chat API
ChatFirebaseVertexAI langchain_firebase ? ? ? Vertex AI for Firebase
ChatMistralAI langchain_mistralai ? - - Mistral Chat API
ChatVertexAI langchain_google - - - GCP Vertex AI Chat API

LLMs(傳統(tǒng)語(yǔ)言模型)

注意: 優(yōu)先使用 Chat Models,因?yàn)樵S多提供商已棄用 LLMs

模型 流式 說(shuō)明
Ollama langchain_ollama ? Ollama Completions API
OpenAI langchain_openai ? OpenAI Completions API
VertexAI langchain_google - GCP Vertex AI Text API

Embedding Models(嵌入模型)

模型 說(shuō)明
OpenAIEmbeddings langchain_openai OpenAI 嵌入 API
GoogleGenerativeAIEmbeddings langchain_google Google AI 嵌入 API
VertexAIEmbeddings langchain_google GCP Vertex AI 嵌入 API
OllamaEmbeddings langchain_ollama Ollama 嵌入 API
MistralAIEmbeddings langchain_mistralai Mistral 嵌入 API

Vector Stores(向量存儲(chǔ))

存儲(chǔ) 說(shuō)明
MemoryVectorStore langchain 內(nèi)存向量存儲(chǔ)(原型和測(cè)試)
Chroma langchain_chroma Chroma 集成
Pinecone langchain_pinecone Pinecone 集成
Supabase langchain_supabase Supabase Vector 集成
ObjectBoxVectorStore langchain_community ObjectBox 集成
VertexAIMatchingEngine langchain_google Vertex AI Vector Search

Tools(工具)

工具 說(shuō)明
CalculatorTool langchain_community 計(jì)算數(shù)學(xué)表達(dá)式
TavilySearchResultsTool langchain_community Tavily 搜索引擎查詢(xún)
TavilyAnswerTool langchain_community Tavily 搜索引擎答案
OpenAIDallETool langchain_openai OpenAI DALL-E 圖像生成

?? 快速開(kāi)始

1. 安裝依賴(lài)

pubspec.yaml 中添加依賴(lài):

dependencies:
  langchain: ^0.8.0+1
  langchain_openai: ^0.8.0+1  # 如果使用 OpenAI
  langchain_google: ^0.8.0+1  # 如果使用 Google
  langchain_community: ^0.8.0+1  # 如果需要社區(qū)組件

2. 基礎(chǔ)示例:調(diào)用 LLM

import 'package:langchain_google/langchain_google.dart';

void main() async {
  // 創(chuàng)建模型實(shí)例
  final model = ChatGoogleGenerativeAI(
    apiKey: 'YOUR_GOOGLE_API_KEY',
  );
  
  // 創(chuàng)建提示
  final prompt = PromptValue.string('Hello world!');
  
  // 調(diào)用模型
  final result = await model.invoke(prompt);
  
  print(result);
  // 輸出: Hello everyone! I'm new here and excited to be part of this community.
}

3. 簡(jiǎn)單鏈?zhǔn)秸{(diào)用

import 'package:langchain/langchain.dart';
import 'package:langchain_openai/langchain_openai.dart';

void main() async {
  // 創(chuàng)建提示模板
  final promptTemplate = ChatPromptTemplate.fromTemplate(
    '講一個(gè)關(guān)于{topic}的笑話(huà)',
  );
  
  // 創(chuàng)建模型
  final model = ChatOpenAI(
    apiKey: 'YOUR_OPENAI_API_KEY',
    defaultOptions: ChatOpenAIOptions(
      model: 'gpt-4',
      temperature: 0.8,
    ),
  );
  
  // 創(chuàng)建輸出解析器
  const outputParser = StringOutputParser<ChatResult>();
  
  // 構(gòu)建鏈:提示模板 -> 模型 -> 輸出解析器
  final chain = promptTemplate.pipe(model).pipe(outputParser);
  
  // 執(zhí)行鏈
  final result = await chain.invoke({'topic': '程序員'});
  
  print(result);
}

?? 核心模塊詳解

Model I/O(模型輸入輸出)

1. Prompt Templates(提示模板)

提示模板用于格式化輸入,支持變量替換:

// 簡(jiǎn)單字符串模板
final promptTemplate = ChatPromptTemplate.fromTemplate(
  'Tell me a joke about {topic}',
);

// 多消息模板
final promptTemplate = ChatPromptTemplate.fromTemplates([
  (ChatMessageType.system, 'You are a helpful assistant'),
  (ChatMessageType.human, '{input}'),
]);

// 使用模板
final formattedPrompt = promptTemplate.format({'topic': 'cats'});

2. Output Parsers(輸出解析器)

解析模型輸出為結(jié)構(gòu)化數(shù)據(jù):

// 字符串輸出解析器
const stringParser = StringOutputParser<ChatResult>();
final result = await model.pipe(stringParser).invoke(prompt);

// JSON 輸出解析器
// 自定義解析器可以將輸出解析為特定數(shù)據(jù)結(jié)構(gòu)

3. Chat Models 使用

final model = ChatOpenAI(
  apiKey: apiKey,
  defaultOptions: ChatOpenAIOptions(
    model: 'gpt-4o',
    temperature: 0.7,
    maxTokens: 1000,
  ),
);

// 單次調(diào)用
final response = await model.invoke(
  PromptValue.string('你好'),
);

// 流式調(diào)用
final stream = model.stream(
  PromptValue.string('寫(xiě)一首詩(shī)'),
);
await for (final chunk in stream) {
  print(chunk);
}

Retrieval(檢索 - RAG)

完整的 RAG 流程

import 'package:langchain/langchain.dart';
import 'package:langchain_openai/langchain_openai.dart';

Future<void> ragExample() async {
  // 1. 創(chuàng)建向量存儲(chǔ)并添加文檔
  final vectorStore = MemoryVectorStore(
    embeddings: OpenAIEmbeddings(apiKey: openaiApiKey),
  );
  
  await vectorStore.addDocuments(
    documents: [
      Document(pageContent: 'LangChain was created by Harrison'),
      Document(pageContent: 'David ported LangChain to Dart in LangChain.dart'),
    ],
  );

  // 2. 定義檢索鏈
  final retriever = vectorStore.asRetriever();
  final setupAndRetrieval = Runnable.fromMap<String>({
    'context': retriever.pipe(
      Runnable.mapInput(
        (docs) => docs.map((d) => d.pageContent).join('\n'),
      ),
    ),
    'question': Runnable.passthrough(),
  });

  // 3. 構(gòu)建 RAG 提示模板
  final promptTemplate = ChatPromptTemplate.fromTemplates([
    (
      ChatMessageType.system,
      'Answer the question based on only the following context:\n{context}'
    ),
    (ChatMessageType.human, '{question}'),
  ]);

  // 4. 定義最終鏈
  final model = ChatOpenAI(apiKey: openaiApiKey);
  const outputParser = StringOutputParser<ChatResult>();
  
  final chain = setupAndRetrieval
      .pipe(promptTemplate)
      .pipe(model)
      .pipe(outputParser);

  // 5. 運(yùn)行管道
  final res = await chain.invoke('Who created LangChain.dart?');
  print(res);
  // 輸出: David created LangChain.dart
}

Document Loaders(文檔加載器)

// 加載文本文件
final loader = TextLoader('path/to/file.txt');
final documents = await loader.load();

// 加載 JSON 文件
final jsonLoader = JsonLoader('path/to/data.json');
final jsonDocs = await jsonLoader.load();

Text Splitters(文本分割器)

// 按字符分割
final splitter = CharacterTextSplitter(
  chunkSize: 1000,
  chunkOverlap: 200,
);
final chunks = await splitter.splitDocuments(documents);

// 遞歸分割
final recursiveSplitter = RecursiveCharacterTextSplitter(
  chunkSize: 1000,
  chunkOverlap: 200,
);

Embeddings(嵌入)

// OpenAI 嵌入
final embeddings = OpenAIEmbeddings(
  apiKey: apiKey,
  model: 'text-embedding-3-small',
);

// 嵌入文檔
final docEmbeddings = await embeddings.embedDocuments([
  'This is a document',
  'This is another document',
]);

// 嵌入查詢(xún)
final queryEmbedding = await embeddings.embedQuery('search query');

Agents(代理)

代理可以根據(jù)用戶(hù)輸入自主決定使用哪些工具:

import 'package:langchain/langchain.dart';
import 'package:langchain_openai/langchain_openai.dart';
import 'package:langchain_community/langchain_community.dart';

Future<void> agentExample() async {
  // 1. 定義工具
  final tools = [
    CalculatorTool(),
    Tool(
      name: 'search',
      description: 'Useful for searching the web',
      func: (input) async => 'Search results for: $input',
    ),
  ];

  // 2. 創(chuàng)建代理
  final llm = ChatOpenAI(
    apiKey: apiKey,
    defaultOptions: ChatOpenAIOptions(
      model: 'gpt-4',
      temperature: 0,
    ),
  );

  final agent = OpenAIFunctionsAgent.fromLLMAndTools(
    llm: llm,
    tools: tools,
  );

  // 3. 創(chuàng)建執(zhí)行器
  final executor = AgentExecutor(agent: agent);

  // 4. 運(yùn)行代理
  final result = await executor.run(
    'What is 25 * 4? Then search for information about that number.',
  );
  
  print(result);
}

?? 實(shí)戰(zhàn)示例

示例 1: 簡(jiǎn)單問(wèn)答

import 'package:langchain/langchain.dart';
import 'package:langchain_openai/langchain_openai.dart';

Future<void> simpleQA() async {
  final model = ChatOpenAI(
    apiKey: 'YOUR_API_KEY',
    defaultOptions: ChatOpenAIOptions(model: 'gpt-4'),
  );
  
  final prompt = PromptValue.chat([
    ChatMessage.system('You are a helpful assistant.'),
    ChatMessage.humanText('What is the capital of France?'),
  ]);
  
  final response = await model.invoke(prompt);
  print(response.output.content);
}

示例 2: 流式聊天

Future<void> streamingChat() async {
  final model = ChatOpenAI(
    apiKey: 'YOUR_API_KEY',
    defaultOptions: ChatOpenAIOptions(model: 'gpt-4'),
  );
  
  final prompt = PromptValue.string('Write a long story about a robot.');
  
  final stream = model.stream(prompt);
  
  await for (final chunk in stream) {
    // 實(shí)時(shí)輸出每個(gè) token
    stdout.write(chunk.output.content);
  }
}

示例 3: 使用工具的聊天

Future<void> chatWithTools() async {
  final model = ChatOpenAI(
    apiKey: 'YOUR_API_KEY',
    defaultOptions: ChatOpenAIOptions(
      model: 'gpt-4',
      tools: [
        // 定義工具
        ChatTool(
          type: 'function',
          function: {
            'name': 'get_weather',
            'description': 'Get the weather for a location',
            'parameters': {
              'type': 'object',
              'properties': {
                'location': {
                  'type': 'string',
                  'description': 'The city name',
                },
              },
              'required': ['location'],
            },
          },
        ),
      ],
    ),
  );
  
  final response = await model.invoke(
    PromptValue.string('What\'s the weather in Beijing?'),
  );
  
  // 處理工具調(diào)用
  if (response.output.toolCalls.isNotEmpty) {
    final toolCall = response.output.toolCalls.first;
    print('Model wants to call: ${toolCall.name}');
    print('With arguments: ${toolCall.arguments}');
  }
}

示例 4: 多模態(tài)(視覺(jué))

Future<void> visionExample() async {
  final model = ChatOpenAI(
    apiKey: 'YOUR_API_KEY',
    defaultOptions: ChatOpenAIOptions(
      model: 'gpt-4-vision-preview',
    ),
  );
  
  final prompt = PromptValue.chat([
    ChatMessage.human(
      ChatMessageContent.multiModal([
        ChatMessageContent.text('What is in this image?'),
        ChatMessageContent.image(
          mimeType: 'image/jpeg',
          data: base64Image, // base64 編碼的圖片
        ),
      ]),
    ),
  ]);
  
  final response = await model.invoke(prompt);
  print(response.output.content);
}

示例 5: 文檔問(wèn)答系統(tǒng)

Future<void> documentQA() async {
  // 1. 加載文檔
  final loader = TextLoader('knowledge_base.txt');
  final documents = await loader.load();
  
  // 2. 分割文檔
  final splitter = RecursiveCharacterTextSplitter(
    chunkSize: 500,
    chunkOverlap: 50,
  );
  final chunks = await splitter.splitDocuments(documents);
  
  // 3. 創(chuàng)建向量存儲(chǔ)
  final embeddings = OpenAIEmbeddings(apiKey: apiKey);
  final vectorStore = MemoryVectorStore(embeddings: embeddings);
  await vectorStore.addDocuments(documents: chunks);
  
  // 4. 創(chuàng)建 QA 鏈
  final retriever = vectorStore.asRetriever(
    searchKwargs: {'k': 3}, // 檢索前3個(gè)最相關(guān)的文檔
  );
  
  final qaPrompt = ChatPromptTemplate.fromTemplates([
    (
      ChatMessageType.system,
      'Use the following context to answer the question:\n\n{context}'
    ),
    (ChatMessageType.human, '{question}'),
  ]);
  
  final model = ChatOpenAI(apiKey: apiKey);
  const parser = StringOutputParser<ChatResult>();
  
  final qaChain = Runnable.fromMap({
    'context': retriever.pipe(
      Runnable.mapInput((docs) => docs.map((d) => d.pageContent).join('\n\n')),
    ),
    'question': Runnable.passthrough(),
  }).pipe(qaPrompt).pipe(model).pipe(parser);
  
  // 5. 提問(wèn)
  final answer = await qaChain.invoke('What is LangChain?');
  print(answer);
}

示例 6: 會(huì)話(huà)記憶

Future<void> conversationWithMemory() async {
  final model = ChatOpenAI(apiKey: apiKey);
  
  // 創(chuàng)建會(huì)話(huà)記憶
  final memory = ConversationBufferMemory();
  
  // 定義對(duì)話(huà)鏈
  final prompt = ChatPromptTemplate.fromTemplates([
    (ChatMessageType.system, 'You are a helpful assistant.'),
    (ChatMessageType.human, '{history}\nHuman: {input}'),
  ]);
  
  final chain = prompt.pipe(model);
  
  // 多輪對(duì)話(huà)
  final inputs = [
    'My name is John',
    'What is my name?',
    'What is 2+2?',
  ];
  
  for (final input in inputs) {
    final history = await memory.loadMemoryVariables();
    final result = await chain.invoke({
      'input': input,
      'history': history['history'] ?? '',
    });
    
    // 保存到記憶
    await memory.saveContext(
      inputValues: {'input': input},
      outputValues: {'output': result.output.content},
    );
    
    print('Human: $input');
    print('AI: ${result.output.content}\n');
  }
}

?? 最佳實(shí)踐

1. API Key 管理

// ? 不要硬編碼 API Key
final model = ChatOpenAI(apiKey: 'sk-...');

// ? 使用環(huán)境變量
final apiKey = Platform.environment['OPENAI_API_KEY']!;
final model = ChatOpenAI(apiKey: apiKey);

// ? 使用 flutter_dotenv
import 'package:flutter_dotenv/flutter_dotenv.dart';

await dotenv.load();
final apiKey = dotenv.env['OPENAI_API_KEY']!;

2. 錯(cuò)誤處理

try {
  final result = await model.invoke(prompt);
  print(result);
} on LLMException catch (e) {
  print('LLM Error: ${e.message}');
} on HttpException catch (e) {
  print('Network Error: $e');
} catch (e) {
  print('Unexpected Error: $e');
}

3. 選擇合適的模型

// 對(duì)于簡(jiǎn)單任務(wù),使用較小的模型
final simpleModel = ChatOpenAI(
  apiKey: apiKey,
  defaultOptions: ChatOpenAIOptions(model: 'gpt-3.5-turbo'),
);

// 對(duì)于復(fù)雜任務(wù),使用更強(qiáng)大的模型
final advancedModel = ChatOpenAI(
  apiKey: apiKey,
  defaultOptions: ChatOpenAIOptions(model: 'gpt-4'),
);

4. 控制輸出長(zhǎng)度和隨機(jī)性

final model = ChatOpenAI(
  apiKey: apiKey,
  defaultOptions: ChatOpenAIOptions(
    model: 'gpt-4',
    temperature: 0.0,  // 0=確定性,1=更隨機(jī)
    maxTokens: 500,    // 限制輸出長(zhǎng)度
    topP: 0.95,        // nucleus sampling
  ),
);

5. 向量存儲(chǔ)選擇

  • 開(kāi)發(fā)/測(cè)試: 使用 MemoryVectorStore(內(nèi)存存儲(chǔ))
  • 生產(chǎn)環(huán)境: 使用 Chroma、PineconeSupabase(持久化存儲(chǔ))
// 開(kāi)發(fā)環(huán)境
final devStore = MemoryVectorStore(embeddings: embeddings);

// 生產(chǎn)環(huán)境
final prodStore = Chroma(
  embeddings: embeddings,
  collectionName: 'my_collection',
);

6. 文本分割策略

// 對(duì)于代碼文檔
final codeSplitter = RecursiveCharacterTextSplitter(
  chunkSize: 1000,
  chunkOverlap: 200,
  separators: ['\n\n', '\n', ' ', ''],
);

// 對(duì)于普通文本
final textSplitter = CharacterTextSplitter(
  chunkSize: 500,
  chunkOverlap: 50,
);

7. 優(yōu)化檢索質(zhì)量

// 增加檢索的文檔數(shù)量
final retriever = vectorStore.asRetriever(
  searchKwargs: {
    'k': 5,  // 檢索前5個(gè)最相關(guān)的文檔
  },
);

// 使用重排序提高準(zhǔn)確性
// 或添加過(guò)濾條件
final retriever = vectorStore.asRetriever(
  searchKwargs: {
    'k': 10,
    'filter': {'source': 'official_docs'},
  },
);

8. 鏈?zhǔn)秸{(diào)用優(yōu)化

// 使用 Runnable.fromMap 組織復(fù)雜的數(shù)據(jù)流
final complexChain = Runnable.fromMap({
  'processed_input': Runnable.mapInput((input) => processInput(input)),
  'context': retriever,
  'original_query': Runnable.passthrough(),
})
  .pipe(promptTemplate)
  .pipe(model)
  .pipe(outputParser);

?? 學(xué)習(xí)資源

官方資源

示例項(xiàng)目

相關(guān)項(xiàng)目

學(xué)習(xí)路徑建議

  1. 入門(mén)階段

    • 閱讀官方文檔的 "Getting Started" 部分
    • 運(yùn)行簡(jiǎn)單的 LLM 調(diào)用示例
    • 了解基本的提示模板使用
  2. 進(jìn)階階段

    • 學(xué)習(xí) LCEL(鏈?zhǔn)奖磉_(dá)語(yǔ)言)
    • 實(shí)踐 RAG(檢索增強(qiáng)生成)
    • 嘗試構(gòu)建簡(jiǎn)單的問(wèn)答系統(tǒng)
  3. 高級(jí)階段

    • 深入學(xué)習(xí) Agents(代理)
    • 集成多個(gè)工具和數(shù)據(jù)源
    • 優(yōu)化性能和成本
  4. 實(shí)戰(zhàn)項(xiàng)目

    • 構(gòu)建聊天機(jī)器人
    • 開(kāi)發(fā)文檔問(wèn)答系統(tǒng)
    • 創(chuàng)建智能助手應(yīng)用

?? 常見(jiàn)問(wèn)題

Q1: 如何選擇合適的 LLM 提供商?

A: 根據(jù)需求選擇:

  • OpenAI: 最強(qiáng)大,但成本較高
  • Google (Gemini): 性?xún)r(jià)比高,多模態(tài)能力強(qiáng)
  • Anthropic (Claude): 適合復(fù)雜推理和長(zhǎng)文本
  • Ollama: 本地運(yùn)行,隱私性好,免費(fèi)

Q2: RAG 和直接調(diào)用 LLM 有什么區(qū)別?

A:

  • 直接調(diào)用: 依賴(lài)模型的預(yù)訓(xùn)練知識(shí),可能有時(shí)效性問(wèn)題
  • RAG: 從外部知識(shí)庫(kù)檢索相關(guān)信息,然后傳給 LLM,更準(zhǔn)確、更新

Q3: 如何降低 API 調(diào)用成本?

A:

  • 使用較小的模型(如 GPT-3.5 而非 GPT-4)
  • 減少 maxTokens 限制
  • 使用緩存避免重復(fù)調(diào)用
  • 批量處理請(qǐng)求
  • 考慮使用本地模型(Ollama)

Q4: 如何處理中文?

A: 所有主流模型都支持中文,但注意:

  • 中文 token 計(jì)數(shù)通常比英文多
  • 提示模板可以直接使用中文
  • 選擇支持中文的嵌入模型

Q5: Flutter 應(yīng)用中如何使用?

A:

// 在 Flutter 中使用與普通 Dart 項(xiàng)目相同
import 'package:langchain/langchain.dart';
import 'package:langchain_openai/langchain_openai.dart';

class ChatScreen extends StatefulWidget {
  // ... Flutter UI 代碼
  
  Future<void> sendMessage(String message) async {
    final model = ChatOpenAI(apiKey: apiKey);
    final response = await model.invoke(PromptValue.string(message));
    setState(() {
      // 更新 UI
    });
  }
}

?? 版本信息

  • 當(dāng)前版本: 0.8.0+1
  • 發(fā)布時(shí)間: 2024年10月17日
  • 許可證: MIT
  • 發(fā)布者: langchaindart.dev
  • 平臺(tái)支持: Android, iOS, Linux, macOS, Web, Windows

?? 貢獻(xiàn)

LangChain.dart 歡迎貢獻(xiàn)者!


?? 總結(jié)

LangChain.dart 是在 Dart/Flutter 生態(tài)系統(tǒng)中構(gòu)建 LLM 應(yīng)用的強(qiáng)大工具。它提供了:

? 統(tǒng)一的 API 接口
? 豐富的集成選項(xiàng)
? 強(qiáng)大的鏈?zhǔn)秸{(diào)用能力
? 完整的 RAG 支持
? 靈活的 Agent 系統(tǒng)
? 跨平臺(tái)支持

通過(guò)學(xué)習(xí)和實(shí)踐 LangChain.dart,你可以快速構(gòu)建各種基于 LLM 的應(yīng)用,如聊天機(jī)器人、問(wèn)答系統(tǒng)、智能助手等。


最后更新: 2025年12月8日
筆記版本: v1.0

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容