0% found this document useful (0 votes)
8 views2 pages

API Base

This document contains a Python script that interacts with a chat API to send messages and receive responses. It sets up the API base URL and authorization headers, defines a function to send chat messages in streaming mode, and handles the response to accumulate and print the complete answer. An example call to the function is also provided, demonstrating how to use it with a user ID and a query.

Uploaded by

qq2587231465
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

API Base

This document contains a Python script that interacts with a chat API to send messages and receive responses. It sets up the API base URL and authorization headers, defines a function to send chat messages in streaming mode, and handles the response to accumulate and print the complete answer. An example call to the function is also provided, demonstrating how to use it with a user ID and a query.

Uploaded by

qq2587231465
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

import requests

import json

# 设置 API 基础 URL 和 API 密钥

api_base = "https://gaia.yafex.cn/v1"
api_key = "你的密钥" # 替换为你的实际 API 密钥
# 定义请求头,包含鉴权信息
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}

def send_chat_message(query, user_id, conversation_id=None):


url = f"{api_base}/chat-messages"
data = {
"query": query,
"response_mode": "streaming", # 使用流式模式
"user": user_id,
"conversation_id": conversation_id or "",
"inputs": {} # 可传入特定变量值,默认空
}
response = requests.post(url, headers=headers, json=data,
stream=True)

if response.status_code == 200:
complete_answer = "" # 用于累积完整答案
for line in response.iter_lines():
if line:
# 每一行去掉前面的 `data: ` 并解析为 JSON
decoded_line = line.decode('utf-8')
if decoded_line.startswith("data: "):
json_data = decoded_line[len("data: "):]
try:
event_data = json.loads(json_data)
answer_part = event_data.get('answer', '')
complete_answer += answer_part # 累积答案部分
except ValueError as e:
print("Error decoding JSON:", e)
print("答:", complete_answer)
else:
print(f"Error: {response.status_code} - {response.text}")
# 示例调用
user_id = "abc-123" # 用户标识,需在应用内唯一
query = """问题"""
print('问:'+query)
send_chat_message(query, user_id)

You might also like