升级打怪

langchain
 
LLM 学习笔记

首先接触的是 Ollama,优点:

  • 容易上手,相关文档和资料比较多;
  • 模型种类丰富;
  • 对 macOS 友好

第一阶段

了解模型种类和划分

1. 按 Transformer 架构划分

类型 核心模块 核心特点 典型任务 代表模型
自编码模型 仅 Encoder 双向注意力,擅长语义理解 文本分类、情感分析、命名实体识别 BERT、RoBERTa、ALBERT
自回归模型 仅 Decoder 单向注意力,自回归生成 文本生成、对话、摘要 GPT 系列、Llama、BLOOM
序列到序列模型 Encoder + Decoder 输入 - 输出序列转换 翻译、生成式摘要、数据转换 T5、BART、GLM

2. 按应用场景划分

  • 通用大模型:跨领域数据训练,适配对话、创作、翻译等多任务,如 GPT - 3.5/4、Claude、Llama 2。

  • 代码专用模型:聚焦编程场景,优化代码生成、补全、调试,如 DeepSeek - Coder、CodeLlama、StarCoder。

  • 行业垂直模型:针对医疗、金融、法律等领域优化,如 Med - Palm、LawGPT。

  • 轻量化 / 蒸馏模型:压缩大模型知识适配低算力场景,如 DistilGPT2、DeepSeek - R1 - Distill。

3. 按能力特性划分

  • 推理增强模型:经思维链微调,擅长数学解题、逻辑分析,如 Qwen3 - 4B - Thinking。

  • 智能体模型:具备工具调用与自主决策,适配复杂任务,如 Tongyi - DeepResearch - 30B - A3B。


第二阶段

深入模型使用

1. ollama 基础操作

# 拉取指定模型
ollama pull <model-name>

# 拉取特定版本的模型
ollama pull llama2:7b
ollama pull mistral:latest

# 查看已下载的模型
ollama list

# 删除指定模型
ollama rm <model-name>

# 复制模型(创建副本)
ollama cp <source-model> <new-model-name>

# 运行默认对话
ollama run <model-name>

# 带系统提示词运行
ollama run <model-name> --system "你是一个有帮助的助手"

# 示例
ollama run llama2
ollama run mistral

# 单次查询(不进入交互模式)
ollama run <model-name> "你的问题是什么?"

# 通过 Modelfile 创建
ollama create <model-name> -f Modelfile

# 查看模型详情
ollama show <model-name>

# 启动 Ollama 服务
ollama serve

# Linux/Mac
pkill ollama

# 指定使用特定 GPU
CUDA_VISIBLE_DEVICES=0 ollama run <model-name>

# 查看运行日志
ollama logs

2. ollama 进阶使用

通过 Modelfile 创建模型

FROM llama2:7b

# 设置参数
PARAMETER temperature 0.7
PARAMETER num_ctx 4096

# 系统提示词
SYSTEM """你是一个专业的技术顾问..."""

# 模板
TEMPLATE """{{ .Prompt }}"""

模型量化技术

量化技术(Quantization)是一种通过降低模型权重精度来减少内存占用和计算资源需求的技术。 在Ollama中,这一核心功能主要由llm/llm.go文件中的Quantize函数实现。 该函数通过调用底层llama.cpp库,将高精度的模型权重转换为低精度表示,同时尽可能保持模型性能。

简单说,通过量化技术个人电脑也可以跑大模型,突破硬件限制🚫。

  1. 如何量化大模型?
  2. 如何使用量化后的大模型?

第1点还在学习中,第2点比较简单。

# 方式1:直接运行预量化版本(最简)
ollama run qwen2.5:7b-instruct-q4_K_M

# 方式2:M1 Pro 深度优化启动(推荐)
OLLAMA_GPU_LAYERS=-1 \
OLLAMA_CONTEXT_SIZE=8192 \
OLLAMA_BATCH_SIZE=512 \
ollama run qwen2.5:7b-instruct-q4_K_M
ed9becfc83f517c79fffc2aa1e4ca330

显示模型信息,其量化等级为“Q4_K_M”

2026-01-06_18-00

配合 langchain.js 调用

2026-01-06_17-49 2026-01-06_17-47

总结

  • LLM
  • Ollama
  • Langchain

以上是这段时间学习到的关于LLM的应用。

Ref

 
LangChain.js 开发日志
pnpm add langchain @langchain/core @langchain/langgraph @langchain/ollama
pnpm add -D @types/node ts-node tsx typescript

目录结构如下:

2025-12-31_18-06

package.json

{
  "name": "langchain-llm",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "index.ts",
  "scripts": {
    "ollama": "tsx src/ollama.ts",
    "prompt-template": "tsx src/prompt-template.ts",
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "packageManager": "[email protected]",
  "dependencies": {
    "@langchain/core": "^1.1.8",
    "@langchain/langgraph": "^1.0.7",
    "@langchain/ollama": "^1.1.0",
    "dotenv": "^17.2.3",
    "langchain": "^1.2.3",
  },
  "devDependencies": {
    "@types/node": "^25.0.3",
    "ts-node": "^10.9.2",
    "tsx": "^4.21.0",
    "typescript": "^5.9.3"
  }
}

src/ollama.ts

import { ChatOllama } from "@langchain/ollama";

async function main() {
  const llm = new ChatOllama({
    model: "qwen2.5:7b", // 或 deepseek-r1:7b
    // model: "deepseek-coder:6.7b", // 或 deepseek-r1:7b
    temperature: 0,
  });

  const res = await llm.invoke("用一句话解释什么是 LangChain");

  console.log(res.content);
}

main().catch(console.error);

src/prompt-template.ts

import { ChatOllama } from "@langchain/ollama";
import { PromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";

const model = new ChatOllama({
  model: "qwen2.5:7b", // 或 deepseek-r1:7b
  temperature: 0,
});

// 创建 Prompt 模板
const promptTemplate = PromptTemplate.fromTemplate(`
你是一个{role},专门帮助用户解决{domain}相关的问题。

用户问题:{question}

请提供详细、专业的回答,包含以下要素:
1. 问题分析
2. 解决方案
3. 代码示例(如果适用)
4. 最佳实践建议

回答:
`);

// 创建输出解析器
const outputParser = new StringOutputParser();

// 构建处理链
const chain = promptTemplate.pipe(model).pipe(outputParser);

async function promptTemplateExample() {
  try {
    const result = await chain.invoke({
      role: "资深前端工程师",
      domain: "React 性能优化",
      question: "如何优化 React 应用的渲染性能?",
    });

    console.log("优化建议:");
    console.log(result);
  } catch (error) {
    console.error("处理失败:", error);
  }
}

promptTemplateExample();

Ref