news 2026/5/7 6:51:35

搭建本地支持联网推理助手(附源码)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
搭建本地支持联网推理助手(附源码)

20251212_搭建本地支持联网推理助手

一、问题

搭建本地助手,提升工作效率。

二、代码

importjsonimportosimportwarningsimportgradioasgrimportrequests AUTHORIZATION="Bearer XXXXXXXXXXX"PROXIES={'https':'http://XXXXXXXXXXX8080',# 替换为自己的域账号和密码'http':'http://XXXXXXXom:8080',}os.environ["no_proxy"]="localhost,127.0.0.1,::1"os.environ['GRADIO_ANALYTICS_ENABLED']='False'warnings.filterwarnings("ignore",category=requests.packages.urllib3.exceptions.InsecureRequestWarning)defstream_response_v3(question,history):messages=[]fornum,hisinenumerate(history):ifnum>=3:breakmessages.append({"role":"user","content":history[0]['content']})messages.append({"role":"assistant","content":history[1]['content']})passmessages.append({"role":"user","content":question})data={"model":"ep-20250718205753-s4hns","messages":messages,"stream":True}try:response=requests.post("https://ark.cn-beijing.volces.com/api/v3/chat/completions",headers={"Authorization":AUTHORIZATION,"Content-Type":"application/json"},proxies=PROXIES,verify=False,json=data,stream=True,timeout=30)response.raise_for_status()full_response=""forlineinresponse.iter_lines():ifline:decoded_line=line.decode('utf-8').lstrip('data: ').strip()ifdecoded_line=="[DONE]":breaktry:chunk=json.loads(decoded_line)ifchunk.get('choices'):delta=chunk['choices'][0].get('delta',{})ifdelta.get('content'):content=delta['content']full_response+=contentyieldfull_responseexceptjson.JSONDecodeError:continueexceptrequests.exceptions.RequestExceptionase:yieldf"请求发生错误:{str(e)}"exceptExceptionase:yieldf"处理响应时发生错误:{str(e)}"defchat_with_ark(message,history):""" 支持多轮对话的ARK聊天函数 Args: message: 用户当前输入的消息 history: 对话历史记录,格式为: [{'role': 'user/assistant', 'content': '消息内容'}, ...] Yields: 逐步生成的回复内容 """messages=[]forturninhistory:messages.append({"role":turn["role"],"content":[{"type":"input_text","text":turn["content"]}]})messages.append({"role":"user","content":[{"type":"input_text","text":message}]})payload={"model":"ep-20251210140512-99ld2","stream":True,"tools":[{"type":"web_search","max_keyword":3}],"input":messages# 使用包含历史的消息列表}response=requests.post("https://ark.cn-beijing.volces.com/api/v3/responses",headers={"Authorization":AUTHORIZATION,"Content-Type":"application/json"},json=payload,stream=True,verify=False,proxies=PROXIES)partial_response=""forlineinresponse.iter_lines():ifline:decoded_line=line.decode('utf-8')ifdecoded_line.startswith('data:'):try:data=json.loads(decoded_line[5:])ifdata.get("type")=="response.output_text.delta":delta=data.get("delta","")partial_response+=deltayieldpartial_responseexceptjson.JSONDecodeError:continuewithgr.Blocks()asdemo:withgr.Tabs():withgr.Tab("1. deepseek-v3-671b"):chatbot1=gr.Chatbot(height=580,type="messages")chat_interface1=gr.ChatInterface(fn=stream_response_v3,cache_examples=False,chatbot=chatbot1,fill_height=True)chat_interface1.scale=2examples1=gr.Examples(examples=["请帮我写python代码,功能要求如下:","请帮我修改python代码,功能要求如下:","下述错误是什么原因?怎么解决?","我的代码报如上,我的代码报错如下。错误原因是什么?怎么解决?",],inputs=chat_interface1.textbox,run_on_click=False,cache_examples=False,)withgr.Tab("2. deepseek-v3-671b(web search)"):chatbot2=gr.Chatbot(height=580,type="messages")chat_interface2=gr.ChatInterface(fn=chat_with_ark,cache_examples=False,chatbot=chatbot2,fill_height=True)chat_interface2.scale=2examples2=gr.Examples(examples=["请帮我写python代码,功能要求如下:","请帮我修改python代码,功能要求如下:","下述错误是什么原因?怎么解决?","我的代码报如上,我的代码报错如下。错误原因是什么?怎么解决?",],inputs=chat_interface2.textbox,run_on_click=False,cache_examples=False,)port=30005importpsutilforprocinpsutil.process_iter(['pid','name']):try:forconninproc.connections():ifconn.laddr.port==port:print(f"Killing process{proc.pid}({proc.name()})")proc.kill()breakexceptExceptionase:print(e)passdemo.queue().launch(server_name="127.0.0.1",server_port=port,share=False,show_error=True)
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/26 21:43:46

大连格恩朗金属管浮子流量计:精准破局,赋能工业流体计量

自2019年扎根流量测量领域,大连格恩朗始终坚守“技术筑基、精准至上”的初心,聚焦工业流体计量痛点,深耕金属管浮子流量计的研发与智造。凭借对精度的极致追求和对工况的深度适配,品牌打造的金属管浮子流量计,已成为化…

作者头像 李华
网站建设 2026/5/3 7:37:42

如何做Dify二次开发?

很多Dify开源版用户在使用的时候,总是在尝试做二次开发来解决开源权限管控等不足的问题,但往往不知道如何下手。本文将以实际二次开发项目dify-plus为例,带你深入体验Dify 二次开发过程,掌握从环境搭建到生产部署的全流程二次开发…

作者头像 李华
网站建设 2026/5/3 15:17:06

剧想天开,造梦未来|一场关于“儿童剧人物造型”的想象力实验

儿童戏剧,是投射在少年儿童心灵舞台上的第一束光。人物造型,作为这束光中最具象、最绚烂的色彩,不仅定义角色的灵魂,更深刻影响着儿童认知世界的方式与审美情感的塑造。党和国家将美育置于培育时代新人的战略高度,而儿…

作者头像 李华
网站建设 2026/5/6 4:16:19

Vue Konva实战指南:从零构建交互式画布应用

Vue Konva实战指南:从零构建交互式画布应用 【免费下载链接】vue-konva Vue & Canvas - JavaScript library for drawing complex canvas graphics using Vue. 项目地址: https://gitcode.com/gh_mirrors/vu/vue-konva 你是否曾经想要在Vue应用中添加精美…

作者头像 李华
网站建设 2026/5/6 13:09:23

房产中介系统APP六大排名

在房产中介行业数字化转型的浪潮中,一款优质的房产中介房源管理系统成为提升运营效率、规范业务流程的核心支撑。无论是个体经纪人、夫妻小店,还是连锁中介机构,都需要适配自身需求的房产中介房源管理软件来实现房客源的精准管控、业务流程的…

作者头像 李华
网站建设 2026/5/5 21:31:24

16、Linux常用命令详解

Linux常用命令详解 1. ftpd命令 1.1 ftp子命令 命令 功能 site [command] 在远程机器上运行特定站点命令 size filename 返回远程机器上指定文件的大小 status 显示当前ftp状态 struct [struct-name] 设置文件传输结构,默认使用流结构 sunique 切换远程机器…

作者头像 李华