From d4d9758caa66b8f82ea0f26c7ca1647ec858b301 Mon Sep 17 00:00:00 2001 From: pt Date: Wed, 5 Mar 2025 21:11:03 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0fastgpt=E9=80=82?= =?UTF-8?q?=E9=85=8D=EF=BC=9A=E6=94=AF=E6=8C=81think=E3=80=81variables?= =?UTF-8?q?=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.yaml | 9 ++++ core/providers/llm/fastgpt/fastgpt.py | 64 +++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 core/providers/llm/fastgpt/fastgpt.py diff --git a/config.yaml b/config.yaml index 6d9cd989b..4db46eeea 100644 --- a/config.yaml +++ b/config.yaml @@ -168,6 +168,15 @@ LLM: base_url: http://homeassistant.local:8123 agent_id: conversation.chatgpt api_key: 你的home assistant api访问令牌 + FastgptLLM: + # 定义LLM API类型 + type: fastgpt + # 如果使用fastgpt,配置文件里prompt(提示词)是无效的,需要在fastgpt控制台设置提示词 + base_url: https://host/api/v1 + api_key: fastgpt-xxx + variables: + k: "v" + k2: "v2" TTS: # 当前支持的type为edge、doubao,可自行适配 EdgeTTS: diff --git a/core/providers/llm/fastgpt/fastgpt.py b/core/providers/llm/fastgpt/fastgpt.py new file mode 100644 index 000000000..a705bc2b1 --- /dev/null +++ b/core/providers/llm/fastgpt/fastgpt.py @@ -0,0 +1,64 @@ +import json +from config.logger import setup_logging +import requests +from core.providers.llm.base import LLMProviderBase + +TAG = __name__ +logger = setup_logging() + +class LLMProvider(LLMProviderBase): + def __init__(self, config): + self.api_key = config["api_key"] + self.base_url = config.get("base_url") + self.detail = config.get("detail", False) + self.variables = config.get("variables", {}) + + def response(self, session_id, dialogue): + try: + # 取最后一条用户消息 + last_msg = next(m for m in reversed(dialogue) if m["role"] == "user") + + # 发起流式请求 + with requests.post( + f"{self.base_url}/chat/completions", + headers={"Authorization": f"Bearer {self.api_key}"}, + json={ + "stream": True, + "chatId": session_id, + "detail": self.detail, + "variables": self.variables, + "messages": [ + { + "role": "user", + "content": last_msg["content"] + } + ] + }, + stream=True + ) as r: + for line in r.iter_lines(): + if line: + try: + if line.startswith(b'data: '): + if line[6:].decode('utf-8') == '[DONE]': + break + + data = json.loads(line[6:]) + if 'choices' in data and len(data['choices']) > 0: + delta = data['choices'][0].get('delta', {}) + if delta and 'content' in delta and delta['content'] is not None: + content = delta['content'] + if '' in content: + continue + if '' in content: + continue + yield content + + except json.JSONDecodeError as e: + continue + except Exception as e: + continue + + except Exception as e: + logger.bind(tag=TAG).error(f"Error in response generation: {e}") + yield "【服务响应异常】" \ No newline at end of file