240908-Python代码实现6种与DBGPT-Knowledge-API的交互方式

news2024/9/17 7:41:34

在这里插入图片描述

A. Chat模式


# import asyncio
# from dbgpt.core import ModelRequest
# from dbgpt.model.proxy import OllamaLLMClient

# client=OllamaLLMClient()

# print(asyncio.run(client.generate(ModelRequest._build("qwen2:1.5b", "你是谁?"))))


import asyncio
from dbgpt.client import Client
from dbgpt.model.proxy import OllamaLLMClient


DBGPT_API_KEY = "dbgpt"

client = Client(
    api_base='http://localhost:5670/api/v2',
    api_key=DBGPT_API_KEY)

# client=OllamaLLMClient()

async def chat():
    async for data in client.chat_stream(
        model="ollama_proxyllm",
        messages="请介绍名侦探柯南",
    ):
        print(data.choices[0].delta.content)
        # print(data.choices[0])
        
if __name__ == "__main__":
     
    asyncio.run(chat())

B. Knowledge模式

import requests
import json

mode = 'example'


if mode=='example-1': # ⭐️ 对已存在的Space进行提问
    ## Question: 流式输出的方法,参考ChatGPT的回答
    # DBGPT_API_KEY=dbgpt
    # SPACE_NAME=Test-DBGPT
    # curl -X POST "http://localhost:5670/api/v2/chat/completions" \
    #     -H "Authorization: Bearer $DBGPT_API_KEY" \
    #     -H "accept: application/json" \
    #     -H "Content-Type: application/json" \
    #     -d "{\"messages\":\"Hello\",\"model\":\"ollama_proxyllm\", \"chat_mode\": \"chat_knowledge\", \"chat_param\": \"$SPACE_NAME\"}"
    
    DBGPT_API_KEY = "dbgpt"
    SPACE_NAME = "Test-DBGPT"

    url = "http://localhost:5670/api/v2/chat/completions"
    headers = {
        "Authorization": f"Bearer {DBGPT_API_KEY}",
        "accept": "application/json",
        "Content-Type": "application/json"
    }
    data = {
        "messages": "Hello",
        "model": "ollama_proxyllm",
        "chat_mode": "chat_knowledge",
        "chat_param": SPACE_NAME
    }

    # 打印要发送的 JSON 数据
    print("Sending JSON data:", json.dumps(data, indent=4))

    response = requests.post(url, headers=headers, json=data)

    print(response.status_code)  # 输出响应状态码
    print("Raw response text:", response.text)  # 打印原始响应内容



if mode=='example-2': # ⭐️ 同上:对已存在的Space进行提问
    DBGPT_API_KEY = "dbgpt"
    SPACE_NAME = "Test-DBGPT"

    url = "http://localhost:5670/api/v2/chat/completions"
    headers = {
        "Authorization": f"Bearer {DBGPT_API_KEY}",
        "accept": "application/json",
        "Content-Type": "application/json"
    }
    data = {
        "messages": "Hello",
        "model": "ollama_proxyllm",
        "chat_mode": "chat_knowledge",
        "chat_param": SPACE_NAME
    }

    response = requests.post(url, headers=headers, json=data)

    print(response.status_code)
    print(response.json())  # 打印响应结果 

if mode=='create': # ⭐️ 创建新的Space:CREATED_SPACE_NAME = "test_ollama1" 
    # DBGPT_API_KEY="dbgpt" 
    # curl --location --request POST 'http://localhost:5670/api/v2/serve/knowledge/spaces' \
    # --header 'Authorization: Bearer $DBGPT_API_KEY' \
    # --header 'Content-Type: application/json' \
    # --data-raw '{"desc": "for client space desc", "name": "test_space_2", "owner": "dbgpt", "vector_type": "Chroma"
    # }'

    # Set API Key
    DBGPT_API_KEY = "dbgpt"
    CREATED_SPACE_NAME = "test_ollama1"

    # Define the URL and headers
    url = "http://localhost:5670/api/v2/serve/knowledge/spaces"
    headers = {
        "Authorization": f"Bearer {DBGPT_API_KEY}",
        "Content-Type": "application/json"
    }

    # Define the payload
    data = {
        "desc": "for client space desc",
        "name": CREATED_SPACE_NAME,
        "owner": "dbgpt",
        "vector_type": "Chroma"
    }

    # Make the POST request
    response = requests.post(url, headers=headers, json=data)

    # Print the response
    print(response.status_code)
    space = response.json()
    print(space) 

