chat2db调用ollama实现数据库的操作。

只试了mysql的调用。

其它的我也不用,本来想充钱算了。最后一看单位是美刀。就放弃了这分心。于是折腾了一下。

本地运行chat2db 及chat2db ui

https://gitee.com/ooooinfo/Chat2DB
clone 后运行起来 chat2db的java端,我现在搞不清这一个项目是有没有链接到数据库里去。
在idea项目中运行
在这里插入图片描述
在这里插入图片描述

前端在:chat2db-client中。我的环境是 node 20 ,yarn , 注意可能需要 yarn add electron
直接运行:yarn start
在这里插入图片描述

安装ollama 以及模型 qwen2.5 这里我也不懂。不知装那一个好。

https://ollama.com/
在这里插入图片描述
在powershell下运行:ollama run qwen2.5 或 ollama pull qwen2.5
最终你要保证ollama启运。

仿一下openai的接口 调用ollama 提供给chat2db:

chat2db中这样设置,所以需要我自己写一个app.py 去做一下代理请求ollama,不是我不想写自定义,主要是总不成功。不如直接仿openai .
在这里插入图片描述

app.py的部分代码。

我用的conda 创建的3.9的环境:
requirements.txt

fastapi==0.104.1
uvicorn==0.24.0
httpx==0.25.1
tenacity==8.2.3
backoff

相关的app.py的代码:

from fastapi import FastAPI, HTTPException, Request, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, StreamingResponse
import httpx
import uvicorn
import traceback
import sys
import time
import json
import asyncio
import re
import backoff  # 确保已安装 backoff 库app = FastAPI(title="Ollama API Adapter",description="An adapter for Ollama API that mimics OpenAI API format",version="1.0.0"
)app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],
)API_KEY = "sk-123456"
OLLAMA_BASE_URL = "http://127.0.0.1:11434"
DEFAULT_MODEL = "qwen2.5:latest"
def verify_api_key(request: Request):authorization: str = request.headers.get('authorization')if not authorization:raise HTTPException(status_code=401, detail="Authorization header is missing.")token_type, _, token = authorization.partition(' ')if token_type.lower() != 'bearer' or token != API_KEY:raise HTTPException(status_code=401, detail="Unauthorized: API Key is invalid or missing.")@app.get("/v1", dependencies=[Depends(verify_api_key)])
async def root():"""Root endpoint that returns API information"""return {"version": "1.0.0","status": "ok","endpoints": ["/v1/chat/completions","/v1/models","/health"]}@app.get("/v1/models", dependencies=[Depends(verify_api_key)])
async def list_models():"""List available models"""try:async with httpx.AsyncClient(timeout=10.0) as client:response = await client.get(f"{OLLAMA_BASE_URL}/api/tags")if response.status_code == 200:models = response.json().get("models", [])return {"data": [{"id": model["name"],"object": "model","created": 0,"owned_by": "ollama"}for model in models]}else:raise HTTPException(status_code=503, detail="Ollama service unavailable")except Exception as e:print(f"Error listing models: {str(e)}")raise HTTPException(status_code=503, detail=str(e))@app.get("/health", dependencies=[Depends(verify_api_key)])
async def health_check():"""健康检查接口"""try:async with httpx.AsyncClient(timeout=5.0) as client:response = await client.get(f"{OLLAMA_BASE_URL}/api/tags")if response.status_code == 200:print("Ollama service is healthy.")return {"status": "healthy", "message": "服务运行正常"}else:print("Ollama service is not healthy.")raise HTTPException(status_code=503, detail="Ollama 服务不可用")except httpx.HTTPStatusError as exc:print(f"HTTP error occurred: {exc.response.status_code}")raise HTTPException(status_code=exc.response.status_code, detail=str(exc))except httpx.RequestError as exc:print(f"An error occurred while requesting {exc.request.url!r}.")raise HTTPException(status_code=500, detail=str(exc))async def generate_sse_response(content):# 提取 SQL 语句并添加换行sql_match = re.search(r'```sql\n(.*?)\n```', content, re.DOTALL)sql = sql_match.group(1).strip() if sql_match else content# 添加换行符formatted_content = f"{sql}\n"# 构造 OpenAI API 格式的响应response_data = {"id": f"chatcmpl-{int(time.time())}","object": "chat.completion.chunk","created": int(time.time()),"model": "gpt-3.5-turbo","choices": [{"delta": {"content": formatted_content  # 使用带换行的内容},"finish_reason": None,"index": 0}]}# 发送主要内容yield f"data: {json.dumps(response_data, ensure_ascii=False)}\n\n"# 发送结束消息finish_response = {"id": f"chatcmpl-{int(time.time())}","object": "chat.completion.chunk","created": int(time.time()),"model": "gpt-3.5-turbo","choices": [{"delta": {},"finish_reason": "stop","index": 0}]}yield f"data: {json.dumps(finish_response, ensure_ascii=False)}\n\n"yield "data: [DONE]\n\n"# 重试策略装饰器
@backoff.on_exception(backoff.expo, httpx.ReadTimeout, max_tries=5, max_time=300)
async def send_request(ollama_request):timeout_config = httpx.Timeout(10.0, read=120.0)  # 连接超10秒,读取超时120秒async with httpx.AsyncClient(timeout=timeout_config) as client:try:response = await client.post(f"{OLLAMA_BASE_URL}/api/chat",json=ollama_request)print(f"Response received with status {response.status_code}")return responseexcept httpx.RequestError as exc:print(f"An error occurred while requesting {exc.request.url!r}.")raise HTTPException(status_code=500, detail=str(exc))@app.post("/v1/chat/completions", dependencies=[Depends(verify_api_key)])
@app.post("/chat/completions", dependencies=[Depends(verify_api_key)])
@app.post("/", dependencies=[Depends(verify_api_key)])
async def chat_completions(request: Request):try:body = await request.json()messages = body.get("messages", [])stream = body.get("stream", True)print(f"Received request with body: {body}")  # 使用 print 打印请求体ollama_request = {"model": DEFAULT_MODEL,"messages": messages,"stream": False}response = await send_request(ollama_request)print(f"Received response: {response.text}")  # 使用 print 打印响应文本if response.status_code != 200:print(f"Failed to get response from model, status code: {response.status_code}")raise HTTPException(status_code=400, detail="Failed to get response from model")ollama_response = response.json()content = ollama_response.get("message", {}).get("content", "")print(f"Processed content: {content}")  # 使用 print 打印处理后的内容if not stream:result = {"id": f"chatcmpl-{int(time.time())}","object": "chat.completion","created": int(time.time()),"model": DEFAULT_MODEL,"choices": [{"message": {"role": "database developer and expert","content": content},"finish_reason": "stop","index": 0}]}print(f"Returning non-stream response: {result}")  # 使用 print 打印非流响应return resultheaders = {"Content-Type": "text/event-stream","Cache-Control": "no-cache","Connection": "keep-alive"}return StreamingResponse(generate_sse_response(content),media_type="text/event-stream",headers=headers)except json.JSONDecodeError as e:print(f"JSON decoding error: {str(e)}")return JSONResponse(status_code=400, content={"message": "Invalid JSON data"})except Exception as e:print(f"Error during chat completions: {str(e)}")print(traceback.format_exc())  # 使用 print 打印堆栈跟踪return JSONResponse(status_code=500,content={"message": "Internal server error"})if __name__ == "__main__":print("Starting server on 0.0.0.0:8080")uvicorn.run(app, host="0.0.0.0", port=8080)

