LangChain系列文章超链接:

《Python+LangChain+大模型实战:使用通用配置加载器的Few‑Shot小样本提示词教程》

《使用Python版LangChain调用外部函数实战:实现智能天气查询》

《Python + LangChain Agent 实战:从单城市查询到多城市天气智能对比》

《Python+LangChain Agent 工具选择逻辑深度解析》

前言

在大模型应用开发中,两个问题最常见:

  1. API 密钥、模型地址散写代码里,改一次要翻遍所有文件,极易泄露、难维护。
  2. 让模型做分类 / 结构化输出,结果长篇大论、格式乱飞,下游程序无法解析。

本文用一套可直接复制运行的工程化代码,一次性解决:

  • 单例模式配置加载器(支持小米大模型,可扩展任意大模型)
  • LangChain Few‑Shot 精准控制输出格式
  • 有无 Few‑Shot 效果直观对比
  • 完整配置文件 + 运行结果演示

1 效果先看:有无 Few‑Shot 差距有多大?

输入:这个电影太好看了!

无 Few‑Shot

不用few-shot输出:太棒了!能遇到一部让自己由衷觉得好看的电影,真的是一件特别开心的事!🎉

我猜你现在一定还沉浸在电影的情绪里,回味着那些精彩的画面和情节吧?

**方便分享一下是哪部电影吗?** 我也很好奇是什么作品能让你这么激动!

如果你愿意的话,我们可以一起聊聊:
*   **最让你心动的角色**是谁?为什么?
*   **哪个情节**让你印象最深刻?(可以不用怕剧透,如果你不介意的话!)
*   是它的**故事、画面、音乐**,还是演员的表演打动了你?

我已经准备好听你的安利啦!

使用 Few‑Shot

使用few-shot的输出:积极

结论:Few‑Shot 能强制模型只输出标签、不废话、格式统一,工程化必备。


2 项目结构

pythonProject/
├── config.properties    # 配置文件(密钥/地址/模型)
├── config_loader.py     # 单例配置加载器
└── langchain_fewshot.py # Few-Shot 主程序

3 第一步:配置文件 config.properties

把敏感信息全部外置,绝不硬编码!

[xiaomi]
api_key = 你的小米大模型API Key
api_base_url = https://api.example.com/v1
model = 你的模型名称
temperature = 0.1
max_tokens = 1024

4 第二步:配置加载器 config_loader.py

单例模式 + 统一读取 + 类型自动转换 + 异常提示,所有大模型项目通用。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import configparser
import os
from typing import Dict, Any

class ConfigLoader:
    _instance = None
    _config = None

    def __new__(cls, config_path: str = "config.properties"):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._load_config(config_path)
        return cls._instance

    def _load_config(self, config_path: str):
        if not os.path.exists(config_path):
            raise FileNotFoundError(
                f"配置文件不存在: {os.path.abspath(config_path)}\n"
                "请在项目根目录创建 config.properties"
            )
        self._config = configparser.ConfigParser()
        self._config.read(config_path, encoding="utf-8")

    def get(self, section: str, key: str) -> str:
        try:
            return self._config[section][key].strip()
        except KeyError as e:
            raise ValueError(f"配置缺失: [{section}] {key}") from e

    def get_xiaomi_config(self) -> Dict[str, Any]:
        section = "xiaomi"
        config = {
            "api_key": self.get(section, "api_key"),
            "api_base_url": self.get(section, "api_base_url"),
            "model": self.get(section, "model"),
        }
        # 可选配置带默认值
        try:
            config["temperature"] = float(self.get(section, "temperature"))
        except:
            config["temperature"] = 0.7
        try:
            config["max_tokens"] = int(self.get(section, "max_tokens"))
        except:
            config["max_tokens"] = 1024
        return config

核心亮点

  • 全局只加载一次配置,高效安全
  • 外置配置,避免密钥泄露
  •  可轻松扩展 OpenAI、阿里、百度等模型

5 第三步:LangChain Few‑Shot 情感分类

langchain_fewshot.py 完整可运行代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import openai
from config_loader import ConfigLoader
from langchain_openai import ChatOpenAI
from langchain_core.prompts import PromptTemplate, FewShotPromptTemplate

def few_shot_input(input_text):
    # 1. 小样本示例(覆盖积极/消极/中性)
    examples = [
        {"text": "今天心情特别好", "label": "积极"},
        {"text": "上班迟到还下雨,好烦", "label": "消极"},
        {"text": "天气一般,没什么感觉", "label": "中性"},
    ]
    # 2. 例子格式
    example_prompt = PromptTemplate(
        input_variables=["text", "label"],
        template="文本:{text}\n情感:{label}\n"
    )
    # 3. 组装 FewShot 模板
    few_shot_prompt = FewShotPromptTemplate(
        examples=examples,
        example_prompt=example_prompt,
        prefix="请判断以下文本的情感,只能输出:积极/消极/中性",
        suffix="文本:{input}\n情感:",
        input_variables=["input"],
        example_separator="\n"
    )
    return few_shot_prompt.format(input=input_text)

if __name__ == '__main__':
    # 加载配置
    config = ConfigLoader()
    xiaomi_cfg = config.get_xiaomi_config()

    # 初始化模型
    client = ChatOpenAI(
        api_key=xiaomi_cfg["api_key"],
        base_url=xiaomi_cfg["api_base_url"],
        model=xiaomi_cfg["model"]
    )

    input_text = "这个电影太好看了!"

    # 无 Few-Shot
    print("不用few-shot输出:" + client.invoke(input_text).content)

    # 使用 Few-Shot
    prompt = few_shot_input(input_text)
    print("-" * 50)
    print("使用few-shot的输出:" + client.invoke(prompt).content)

6 Few‑Shot 核心原理

  1. examples:给模型看的样例,决定输出风格
  2. example_prompt:统一样例格式
  3. prefix:任务指令(必须严格约束输出)
  4. suffix:待预测输入占位
  5. FewShotPromptTemplate:自动拼接所有内容,形成最终提示

用少量示例教会模型按格式输出,不用微调、零训练成本。


7 运行结果展示

不用few-shot输出:太棒了!能遇到一部让自己由衷觉得好看的电影,真的是一件特别开心的事!🎉

我猜你现在一定还沉浸在电影的情绪里,回味着那些精彩的画面和情节吧?

**方便分享一下是哪部电影吗?** 我也很好奇是什么作品能让你这么激动!

如果你愿意的话,我们可以一起聊聊:
*   **最让你心动的角色**是谁?为什么?
*   **哪个情节**让你印象最深刻?(可以不用怕剧透,如果你不介意的话!)
*   是它的**故事、画面、音乐**,还是演员的表演打动了你?

我已经准备好听你的安利啦!
-------------------------------
使用few-shot的输出:积极

8 适用场景

  • 情感分析、意图识别、文本分类
  • 实体抽取、结构化输出(JSON / 标签)
  • 固定格式回复、表单提取
  • 任何需要稳定、可控、简洁输出的场景
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