if mode=='update': # ⭐️ 更新指定的Space 
    # DBGPT_API_KEY="dbgpt" 
    # curl --location --request PUT 'http://localhost:5670/api/v2/serve/knowledge/spaces' \
    # --header 'Authorization: Bearer $DBGPT_API_KEY' \
    # --header 'Content-Type: application/json' \
    # --data-raw '{"desc": "for client space desc v2", "id": "49", "name": "test_space_2", "owner": "dbgpt", "vector_type": "Chroma"
    # }'

    # Set API Key
    DBGPT_API_KEY = "dbgpt"
    Update_SPACE_NAME = "test_space_20"


    # Define the URL and headers
    url = "http://localhost:5670/api/v2/serve/knowledge/spaces"
    headers = {
        "Authorization": f"Bearer {DBGPT_API_KEY}",
        "Content-Type": "application/json"
    }

    # Define the payload
    data = {
        "desc": "for client space desc v2",
        "id": "2",
        "name": Update_SPACE_NAME,
        "owner": "null",
        "vector_type": "Chroma"
    }

    # Make the PUT request
    response = requests.put(url, headers=headers, json=data)

    # Print the response
    print(response.status_code)
    print(response.json())



if mode=='delete': # ⭐️ 删除指定的Space,SPACE_ID可通过上面的list获得 
    # DBGPT_API_KEY=dbgpt
    # SPACE_ID={YOUR_SPACE_ID}
    # curl -X DELETE "http://localhost:5670/api/v2/serve/knowledge/spaces/$SPACE_ID" \
    #     -H "Authorization: Bearer $DBGPT_API_KEY" \
    #     -H "accept: application/json" \
    #     -H "Content-Type: application/json" \
        
    DBGPT_API_KEY = 'dbgpt'
    SPACE_ID = 1 # 这里需要指定Space的ID号码

    url = f"http://localhost:5670/api/v2/serve/knowledge/spaces/{SPACE_ID}"
    headers = {
        "Authorization": f"Bearer {DBGPT_API_KEY}",
        "accept": "application/json",
        "Content-Type": "application/json"
    }

    response = requests.delete(url, headers=headers)

    # 检查响应状态
    if response.status_code == 200:
        print("Space deleted successfully.")
    else:
        print(f"Failed to delete space. Status code: {response.status_code}, Response: {response.text}")



## Delete: 虽然响应报错,但是成功删除的对应的DBGPT中的Space
# 【非PDF-SPACE的删除信息】
# (dbgpt-env) (base) lgk@WIN-20240401VAM:~/Projects/DB-GPT-main$ python test_knowledge.py 
# Failed to delete space. Status code: 400, Response: {"success":false,"err_code":"E0003","err_msg":"1 validation errors:\n  {'type': 'none_required', 'loc': ('response', 'data'), 'msg': 'Input should be None', 'input': SpaceServeResponse(id=3, name='Test-Delete', vector_type='Chroma', desc='Test delete files', context=None, owner=None, user_id=None, user_ids=None, sys_code=None, domain_type='Normal')}\n","data":null}

# 【PDF-SPACE的删除信息】
# (dbgpt-env) (base) lgk@WIN-20240401VAM:~/Projects/DB-GPT-main$ python test_knowledge.py 
# Failed to delete space. Status code: 400, Response: {"success":false,"err_code":"E0003","err_msg":"1 validation errors:\n  {'type': 'none_required', 'loc': ('response', 'data'), 'msg': 'Input should be None', 'input': SpaceServeResponse(id=1, name='Test-DBGPT', vector_type='Chroma', desc='for client space desc v2', context='{\"embedding\":{\"topk\":5,\"recall_score\":\"0.1\",\"recall_type\":\"TopK\",\"model\":\"proxy_ollama\",\"chunk_size\":500,\"chunk_overlap\":50},\"prompt\":{\"scene\":\"A chat between a curious user and an artificial intelligence assistant, who very familiar with database related knowledge. \\\\nThe assistant gives helpful, detailed, professional and polite answers to the user\\'s questions. \",\"template\":\" Based on the known information below, provide users with professional and concise answers to their questions.\\\\nconstraints:\\\\n    1.Ensure to include original markdown formatting elements such as images, links, tables, or code blocks without alteration in the response if they are present in the provided information.\\\\n        For example, image format should be ![image.png](xxx), link format [xxx](xxx), table format should be represented with |xxx|xxx|xxx|, and code format with xxx.\\\\n    2.If the information available in the knowledge base is insufficient to answer the question, state clearly: \\\\\"The content provided in the knowledge base is not enough to answer this question,\\\\\" and avoid making up answers.\\\\n    3.When responding, it is best to summarize the points in the order of 1, 2, 3, And displayed in markdwon format.\\\\n            known information: \\\\n            {context}\\\\n            question:\\\\n            {question},when answering, use the same language as the \\\\\"user\\\\\".\\\\n\",\"max_token\":2000},\"summary\":{\"max_iteration\":5,\"concurrency_limit\":3}}', owner='null', user_id=None, user_ids=None, sys_code=None, domain_type='Normal')}\n","data":null}
   




