当前位置: 首页 > news >正文

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

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)
http://www.rkmt.cn/news/87363.html

相关文章:

  • Qwen-Image-Lightning:如何用4-8步实现实时文生图创作
  • 2025年中国五大电子汽车衡厂商推荐:汽车衡正规厂商哪家性价 - mypinpai
  • 大模型训练优化:5个内存效率提升技巧与实战配置指南
  • 2025年ELBE联轴器品牌推荐排名,看看哪家价格实惠 - 工业推荐榜
  • 人工智能作业
  • 精通 oil.nvim 排序配置:打造个性化文件管理体验
  • 探索你的“饮食碳足迹”:一款直观的可持续饮食计算工具
  • Spring管理MyBatis Mapper接口的原理详解
  • Trae Agent离线模式终极指南:无网络环境下的完整解决方案
  • 终极指南:用ReplayBook轻松搞定英雄联盟回放管理
  • Unity塔防游戏开发实战:构建智能防御系统的完整指南
  • 微信7.0.6提示升级问题解决方法
  • 回收台达PLC,伺服,变频器等
  • 大厂RAG架构师都藏着!9个核心步骤,彻底搞懂向量检索系统的设计精髓
  • 漏洞赏金真的容易吗?揭秘技术挑战与成功之路
  • 现代C++与Qt飞行仪表库:让飞行模拟开发触手可及
  • 5分钟学会:这款Windows酷安UWP客户端为何成为效率神器?
  • Duplicacy缓存机制终极指南:如何实现5倍备份速度提升
  • 2025年中国工业隔音设备五大品牌推荐:办公室静音房、隔音房 - myqiye
  • 上海舒舜精密轴承有限公司的实力如何?客户对产品的满意度怎样 - 工业品牌热点
  • 2025 GEO优化避坑5条:警惕付费收录、虚假榜单
  • RookieAI_yolov8:5分钟快速掌握游戏AI自瞄核心技术
  • TikTok直播录制终极解决方案:一键自动保存精彩瞬间
  • Python实战:Sholl分析在神经科学研究中的完整应用指南
  • 廊坊市企业营销策划哪家更专业
  • 2025年深圳遗嘱咨询律师电话汇总: 深圳知名律所联系方式及遗嘱服务专业指引 - 品牌推荐
  • 2025年热门的钢板预处理线厂家推荐及采购参考 - 品牌宣传支持者
  • AI助力SEO中的关键词优化新攻略与实践案例分享
  • 2025年有实力的耐高温材料喷涂四氟/不沾涂层喷涂四氟优质厂家推荐榜单 - 品牌宣传支持者
  • 2025年12月UEM统一端点管理推荐:企业级UEM平台权威评测与排行榜单指南 - 品牌推荐