news 2026/6/14 12:03:09

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

作者头像

张小明

前端开发工程师

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/6/12 23:04:03

3大痛点解析:Flink监控体系为何总是失效?终极解决方案来了!

你是否经历过Flink作业突然卡死却找不到原因?背压监控数据一片空白?检查点频繁失败却无从下手?这些困扰开发者的监控难题,本文将为你一一解决!🚀 【免费下载链接】flink 项目地址: https://gitcode.com/…

作者头像 李华
网站建设 2026/6/10 15:33:12

Latest:macOS应用更新的终极完整指南

Latest:macOS应用更新的终极完整指南 【免费下载链接】Latest A small utility app for macOS that makes sure you know about all the latest updates to the apps you use. 项目地址: https://gitcode.com/gh_mirrors/la/Latest Latest 是一款专为 macOS …

作者头像 李华
网站建设 2026/6/12 22:46:24

多语言代码质量检测神器:fuck-u-code的国际化实践解析

在全球化协作日益普及的软件开发环境中,代码质量工具的国际化支持已成为提升开发效率的关键要素。GitHub精选项目"fuck-u-code"作为一款基于Go语言构建的代码质量检测器,不仅能够精准评估代码的"屎山等级",更通过完善的国…

作者头像 李华
网站建设 2026/6/10 16:00:28

终极伺服系统设计指南:5步快速掌握电机控制核心技术

终极伺服系统设计指南:5步快速掌握电机控制核心技术 【免费下载链接】伺服系统设计指导PDF资源说明分享 《伺服系统设计指导》是一本专门针对电机运动控制领域的参考书籍。本书深入浅出地介绍了伺服系统的设计精髓,涵盖了从基础理论到实际应用的广泛知识…

作者头像 李华
网站建设 2026/6/13 2:36:41

5步快速上手GPT-2 XL:从零开始的AI写作实战指南

5步快速上手GPT-2 XL:从零开始的AI写作实战指南 【免费下载链接】gpt2-xl 项目地址: https://ai.gitcode.com/hf_mirrors/ai-gitcode/gpt2-xl 还在为复杂的AI模型部署而头疼吗?🤔 想要快速掌握强大的文本生成能力却不知从何入手&…

作者头像 李华
网站建设 2026/6/14 10:53:10

windows不会自更新时应怎样处理?

当Windows自动更新功能失效时,这是一个需要认真对待的问题。系统无法获取安全补丁,会带来严重的安全风险。请按照以下从易到难、逐步排查的流程来解决问题。 第一步:基础检查与快速修复检查网络与时间 网络:确保网络连接正常&…

作者头像 李华