if mode=='get': # ⭐️ 获得执行的Space
    # DBGPT_API_KEY=dbgpt
    # SPACE_ID={YOUR_SPACE_ID}
    # curl -X GET "http://localhost:5670/api/v2/serve/knowledge/spaces/$SPACE_ID" -H "Authorization: Bearer $DBGPT_API_KEY"
    
    
    # Set API Key and Space ID
    DBGPT_API_KEY = "dbgpt"
    SPACE_ID = "Test-DBGPT"  # Replace with your actual space ID

    # Define the URL and headers
    url = f"http://localhost:5670/api/v2/serve/knowledge/spaces/{SPACE_ID}"
    headers = {
        "Authorization": f"Bearer {DBGPT_API_KEY}"
    }

    # Make the GET request
    response = requests.get(url, headers=headers)

    # Print the response
    print(response.status_code)
    print(response.json())

if mode=='list': # ⭐️ 查看现有的所有Space 
    # DBGPT_API_KEY=dbgpt 
    # curl -X GET 'http://localhost:5670/api/v2/serve/knowledge/spaces' -H "Authorization: Bearer $DBGPT_API_KEY"
    
    # Set API Key
    DBGPT_API_KEY = "dbgpt"

    # Define the URL and headers
    url = "http://localhost:5670/api/v2/serve/knowledge/spaces"
    headers = {
        "Authorization": f"Bearer {DBGPT_API_KEY}"
    }

    # Make the GET request
    response = requests.get(url, headers=headers)

    # Print the response
    print(response.status_code)
    print(response.json())   

C. List Knowledge Space 返回的结果

{
    "success": true,
    "err_code": null,
    "err_msg": null,
    "data": {
      "items": [
        {
          "id": 1,
          "name": "Test-DBGPT",
          "vector_type": "Chroma",
          "desc": "for client space desc v2",
          "context": {
            "embedding": {
              "topk": 5,
              "recall_score": "0.1",
              "recall_type": "TopK",
              "model": "proxy_ollama",
              "chunk_size": 500,
              "chunk_overlap": 50
            },
            "prompt": {
              "scene": "A chat between a curious user and an artificial intelligence assistant, who very familiar with database related knowledge. \nThe assistant gives helpful, detailed, professional and polite answers to the user's questions.",
              "template": " Based on the known information below, provide users with professional and concise answers to their questions.\nconstraints:\n    1.Ensure to include original markdown formatting elements such as images, links, tables, or code blocks without alteration in the response if they are present in the provided information.\n        For example, image format should be ![image.png](xxx), link format [xxx](xxx), table format should be represented with |xxx|xxx|xxx|, and code format with xxx.\n    2.If the information available in the knowledge base is insufficient to answer the question, state clearly: \"The content provided in the knowledge base is not enough to answer this question,\" and avoid making up answers.\n    3.When responding, it is best to summarize the points in the order of 1, 2, 3, And displayed in markdwon format.\n            known information: \n            {context}\n            question:\n            {question},when answering, use the same language as the \"user\".\n",
              "max_token": 2000
            },
            "summary": {
              "max_iteration": 5,
              "concurrency_limit": 3
            }
          },
          "owner": "null",
          "user_id": null,
          "user_ids": null,
          "sys_code": null,
          "domain_type": "Normal"
        },
        {
          "id": 2,
          "name": "test_space_20",
          "vector_type": "Chroma",
          "desc": "for client space desc v2",
          "context": null,
          "owner": "null",
          "user_id": null,
          "user_ids": null,
          "sys_code": null,
          "domain_type": null
        },
        {
          "id": 3,
          "name": "Test-Delete",
          "vector_type": "Chroma",
          "desc": "Test delete files",
          "context": null,
          "owner": null,
          "user_id": null,
          "user_ids": null,
          "sys_code": null,
          "domain_type": "Normal"
        }
      ],
      "total_count": 3,
      "total_pages": 1,
      "page": 1,
      "page_size": 20
    }
  }
  

