Refactoring

This commit is contained in:
Changhua
2023-11-26 00:11:48 +08:00
parent 6aafbc6eec
commit af2b317cd7
19 changed files with 85 additions and 57 deletions

View File

@@ -54,7 +54,7 @@ python main.py
# 需要停止按 Ctrl+C
```
如果你配置了多个模型(不需要将其他配置注释或者移除)下面的内容才对你有帮助否则略过通过python main.py -h 通过参数可以选择要跑的模型。
如果你配置了多个模型不需要将其他配置注释或者移除,下面的内容才对你有帮助否则略过,通过 python main.py -h 通过参数可以选择要跑的模型。
```sh
# 查看帮助
python main.py -h
@@ -62,6 +62,7 @@ python main.py -h
# -h, --help show this help message and exit
# -c C, --chat_model C 选择要使用的AI模型默认不选择可选参数1. tigerbot 模型 2. chatgpt 模型 3. 讯飞星火模型 4. chatglm 模型
```
```sh
# 例: 我想运行选择chatgpt的机器人
python main.py -c 2
@@ -99,6 +100,8 @@ groups:
#### 配置 AI 模型
为了使用 AI 模型,需要对相应模型并进行配置。
使用 ChatGLM 见注意事项 [README.MD](base/chatglm/README.MD)
```yaml
chatgpt: # -----chatgpt配置这行不填-----
key: # 填写你 ChatGPT 的 key
@@ -107,7 +110,7 @@ chatgpt: # -----chatgpt配置这行不填-----
prompt: 你是智能聊天机器人,你叫 wcferry # 根据需要对角色进行设定
chatglm: # -----chatglm配置这行不填-----
key: # key 暂时没有
key: sk-012345678901234567890123456789012345678901234567 # 这个应该不用动
api: http://localhost:8000/v1 # 根据自己的chatglm地址修改
proxy: # 如果你在国内你可能需要魔法大概长这样http://域名或者IP地址:端口号
prompt: 你是智能聊天机器人,你叫小薇 # 根据需要对角色进行设定

View File

@@ -1,16 +1,17 @@
# ChatGLM3集成使用说明
# ChatGLM3 集成使用说明
* 1.需要取消配置中 chatglm 的注释, 并配置对应信息使用ChatGLM3,启用最新版ChatGLM3根目录下openai_api.py获取api地址
1. 需要取消配置中 chatglm 的注释, 并配置对应信息,使用 [ChatGLM3](https://github.com/THUDM/ChatGLM3), 启用最新版 ChatGLM3 根目录下 openai_api.py 获取 api 地址:
```yaml
# 如果要使用 chatglm取消下面的注释并填写相关内容
chatglm:
key: xxx #根据需要自己做key校验
key: sk-012345678901234567890123456789012345678901234567 # 根据需要自己做key校验
api: http://localhost:8000/v1 # 根据自己的chatglm地址修改
proxy: # 如果你在国内你可能需要魔法大概长这样http://域名或者IP地址:端口号
prompt: 你是智能聊天机器人,你叫小薇 # 根据需要对角色进行设定
file_path: F:/Pictures/temp #设定生成图片和代码使用的文件夹路径
```
* 2.修改chatglm/tool_registry.py工具里面的一下配置comfyUI地址或者根据需要自己配置一些工具,函数名上需要加@register_tool,函数里面需要叫'''函数描述'''参数需要用Annotated[str,'',True]修饰,分别是类型,参数说明,是否必填,再加->加上对应的返回类型
2. 修改 chatglm/tool_registry.py 工具里面的一下配置comfyUI 地址或者根据需要自己配置一些工具,函数名上需要加 @register_tool, 函数里面需要叫'''函数描述''',参数需要用 Annotated[str,'',True] 修饰,分别是类型,参数说明,是否必填,再加 ->加上对应的返回类型
```python
@register_tool
def get_confyui_image(prompt: Annotated[str, '要生成图片的提示词,注意必须是英文', True]) -> dict:
@@ -30,12 +31,15 @@ def get_confyui_image(prompt: Annotated[str, '要生成图片的提示词,注意
return {'res': images[0]['image'], 'res_type': 'image', 'filename': images[0]['filename']}
```
* 3 使用 Code Interpreter 还需要安装 Jupyter 内核,默认名称叫chatglm3
3. 使用 Code Interpreter 还需要安装 Jupyter 内核,默认名称叫 chatglm3
```
ipython kernel install --name chatglm3 --user
```
如果名称需要自定义可以配置系统环境变量IPYKERNEL 或者修改 chatglm/code_kernel.py
```
IPYKERNEL = os.environ.get('IPYKERNEL', 'chatglm3')
```
* 4 启动后,发送 #帮助 可以查看 模式和常用指令
4. 启动后,发送 #帮助 可以查看 模式和常用指令

View File

@@ -2,11 +2,9 @@ import base64
import os
import queue
import re
import time
from io import BytesIO
from pprint import pprint
from subprocess import PIPE
from typing import Dict, Optional, Tuple, Union
from typing import Optional, Union
import jupyter_client
from PIL import Image

View File

@@ -2,20 +2,16 @@ import inspect
import json
import random
import re
import time
import traceback
from copy import deepcopy
from datetime import datetime
from pprint import pformat
from types import GenericAlias
from typing import Annotated, get_origin
import requests
from func_news import News
from base.chatglm.comfyUI_api import ComfyUIApi
from base.func_news import News
from zhdate import ZhDate
from chatglm.comfyUI_api import ComfyUIApi
_TOOL_HOOKS = {}
_TOOL_DESCRIPTIONS = {}

View File

Can't render this file because it is too large.

View File

@@ -5,39 +5,45 @@ import json
import os
import random
from datetime import datetime
from typing import Dict, Optional, Tuple, Union
from typing import Optional
import openai
from base.chatglm.code_kernel import CodeKernel, execute
from base.chatglm.tool_registry import dispatch_tool, extract_code, get_tools
from wcferry import Wcf
from chatglm.code_kernel import CodeKernel, execute
from chatglm.tool_registry import dispatch_tool, extract_code, get_tools
functions = get_tools()
class ChatGLM:
def __init__(self, config={}, wcf: Optional[Wcf] = None, max_retry=5) -> None:
openai.api_key = config.get('key', 'XXX')
openai.api_key = config.get("key", "empty")
# 自己搭建或第三方代理的接口
openai.api_base = config.get('api', 'http://localhost:8000/v1')
if config.get('proxy', None):
openai.proxy = {"http": config.get(
'proxy', None), "https": config.get('proxy', None)}
openai.api_base = config["api"]
proxy = config.get("proxy")
if proxy:
openai.proxy = {"http": proxy, "https": proxy}
self.conversation_list = {}
self.chat_type = {}
self.max_retry = max_retry
self.wcf = wcf
self.filePath = config.get('file_path', 'temp')
self.filePath = config["file_path"]
self.kernel = CodeKernel()
self.system_content_msg = {"chat": [{"role": "system", "content": config.get('prompt', '你是智能聊天机器人,你叫小薇')}],
self.system_content_msg = {"chat": [{"role": "system", "content": config["prompt"]}],
"tool": [{"role": "system", "content": "Answer the following questions as best as you can. You have access to the following tools:"}],
"code": [{"role": "system", "content": "你是一位智能AI助手你叫ChatGLM你连接着一台电脑但请注意不能联网。在使用Python解决任务时你可以运行代码并得到结果如果运行结果有错误你需要尽可能对代码进行改进。你可以处理用户上传到电脑上的文件文件默认存储路径是{}".format(self.filePath)}]}
def __repr__(self):
return 'ChatGLM'
@staticmethod
def value_check(conf: dict) -> bool:
if conf:
if conf.get("api") and conf.get("prompt") and conf.get("file_path"):
return True
return False
def get_answer(self, question: str, wxid: str) -> str:
# wxid或者roomid,个人时为微信id群消息时为群id
if '#帮助' == question:

View File

@@ -21,6 +21,13 @@ class ChatGPT:
def __repr__(self):
return 'ChatGPT'
@staticmethod
def value_check(conf: dict) -> bool:
if conf:
if conf.get("key") and conf.get("api") and conf.get("prompt"):
return True
return False
def get_answer(self, question: str, wxid: str) -> str:
# wxid或者roomid,个人时为微信id群消息时为群id
self.updateMessage(wxid, question, "user")

View File

@@ -1,12 +1,15 @@
# -*- coding: utf-8 -*-
import os
import random
import pandas as pd
class Chengyu(object):
def __init__(self) -> None:
self.df = pd.read_csv("chengyu.csv", delimiter="\t")
root = os.path.dirname(os.path.abspath(__file__))
self.df = pd.read_csv(f"{root}/chengyu.csv", delimiter="\t")
self.cys, self.zis, self.yins = self._build_data()
def _build_data(self):

View File

@@ -1,5 +1,6 @@
import datetime
import calendar
import datetime
from chinese_calendar import is_workday
from robot import Robot

View File

@@ -18,6 +18,12 @@ class TigerBot:
def __repr__(self):
return 'TigerBot'
@staticmethod
def value_check(conf: dict) -> bool:
if conf:
return all(conf.values())
return False
def get_answer(self, msg: str, sender: str = None) -> str:
payload = {
"text": msg,

View File

@@ -19,6 +19,12 @@ class XinghuoWeb:
def __repr__(self):
return 'XinghuoWeb'
@staticmethod
def value_check(conf: dict) -> bool:
if conf:
return all(conf.values())
return False
def get_answer(self, msg: str, sender: str = None) -> str:
answer = self._chat.chat(msg)
return answer

View File

@@ -54,7 +54,7 @@ chatgpt: # -----chatgpt配置这行不填-----
prompt: 你是智能聊天机器人你叫wcferry # 根据需要对角色进行设定
chatglm: # -----chatglm配置这行不填-----
key: # key 暂时没有
key: sk-012345678901234567890123456789012345678901234567 # 这个应该不用动
api: http://localhost:8000/v1 # 根据自己的chatglm地址修改
proxy: # 如果你在国内你可能需要魔法大概长这样http://域名或者IP地址:端口号
prompt: 你是智能聊天机器人,你叫小薇 # 根据需要对角色进行设定

View File

@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
import time
import schedule
from typing import Any, Callable
import schedule
class Job(object):
def __init__(self) -> None:

View File

@@ -2,15 +2,13 @@
# -*- coding: utf-8 -*-
import signal
from argparse import ArgumentParser
from wcferry import Wcf
from base.func_report_reminder import ReportReminder
from configuration import Config
from func_report_reminder import ReportReminder
from robot import Robot
from constants import ChatType
from robot import Robot
from wcferry import Wcf
def weather_report(robot: Robot) -> None:

View File

@@ -7,17 +7,16 @@ import xml.etree.ElementTree as ET
from queue import Empty
from threading import Thread
from wcferry import Wcf, WxMsg
from constants import ChatType
from base.func_chatglm import ChatGLM
from base.func_chatgpt import ChatGPT
from base.func_chengyu import cy
from base.func_news import News
from base.func_tigerbot import TigerBot
from base.func_xinghuo_web import XinghuoWeb
from configuration import Config
from func_chatgpt import ChatGPT
from func_chatglm import ChatGLM
from func_chengyu import cy
from func_news import News
from func_tigerbot import TigerBot
from func_xinghuo_web import XinghuoWeb
from constants import ChatType
from job_mgmt import Job
from wcferry import Wcf, WxMsg
class Robot(Job):
@@ -32,31 +31,31 @@ class Robot(Job):
self.allContacts = self.getAllContacts()
if ChatType.is_in_chat_types(chat_type):
if chat_type == ChatType.TIGER_BOT.value and self.value_check(self.config.TIGERBOT):
if chat_type == ChatType.TIGER_BOT.value and TigerBot.value_check(self.config.TIGERBOT):
self.chat = TigerBot(self.config.TIGERBOT)
elif chat_type == ChatType.CHATGPT.value and self.value_check(self.config.CHATGPT):
elif chat_type == ChatType.CHATGPT.value and ChatGPT.value_check(self.config.CHATGPT):
self.chat = ChatGPT(self.config.CHATGPT)
elif chat_type == ChatType.XINGHUO_WEB.value and self.value_check(self.config.XINGHUO_WEB):
elif chat_type == ChatType.XINGHUO_WEB.value and XinghuoWeb.value_check(self.config.XINGHUO_WEB):
self.chat = XinghuoWeb(self.config.XINGHUO_WEB)
elif chat_type == ChatType.CHATGLM.value and self.value_check(self.config.CHATGLM):
elif chat_type == ChatType.CHATGLM.value and ChatGLM.value_check(self.config.CHATGLM):
self.chat = ChatGLM(self.config.CHATGLM)
else:
self.LOG.warning('未配置模型')
self.LOG.warning("未配置模型")
self.chat = None
else:
if self.value_check(self.config.TIGERBOT):
if TigerBot.value_check(self.config.TIGERBOT):
self.chat = TigerBot(self.config.TIGERBOT)
elif self.value_check(self.config.CHATGPT):
elif ChatGPT.value_check(self.config.CHATGPT):
self.chat = ChatGPT(self.config.CHATGPT)
elif self.value_check(self.config.XINGHUO_WEB):
elif XinghuoWeb.value_check(self.config.XINGHUO_WEB):
self.chat = XinghuoWeb(self.config.XINGHUO_WEB)
elif self.value_check(self.config.CHATGLM):
elif ChatGLM.value_check(self.config.CHATGLM):
self.chat = ChatGLM(self.config.CHATGLM)
else:
self.LOG.warning('未配置模型')
self.LOG.warning("未配置模型")
self.chat = None
self.LOG.info(f'已选择: {self.chat}')
self.LOG.info(f"已选择: {self.chat}")
@staticmethod
def value_check(args: dict) -> bool: