news 2026/5/1 6:09:43

Qwen3-4B Instruct-2507实战教程:用LangChain封装Qwen3构建结构化问答Agent

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Qwen3-4B Instruct-2507实战教程:用LangChain封装Qwen3构建结构化问答Agent

Qwen3-4B Instruct-2507实战教程:用LangChain封装Qwen3构建结构化问答Agent

1. 项目概述

Qwen3-4B Instruct-2507是阿里通义千问系列中的一款专注于纯文本处理的大语言模型。相比全功能版本,它移除了视觉相关模块,专注于提升文本处理效率和响应速度。本教程将指导你如何使用LangChain框架封装这个模型,构建一个结构化的问答Agent系统。

这个项目的核心优势在于:

  • 纯文本优化:专注文本任务,推理速度更快
  • 流式输出:支持实时逐字显示生成内容
  • 高效部署:自动适配GPU资源,开箱即用
  • 灵活调节:可调整生成长度和创造性参数

2. 环境准备与安装

2.1 基础环境要求

在开始前,请确保你的系统满足以下要求:

  • Python 3.8或更高版本
  • CUDA 11.7+(如需GPU加速)
  • 至少16GB内存(32GB推荐)
  • 支持NVIDIA显卡(如使用GPU)

2.2 安装依赖包

使用以下命令安装必要的Python包:

pip install langchain transformers torch streamlit

对于GPU加速,建议安装对应版本的PyTorch:

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu117

3. 模型加载与基础封装

3.1 加载Qwen3-4B模型

首先,我们创建一个Python脚本加载基础模型:

from transformers import AutoModelForCausalLM, AutoTokenizer model_name = "Qwen/Qwen3-4B-Instruct-2507" tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained( model_name, device_map="auto", torch_dtype="auto", trust_remote_code=True )

3.2 创建基础问答函数

封装一个简单的问答函数:

def qwen_qa(question, chat_history=None, max_length=512, temperature=0.7): if chat_history is None: chat_history = [] inputs = tokenizer.apply_chat_template( chat_history + [{"role": "user", "content": question}], add_generation_prompt=True, return_tensors="pt" ).to(model.device) outputs = model.generate( inputs, max_new_tokens=max_length, temperature=temperature, do_sample=temperature > 0, pad_token_id=tokenizer.eos_token_id ) response = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True) return response

4. 使用LangChain构建结构化Agent

4.1 创建LangChain接口

我们将使用LangChain的LLM接口封装Qwen3:

from langchain.llms.base import LLM from typing import Optional, List, Dict, Any class Qwen3LangChain(LLM): @property def _llm_type(self) -> str: return "qwen3-4b" def _call(self, prompt: str, stop: Optional[List[str]] = None, **kwargs) -> str: return qwen_qa(prompt, **kwargs) @property def _identifying_params(self) -> Dict[str, Any]: return {"model_name": "Qwen3-4B-Instruct-2507"}

4.2 构建问答链

创建一个简单的问答链:

from langchain.chains import LLMChain from langchain.prompts import PromptTemplate template = """你是一个专业的AI助手。请回答以下问题: 问题: {question} 回答:""" prompt = PromptTemplate(template=template, input_variables=["question"]) llm = Qwen3LangChain() qa_chain = LLMChain(llm=llm, prompt=prompt)

5. 高级功能实现

5.1 多轮对话记忆

实现对话历史管理:

from langchain.memory import ConversationBufferMemory memory = ConversationBufferMemory() conversation = LLMChain( llm=llm, prompt=prompt, memory=memory, verbose=True ) # 使用示例 response = conversation({"question": "介绍一下Python的特点"}) print(response["text"]) response = conversation({"question": "能详细说说其中的动态类型吗"}) print(response["text"]) # 会记住之前的对话

5.2 结构化输出解析

使用LangChain的输出解析器:

from langchain.output_parsers import StructuredOutputParser, ResponseSchema from langchain.prompts import ChatPromptTemplate response_schemas = [ ResponseSchema(name="answer", description="问题的直接回答"), ResponseSchema(name="explanation", description="详细的解释"), ResponseSchema(name="sources", description="参考来源", type="list") ] output_parser = StructuredOutputParser.from_response_schemas(response_schemas) format_instructions = output_parser.get_format_instructions() prompt = ChatPromptTemplate.from_template( """回答以下问题,并按照指定格式返回结果。 问题: {question} {format_instructions}""" ) chain = LLMChain(llm=llm, prompt=prompt) output = chain.run(question="Python中的装饰器是什么?", format_instructions=format_instructions) parsed = output_parser.parse(output)

6. 部署为Web服务

6.1 使用Streamlit创建界面

创建一个简单的Web界面:

import streamlit as st st.title("Qwen3-4B问答系统") st.sidebar.header("参数设置") max_length = st.sidebar.slider("最大长度", 128, 2048, 512) temperature = st.sidebar.slider("创造性", 0.0, 1.5, 0.7) if "messages" not in st.session_state: st.session_state.messages = [] for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) if prompt := st.chat_input("输入你的问题"): st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt) with st.chat_message("assistant"): response = qwen_qa( prompt, chat_history=st.session_state.messages[:-1], max_length=max_length, temperature=temperature ) st.markdown(response) st.session_state.messages.append({"role": "assistant", "content": response})

6.2 运行服务

使用以下命令启动服务:

streamlit run qwen_app.py

7. 总结与进阶建议

通过本教程,我们完成了从基础模型加载到完整问答系统部署的全过程。以下是几个可以进一步优化的方向:

  1. 性能优化:实现批处理推理,提高吞吐量
  2. 知识增强:结合向量数据库实现外部知识检索
  3. 领域适配:使用LoRA等技术进行领域微调
  4. 安全增强:添加内容过滤和审核机制
  5. 多模态扩展:结合其他模型实现图文混合问答

这个基于Qwen3-4B和LangChain的问答系统可以作为各种企业应用的基础,如智能客服、知识库问答、编程助手等场景。


获取更多AI镜像

想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/1 6:09:31

GLM-4.7-Flash部署案例:高校AI教学平台——学生作业智能批改

GLM-4.7-Flash部署案例:高校AI教学平台——学生作业智能批改 1. 项目背景与需求 1.1 高校教学痛点 高校教师每学期需要批改大量学生作业,传统人工批改方式存在以下问题: 批改工作量大,占用教师大量时间主观评价标准难以统一反…

作者头像 李华
网站建设 2026/4/30 8:00:19

AI视觉识别技术在游戏场景中的研究与应用

AI视觉识别技术在游戏场景中的研究与应用 【免费下载链接】AI-Aimbot Worlds Best AI Aimbot - CS2, Valorant, Fortnite, APEX, every game 项目地址: https://gitcode.com/gh_mirrors/ai/AI-Aimbot 一、技术原理:基于深度学习的游戏视觉分析框架 AI视觉识…

作者头像 李华
网站建设 2026/4/30 16:00:51

Qwen3-Reranker-8B效果展示:MTEB多语言重排序榜首模型实测案例

Qwen3-Reranker-8B效果展示:MTEB多语言重排序榜首模型实测案例 1. 开篇:认识这款多语言重排序冠军模型 如果你正在寻找一款能在多语言文本排序任务中表现出色的模型,Qwen3-Reranker-8B绝对值得关注。这款模型在MTEB多语言排行榜上以70.58的…

作者头像 李华