D. 参考文献

  • Knowledge | DB-GPT
  • 工作流API

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

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

相关文章

Debug-027-el-tooltip组件的使用及注意事项

前言: 这两天,碰到这个饿了么的el-tooltip比较多。这个组件使用起来也挺简单的,常用于展示鼠标 hover 时的提示信息。但是有一些小点需要注意。这里不再机械化的介绍文档,不熟悉的话可以先看一下: https://element-pl…

这个隐藏功能,90%的人还不知道!可一键直达40+AI应用!含Kimi、腾讯元宝、秘塔AI等常用AI工具

大家好,我是程序员X小鹿,前互联网大厂程序员,自由职业2年,也一名 AIGC 爱好者,持续分享更多前沿的「AI 工具」和「AI副业玩法」,欢迎一起交流~ 又是被粉丝感动的一天。 昨天一位读者加到我,是一…

基于Java+SpringBoot+Vue+MySQL的美容美发管理系统

作者:计算机学姐 开发技术:SpringBoot、SSM、Vue、MySQL、JSP、ElementUI等,“文末源码”。 专栏推荐:前后端分离项目源码、SpringBoot项目源码、SSM项目源码 系统展示 基于SpringBootVue的美容美发管理系统【附源码文档】、前后…

音频创作无界限:全球热门剪辑软件深度评测

如果是一个音乐爱好者肯定会有过想要录制自己音乐作品的想法吧。这个操作放在早些年可能有些难度,但是现在是科技告诉发展的时代,互联网上有不少在线音频剪辑工具可以供我们选择。这次我们就一起来探讨有什么适合音频剪辑的工具。 1.福昕音频剪辑 链接…

3.C_数据结构_栈

概述 什么是栈: 栈又称堆栈,是限定在一段进行插入和删除操作的线性表。具有后进先出(LIFO)的特点。 相关名词: 栈顶:允许操作的一端栈底:不允许操作的一端空栈:没有元素的栈 栈的作用: 可…

【机器人工具箱Robotics Toolbox开发笔记(一)】Matlab机器人工具箱简介

MATLAB是一款被广泛应用于科学计算和工程领域的专业软件。它的全称为Matrix Laboratory(矩阵实验室),因为其最基本的数据类型就是矢量与矩阵,所以在处理数学和科学问题时非常方便,可用于线性代数计算、图形和动态仿真的…

系统架构的演进:同步通讯到异步通讯的过渡

系统架构的演进:同步通讯到异步通讯的过渡 一 . 同步通讯 VS 异步通讯1.1 同步调用方案① 耦合度高② 性能下降③ 资源浪费④ 级联失败 1.2 异步调用方案① 同步解耦② 性能提升 , 吞吐量增加③ 服务没有强依赖 , 不必考虑级联失败问题④ 流量削峰 1.3 小结 二 . 三…

【C++】STL学习——stack和queue的讲解(了解适配器)

目录 stack介绍queue介绍适配器stack的模拟实现queue模拟实现deque(了解) stack介绍 stack是一种容器适配器,专门用在具有后进先出操作的上下文环境中,其删除只能从容器的一端进行 元素的插入与提取操作。stack是作为容器适配器被…

Java | Leetcode Java题解之第393题UTF-8编码验证

题目&#xff1a; 题解&#xff1a; class Solution {static final int MASK1 1 << 7;static final int MASK2 (1 << 7) (1 << 6);public boolean validUtf8(int[] data) {int m data.length;int index 0;while (index < m) {int num data[index];…

算法练习题18——leetcode240搜索二维矩阵||(二分)

题目描述 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性&#xff1a; 每行的元素从左到右升序排列。 每列的元素从上到下升序排列。 代码 class Solution {public boolean searchMatrix(int[][] matrix, int target) {for(int[…

