大模型多轮对话技巧
temperature 如果是0每次返回的是增量代码temperature 如果是0.7每次返回的是全部代码没有多轮对话的效果。import urllib import json import requests import base64 from http.client import HTTPException from typing import List, Dict, Any, Optional from pathlib import Path import os from img_val.val_img_xiti import test_single_image from tools.ggb_html_tool import generate_multi_ggb_html _MODEL_ID None BASE_URL http://192.168.100.203:17890 # 请根据实际服务地址修改 def get_model_id() - str: 获取 vLLM 服务的模型 ID并缓存 global _MODEL_ID if _MODEL_ID is not None: return _MODEL_ID try: resp urllib.request.urlopen(f{BASE_URL}/v1/models, timeout30) data json.loads(resp.read().decode(utf-8)) _MODEL_ID data[data][0][id] print(f获取到模型 ID: {_MODEL_ID}) return _MODEL_ID except Exception as e: print(f获取模型 ID 失败: {e}) raise HTTPException(status_code500, detail无法获取 vLLM 模型 ID) def chat_with_text(text: str, system_prompt: str , temperature: float 0.7, history: Optional[List[Dict[str, str]]] None, stream: bool True) - Dict[str, Any]: model_id get_model_id() messages [] if system_prompt: messages.append({role: system, content: system_prompt}) if history: messages.extend(history) # 添加当前用户消息 messages.append({role: user, content: text}) payload {model: model_id, messages: messages, temperature: temperature, max_tokens: 4096, stream: stream, } full_response try: response requests.post(f{BASE_URL}/v1/chat/completions, jsonpayload, streamstream, timeout300) if response.status_code ! 200: print(f❌ Error: {response.status_code}) print(response.text) return {response: , history: history or []} if stream: # 流式输出 for line in response.iter_lines(): if line: line line.decode(utf-8) if line.startswith(data: ): data line[6:] if data [DONE]: break try: chunk json.loads(data) choices chunk.get(choices, []) if choices: delta choices[0].get(delta, {}) content_delta delta.get(content, ) if content_delta: print(content_delta, end, flushTrue) full_response content_delta except json.JSONDecodeError: continue print() # 换行 else: # 非流式输出 data response.json() full_response data.get(choices, [{}])[0].get(message, {}).get(content, ) print(full_response) # 更新历史记录 updated_history (history or []).copy() updated_history.append({role: user, content: text}) updated_history.append({role: assistant, content: full_response}) return {response: full_response, history: updated_history} except requests.exceptions.Timeout: print(❌ Request timeout) return {response: , history: history or []} except Exception as e: print(f❌ Error: {e}) return {response: , history: history or []} class ChatSession: 对话会话类方便管理多轮对话 def __init__(self, system_prompt: str , temperature: float 0.7): self.system_prompt system_prompt self.temperature temperature self.history: List[Dict[str, str]] [] self.responses: List[str] [] def ask(self, text: str, stream: bool True) - str: result chat_with_text(texttext, system_promptself.system_prompt, temperatureself.temperature, historyself.history, streamstream) self.history result[history] response result[response] self.responses.append(response) return response def clear_history(self): 清空对话历史 self.history [] self.responses [] def get_full_conversation(self) - str: 获取完整的对话文本 conversation [] for msg in self.history: role 用户 if msg[role] user else 助手 conversation.append(f{role}: {msg[content]}) return \n\n.join(conversation) if __name__ __main__: # 方式1直接使用 chat_with_text 函数手动管理历史 if 0: print(方式1手动管理历史) history [] questions [画一个圆 生成ggb代码不要注释, 圆内画一个内接三角形ABC, 过点C 画AB的垂线, 过点A 画角A的角平分线,画一个三角形] for i, q in enumerate(questions): print(f\n--- 第 {i 1} 轮对话 ---) print(f用户: {q}) result chat_with_text(textq, system_prompt你是一个数学几何助手请根据要求生成GeoGebra代码。, historyhistory,temperature0.0, streamTrue) history result[history] print(fresponse: {result[response]}) # 只打印前100字符 if 1: # 方式2使用 ChatSession 类更方便 print(方式2使用 ChatSession 类) session ChatSession(system_prompt你是一个数学几何助手请根据要求生成GeoGebra代码。, temperature0.7) questions [画一个圆 生成ggb代码不要注释, 圆内画一个内接三角形ABC, 过点C 画AB的垂线, 过点A 画角A的角平分线,画一个四边形] for i, q in enumerate(questions): print(f--- 第 {i 1} 轮对话 ---) print(fask: {q}) response session.ask(q, streamTrue) print(fresponse: {response}) # 打印完整对话历史 print(\n * 50) print(完整对话历史:) print( * 50) print(session.get_full_conversation())

相关新闻

解锁魂系游戏模组新境界:ModEngine2智能运行时注入库完全指南

解锁魂系游戏模组新境界:ModEngine2智能运行时注入库完全指南

解锁魂系游戏模组新境界:ModEngine2智能运行时注入库完全指南 【免费下载链接】ModEngine2 Runtime injection library for modding Souls games. WIP 项目地址: https://gitcode.com/gh_mirrors/mo/ModEngine2 探索《艾尔登法环》和《黑暗之魂3》模组管理的…

2026/11/12 4:21:52 阅读更多 →
TPS65982BB芯片解析:集成USB Billboard、数据MUX与5V负载开关的设计指南

TPS65982BB芯片解析:集成USB Billboard、数据MUX与5V负载开关的设计指南

1. 项目概述与核心价值如果你最近在折腾USB Type-C扩展坞、充电器或者任何支持USB Power Delivery(PD)协议的设备,大概率会碰到一个需求:当你的设备(比如一个支持DisplayPort Alt Mode的扩展坞)连接到电脑时…

2026/11/10 18:58:27 阅读更多 →
RISC-V IOMMU 硬件设计学习计划|第 1 天:IOMMU 在 RISC-V SoC 中解决什么问题

RISC-V IOMMU 硬件设计学习计划|第 1 天:IOMMU 在 RISC-V SoC 中解决什么问题

RISC-V IOMMU 硬件设计学习计划|第 1 天:IOMMU 在 RISC-V SoC 中解决什么问题> 计划日期:2026-07-27。本系列基于官方 RISC-V IOMMU Architecture Specification 与官方 riscv-iommu/iommu_ref_model C 参考模型整理。本文自包含阅读&…

2026/11/10 5:32:44 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年,我大部分时间都在跟浏览器标签页打交道,直到第一次把桌面应用跑起来,才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词,最开始是在某段时间频繁出现在同事的讨论里,一个用HTML…

2026/11/12 5:00:00 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介:亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档,主要面向智能锁安装人员、终端用户及售后维护者,帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件,大小4.37MB,内容结构清晰&#xff…

2026/11/12 5:13:20 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统,整车要求空载跑到8m/s,电机转速已经拉到额定点,驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令,转速纹丝不动,三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/11/12 5:13:20 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年,用它写过嵌入式驱动、做过游戏服务端,也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词,我其实挺感慨的——这门语言的难点从来不是语法多,而是知识点之间的耦合太深…

2026/11/12 18:22:26 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介:亚太天能T109滑盖智能锁产品说明书以PDF格式发布,适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开,先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能,再给出完整安装步骤&…

2026/11/12 18:22:25 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历:翻开源码注释、论文摘要或者一份专业报告,每个字都认识,连在一起却像天书。想找人聊聊,身边要么没人懂,要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型,几秒钟之后&a…

2026/11/12 5:13:20 阅读更多 →

日新闻

周新闻

月新闻