Langchain-Chatchat
112 строк · 3.1 Кб
1import requests2import json3import sys4from pathlib import Path5
6sys.path.append(str(Path(__file__).parent.parent.parent))7from configs import BING_SUBSCRIPTION_KEY8from server.utils import api_address9
10from pprint import pprint11
12
13api_base_url = api_address()14
15
16def dump_input(d, title):17print("\n")18print("=" * 30 + title + " input " + "="*30)19pprint(d)20
21
22def dump_output(r, title):23print("\n")24print("=" * 30 + title + " output" + "="*30)25for line in r.iter_content(None, decode_unicode=True):26print(line, end="", flush=True)27
28
29headers = {30'accept': 'application/json',31'Content-Type': 'application/json',32}
33
34data = {35"query": "请用100字左右的文字介绍自己",36"history": [37{38"role": "user",39"content": "你好"40},41{42"role": "assistant",43"content": "你好,我是人工智能大模型"44}45],46"stream": True,47"temperature": 0.7,48}
49
50
51def test_chat_chat(api="/chat/chat"):52url = f"{api_base_url}{api}"53dump_input(data, api)54response = requests.post(url, headers=headers, json=data, stream=True)55dump_output(response, api)56assert response.status_code == 20057
58
59def test_knowledge_chat(api="/chat/knowledge_base_chat"):60url = f"{api_base_url}{api}"61data = {62"query": "如何提问以获得高质量答案",63"knowledge_base_name": "samples",64"history": [65{66"role": "user",67"content": "你好"68},69{70"role": "assistant",71"content": "你好,我是 ChatGLM"72}73],74"stream": True75}76dump_input(data, api)77response = requests.post(url, headers=headers, json=data, stream=True)78print("\n")79print("=" * 30 + api + " output" + "="*30)80for line in response.iter_content(None, decode_unicode=True):81data = json.loads(line[6:])82if "answer" in data:83print(data["answer"], end="", flush=True)84pprint(data)85assert "docs" in data and len(data["docs"]) > 086assert response.status_code == 20087
88
89def test_search_engine_chat(api="/chat/search_engine_chat"):90global data91
92data["query"] = "室温超导最新进展是什么样?"93
94url = f"{api_base_url}{api}"95for se in ["bing", "duckduckgo"]:96data["search_engine_name"] = se97dump_input(data, api + f" by {se}")98response = requests.post(url, json=data, stream=True)99if se == "bing" and not BING_SUBSCRIPTION_KEY:100data = response.json()101assert data["code"] == 404102assert data["msg"] == f"要使用Bing搜索引擎,需要设置 `BING_SUBSCRIPTION_KEY`"103
104print("\n")105print("=" * 30 + api + f" by {se} output" + "="*30)106for line in response.iter_content(None, decode_unicode=True):107data = json.loads(line[6:])108if "answer" in data:109print(data["answer"], end="", flush=True)110assert "docs" in data and len(data["docs"]) > 0111pprint(data["docs"])112assert response.status_code == 200113
114