双指针(6)_单调性_查找总价格为目标值的两个商品

个人主页&#xff1a;C忠实粉丝 欢迎 点赞&#x1f44d; 收藏✨ 留言✉ 加关注&#x1f493;本文由 C忠实粉丝 原创 双指针(6)_单调性_查找总价格为目标值的两个商品 收录于专栏【经典算法练习】 本专栏旨在分享学习C的一点学习笔记&#xff0c;欢迎大家在评论区交流讨论&#…

DuPL: Dual Student with Trustworthy Progressive Learning for Robust WSSS

摘要 近年来&#xff0c;具有图像级标签的单阶段弱监督语义分割(WSSS)因其简化了其繁琐的多阶段语义分割而获得了越来越多的关注。由于类激活图(Class Activation Map, CAM)固有的模糊性&#xff0c;我们观察到一级管道经常会遇到由错误的CAM伪标签引起的确认偏差&#xff0c;…

基于SpringBoot的图书馆座位预约系统+小程序+LW参考示例

系列文章目录 1.基于SSM的洗衣房管理系统原生微信小程序LW参考示例 2.基于SpringBoot的宠物摄影网站管理系统LW参考示例 3.基于SpringBootVue的企业人事管理系统LW参考示例 4.基于SSM的高校实验室管理系统LW参考示例 5.基于SpringBoot的二手数码回收系统原生微信小程序LW参考示…

继电器的使用

本文为大家讲一下继电器的常规使用. 添加 在菜单中选择 “绘制–无源元件–添加继电器(relay)” 以添加继电器. 或者用 shiftr(大写) 这个快捷键 继电器由一个线圈和该线圈所控制的铁质弹性开关(衔铁)组成. 原理 它的原理如下: 上面的铁质弹性开关, 默认情况下在弹力作用下…

java基础概念22-抽象类

一、抽象类的引入 1-1、封装 问题&#xff1a;javabean越来越多。重复的内容越多——继承 1-2、继承 二、抽象类、抽象方法 一个方法抽取到父类中&#xff0c;不确定方法体——抽象方法 定义了抽象方法的类——抽象类。 在Java中&#xff0c;抽象类是一种特殊的类&#xff0c…

博士生锻炼记录:2024.9.8

读博三年来感觉身体状况大不如前&#xff0c;虽然博士生的主要任务就是做课题和发文章&#xff0c;但是身体健康也是不容忽视的一环&#xff0c;一个好的身体是做好任何事情的基础&#xff0c;我们应该在不影响身体健康的前提下努力做课题。 这周初去参加了一个体成分测量的活…

Python编码系列—Python项目管理:掌握高效工具与实践

&#x1f31f;&#x1f31f; 欢迎来到我的技术小筑&#xff0c;一个专为技术探索者打造的交流空间。在这里&#xff0c;我们不仅分享代码的智慧&#xff0c;还探讨技术的深度与广度。无论您是资深开发者还是技术新手&#xff0c;这里都有一片属于您的天空。让我们在知识的海洋中…

YOLOv9改进策略【Neck】| 使用CARAFE轻量级通用上采样算子

一、本文介绍 本文记录的是利用CARAFE上采样对YOLOv9的颈部网络进行改进的方法研究。YOLOv9采用传统的最近邻插值的方法&#xff0c;仅考虑子像素邻域&#xff0c;无法捕获密集预测任务所需的丰富语义信息&#xff0c;从而影响模型在密集预测任务中的性能。CARAFE通过在大感受…

Linux服务器Java启动脚本

Linux服务器Java启动脚本 1、初版2、优化版本3、常用脚本仓库 本文章介绍了如何在Linux服务器上执行Java并启动jar包&#xff0c; 通常我们会使用nohup直接启动&#xff0c;但是还是需要手动停止然后再次启动&#xff0c; 那如何更优雅的在服务器上启动jar包呢&#xff0c;让我…

设计模式之工厂模式(通俗易懂--代码辅助理解【Java版】)

文章目录 1、工厂模式概述1&#xff09;特点&#xff1a;2&#xff09;主要角色&#xff1a;3&#xff09;工作流程&#xff1a;4&#xff09;优点5&#xff09;缺点6&#xff09;适用场景 2、简单工厂模式(静态工厂模式)1) 在简单工厂模式中&#xff0c;有三个主要角色&#x…