部署本地api:https://blog.csdn.net/qq_35809258/article/details/145481113
实现持续对话:https://blog.csdn.net/qq_35809258/article/details/145490986

通过以上两个链接基本对话环境齐备,直接进行下一步
上传的文件类型可能有多种,需要安装所用到的python库

pip install python-docx  # Word文档处理
pip install pdfplumber   # PDF解析
pip install opencv-python # 图像处理

代码:

import os
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import torch

# 支持的文件类型白名单
ALLOWED_EXTENSIONS = {'.txt', '.py', '.md', '.csv'}


def handle_file_upload(file_path: str) -> str:
    """处理文件上传并返回内容"""
    try:
        # 验证文件类型
        _, ext = os.path.splitext(file_path)
        if ext.lower() not in ALLOWED_EXTENSIONS:
            return f"错误:不支持的文件类型 {ext}"

        # 读取文件内容
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()

        # 限制文件大小(例如最大 1MB)
        if len(content) > 1_000_000:
            return "错误:文件大小超过 1MB 限制"

        return content

    except FileNotFoundError:
        return "错误:文件不存在"
    except UnicodeDecodeError:
        return "错误:文件编码格式不支持"


def chat_session(tokenizer,model):
    """管理对话会话"""
    conversation_history = []
    attached_files = {}  # 存储附件内容 {文件名: 内容}

    while True:
        user_input = input("\nYou: ").strip()

        # 处理特殊命令
        if user_input.lower() == "stop":
            break
        elif user_input.lower().startswith("upload "):
            file_path = user_input.split(" ", 1)[1]
            file_content = handle_file_upload(file_path)

            if file_content.startswith("错误"):
                print(file_content)
            else:
                filename = os.path.basename(file_path)
                attached_files[filename] = file_content
                print(f"成功上传文件: {filename} ({len(file_content)} 字符)")
            continue

        # 将附件内容合并到提示词
        full_prompt = "\n".join(conversation_history)
        if attached_files:
            file_context = "\n".join(
                [f"【文件 {name} 内容】\n{content[:1000]}..." for name, content in attached_files.items()]
            )
            full_prompt += f"\n{file_context}\n用户提问: {user_input}\n助理回答:"
        else:
            full_prompt += f"\n用户提问: {user_input}\n助理回答:"

        # 编码并生成回复
        inputs = tokenizer(full_prompt, return_tensors="pt").to(model.device)
        outputs = model.generate(
            inputs.input_ids,
            attention_mask=inputs.attention_mask,
            max_new_tokens=300,
            temperature=0.7,
            pad_token_id=tokenizer.pad_token_id
        )

        response = tokenizer.decode(outputs[0][inputs.input_ids.shape[-1]:], skip_special_tokens=True)
        response = response.split("。")[0] + "。"  # 截断第一个完整句子

        # 更新对话历史
        conversation_history.append(f"用户: {user_input}\n助理: {response}")
        print(f"\nAssistant: {response}")


def main():
    # 初始化模型和分词器
    quantization_config = BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_use_double_quant=True,
        bnb_4bit_quant_type="nf4",
        bnb_4bit_compute_dtype=torch.float16
    )

    model = AutoModelForCausalLM.from_pretrained(
        "./deepseek-coder-7b-instruct",
        quantization_config=quantization_config,
        device_map="auto"
    )

    tokenizer = AutoTokenizer.from_pretrained("./deepseek-coder-7b-instruct")
    tokenizer.pad_token_id = tokenizer.eos_token_id

    # 主循环
    while True:
        cmd = input("\n输入 'start' 开始对话,'exit' 退出: ").lower()

        if cmd == "exit":
            break
        elif cmd == "start":
            print("\n==== 新对话开始 ====")
            print("可用命令:")
            print("  - upload <文件路径> : 上传文本文件")
            print("  - stop              : 结束当前对话")
            chat_session(tokenizer,model)


if __name__ == "__main__":
    main()

随便建个txt,输入一段内容,比如:
在这里插入图片描述

运行结果如下:

输入 'start' 开始对话,'exit' 退出: start

==== 新对话开始 ====
可用命令:
  - upload <文件路径> : 上传文本文件
  - stop              : 结束当前对话

You: upload example.txt
成功上传文件: example.txt (20 字符)

You: 请解释这个代码文件的功能

Assistant:  这个代码文件是一个Python脚本,它打印出"hello world"。

You: stop

输入 'start' 开始对话,'exit' 退出: exit
Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