langchain-chatchat 写接口
时间: 2025-05-08 18:56:57 浏览: 20
### Langchain 和 Chatchat 的 API 接口开发
对于 Langchain-Chatchat 流式接口的访问,当前版本已采用 HTTP 流式协议替代了早期使用的 WebSocket 协议[^1]。这意味着开发者可以通过设置 `stream=True` 参数来利用 Python 中的 requests 库发起请求并处理流式的响应数据。
#### 使用 Requests 实现流式 API 调用
下面是一个基于 Python 3.10 版本下通过 requests 包实现对 Langchain-Chatchat 进行流式调用的例子:
```python
import requests
def stream_chat(query: str, history: list):
url = 'http://ip:port/chat/stream'
with requests.post(
url,
headers={
'Authorization': '',
'Content-Type': 'application/json'
},
json={
"query": query,
"history": history,
"model_name": "chatglm2-6b",
"temperature": 0.7,
"prompt_name": "llm_chat"
},
stream=True
) as resp:
if resp.status_code == 200:
for line in resp.iter_lines():
if line:
yield line.decode('utf-8')
```
此代码片段展示了如何配置 POST 请求以启用流模式(`stream=True`),并通过迭代器逐行读取服务器返回的数据。
#### Chat 接口调用实例
除了上述流式接口外,还有常规的聊天接口可供使用。这里给出了一种简单的调用方法,适用于不涉及实时更新的应用场景[^2]:
```python
import requests
def chat(param: str, history: list) -> str:
url = 'http://ip:port/chat/chat'
response = requests.post(
url,
headers={'Authorization': '', 'Content-Type': 'application/json'},
json={
"query": param,
"history": history,
"model_name": "chatglm2-6b",
"temperature": 0.7,
"prompt_name": "llm_chat"
}
)
if response.status_code == 200:
return response.json() # 修改为 .json() 方法获取 JSON 响应体
else:
raise Exception(f"Error {response.status_code}: {response.text}")
```
注意,在这个例子中,如果服务端正常响应,则会尝试解析 JSON 格式的回复;否则抛出异常提示错误信息。
#### 自定义 API 返回格式
为了满足特定需求或者优化用户体验,可以在项目源码中的 `api.py` 文件里调整各个 API 功能对应函数内的逻辑,特别是关于 JSON 数据结构的部分。具体来说就是修改那些负责构建和发送 JSON 对象的地方,比如在 `mount_knowledge_routes` 函数内部找到相应位置进行定制化更改[^3]。
阅读全文
相关推荐


