上面代码装key及model都写死,所以你一下要先下载下来相关的模型 。
python app.py
在这里插入图片描述
再注意以下本置:
在这里插入图片描述
在chat2db做好链接,再输入你的提示词。见下面效果:
在这里插入图片描述
响应速度几秒钟,当时看自己电脑响应速度了。都不花钱了,就不要什么自行车了。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/59756.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【搜狐简单AI-注册/登录安全分析报告-无验证方式导致安全隐患】

前言 由于网站注册入口容易被机器执行自动化程序攻击,存在如下风险: 暴力破解密码,造成用户信息泄露,不符合国家等级保护的要求。短信盗刷带来的拒绝服务风险 ,造成用户无法登陆、注册,大量收到垃圾短信的…

C函数如何返回参数lua使用

返回基本数据类型 数字类型(整数和浮点数) 在C函数中,可以使用lua_pushnumber函数将一个数字(整数或浮点数)压入Lua栈。当C函数返回后,Lua会从栈顶获取这个数字作为返回值。例如,以下是一个简单…

微服务day09

DSL查询 快速入门 GET /items/_search {"query": {"match_all": {}} } 叶子查询 GET /items/_search {"query": {"match_all": {}} }GET /items/_search {"query": {"multi_match": {"query": "脱…

Linux驱动开发第2步_“物理内存”和“虚拟内存”的映射

“新字符设备的GPIO驱动”和“设备树下的GPIO驱动”都要用到寄存器地址,使用“物理内存”和“虚拟内存”映射时,非常不方便,而pinctrl和gpio子系统的GPIO驱动,非常简化。因此,要重点学习pinctrl和gpio子系统下的GPIO驱…

信息技术引领未来:大数据治理的实践与挑战

信息技术引领未来:大数据治理的实践与挑战 在信息技术日新月异的今天,大数据已成为企业和社会发展的重要驱动力。大数据治理,作为确保数据质量、安全性和合规性的关键环节,正面临着前所未有的实践挑战与机遇。本文将探讨信息技术…

force stop和pm clear的区别

前言:因为工作中遇到force stop和pm clear进程后,进程不能再次挂起,谷歌系统共性问题,服务类应用经清缓存后当下服务就会挂掉,需要系统重启才能恢复。为了更好的“丢锅”,需要进一步学习force stop和pm cle…

【大数据学习 | flume】flume Sink Processors与拦截器Interceptor

1. Failover Sink Processor 故障转移处理器可以同时指定多个sink输出,按照优先级高低进行数据的分发,并具有故障转移能力。 需要修改第一台服务器agent a1.sourcesr1 a1.sinksk1 k2 a1.channelsc1 a1.sources.r1.typenetcat a1.sources.r1.bindworker…

C# 字典应用

using System;using System.Collections.Generic;class Program{static void Main(){// 创建一个字典&#xff0c;键是字符串类型&#xff0c;值是整数类型Dictionary<string, int> studentScores new Dictionary<string, int>();// 向字典中添加键值对// 原理&am…

如何从头开始构建神经网络?(附教程)

随着流行的深度学习框架的出现&#xff0c;如 TensorFlow、Keras、PyTorch 以及其他类似库&#xff0c;学习神经网络对于新手来说变得更加便捷。虽然这些框架可以让你在几分钟内解决最复杂的计算任务&#xff0c;但它们并不要求你理解背后所有需求的核心概念和直觉。如果你知道…

Conda安装与使用中的若干问题记录

Conda安装与使用中的若干问题记录 1.Anaconda 安装失败1.1.问题复述1.2.问题解决&#xff08;安装建议&#xff09; 2.虚拟环境pip install未安装至本虚拟环境2.1.问题复述2.2.问题解决 3.待补充 最近由于工作上的原因&#xff0c;要使用到Conda进行虚拟环境的管理&#xff0c;…

『OpenCV-Python』视频的读取和保存

点赞 + 关注 + 收藏 = 学会了 推荐关注 《OpenCV-Python专栏》 上一讲介绍了 OpenCV 的读取图片的方法,这一讲简单聊聊 OpenCV 读取和保存视频。 视频的来源主要有2种,一种是本地视频文件,另一种是实时视频流,比如手机和电脑的摄像头。 要读取这两种视频的方法都是一样的…

python关键字和内置函数有哪些?

Python关键字 Python 是一种高级编程语言&#xff0c;具有许多关键字。关键字是语言的保留字&#xff0c;它们在语法上具有特殊的含义&#xff0c;不能用作变量名、函数名或其他标识符。以下是 Python 的一些主要关键字&#xff1a; False - 布尔值假None - 空值或无值True -…

docker构建多平台容器

1.创建builder配置文件 buildkitd.toml debug true [registry."docker.io"] #mirrors ["hub.dvcloud.xin"] http true insecure true2.定义需要构建的平台 platform"linux/amd64,linux/arm64" 3.创建builder if ! docker buildx ls |g…

SQL 中 BETWEEN AND 用于字符串的理解

SQL 中 BETWEEN AND 用于字符串的理解 在 SQL 中&#xff0c;BETWEEN AND 关键字可以用在数值和日期类型上&#xff0c;非常好理解。同时也可以用于字符串类型&#xff0c;它用于选择在两个指定值之间的数据&#xff0c;包括边界值。本文主要总结一下BETWEEN AND用于string类型…

字节青训-字符串字符类型排序问题、小C点菜问题

目录 一、字符串字符类型排序问题 题目 样例 输入&#xff1a; 输出&#xff1a; 输入&#xff1a; 输出&#xff1a; 输入&#xff1a; 输出&#xff1a; 解题思路&#xff1a; 问题理解 数据结构选择 算法步骤 最终代码&#xff1a; 运行结果&#xff1a; ​…

ES数据迁移方式

elasticdump 需要安装elasticdump &#xff0c;node插件 #!/bin/bashindexes("index1" "index2")for index in "${indexes[]}" doecho "backup ${index} start"#--type: 迁移类型&#xff0c;默认为 data&#xff0c;表明只迁移数据…

深入理解接口测试:实用指南与最佳实践5.0(二)

✨博客主页&#xff1a; https://blog.csdn.net/m0_63815035?typeblog &#x1f497;《博客内容》&#xff1a;.NET、Java.测试开发、Python、Android、Go、Node、Android前端小程序等相关领域知识 &#x1f4e2;博客专栏&#xff1a; https://blog.csdn.net/m0_63815035/cat…

CSS基础知识05(弹性盒子、布局详解,动画,3D转换,calc)

目录 0、弹性盒子、布局 0.1.弹性盒子的基本概念 0.2.弹性盒子的主轴和交叉轴 0.3.弹性盒子的属性 flex-direction row row-reverse column column-reverse flex-wrap nowrap wrap wrap-reverse flex-dirction和flex-wrap的组合简写模式 justify-content flex-s…

任务调度工具Spring Test

Spring Task 是Spring框架提供的任务调度工具&#xff0c;可以按照约定的时间自动执行某个代码逻辑。 作用&#xff1a;定时自动执行某段Java代码 应用场景&#xff1a; 信用卡每月还款提醒 银行贷款每月还款提醒 火车票售票系统处理未支付订单 入职纪念日为用户发送通知 一.…

微信小程序实战篇-分类页面制作

一、项目背景与目标 在微信小程序开发中&#xff0c;分类页面是一个常见且重要的功能模块。它能够帮助用户快速定位和浏览不同类别的商品或信息&#xff0c;提升用户体验和操作效率。今天&#xff0c;我们将深入探讨如何制作一个实用的微信小程序分类页面&#xff0c;先来看一下…