API调用指南-PYTHON
步骤1:安装Python和requests库
首先,确保已安装了Python。然后,使用以下命令安装requests库:
pip install requests
如果尚未安装pip,可以使用以下命令安装:
python -m ensurepip
python -m pip install --upgrade pip
步骤2:编写Python代码
使用Python编写HTTP请求的代码。以下是一个简单的示例:
import requests
import json
url = "https://brain-llm-saas.emotibot.com/api/v1/model/chat_completions_stream_endpoint?apiKey={key}"
payload = json.dumps({
"model_uid": "DokGt2E3jLrFWhyOsTcmKCif4RIu790glYanNVzpxSqdevPwbX",
"runtime_parameters": {
"max_tokens": 2096,
"top_p": 0.7,
"top_k": 30,
"temperature": 1,
"messages": [
{
"role": "user",
"content": "你好,北京什么气候"
},
{
"role": "assistant",
"content": "北京是亚热带气候。"
},
{
"role": "user",
"content": "那上海呢?"
}
]
},
})
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers = headers, data = payload, stream=True)
for x in response.iter_content(1024):
print(json.loads(x.decode("utf-8")))
步骤3:运行Python代码
在命令行中,将以下代码复制并粘贴到一个名为http_request.py的文件中:
import requests
import json
url = "https://brain-llm-saas.emotibot.com/api/v1/model/chat_completions_stream_endpoint?apiKey={key}"
payload = json.dumps({
"model_uid": "DokGt2E3jLrFWhyOsTcmKCif4RIu790glYanNVzpxSqdevPwbX",
"runtime_parameters": {
"max_tokens": 2096,
"top_p": 0.7,
"top_k": 30,
"temperature": 1,
"messages": [
{
"role": "user",
"content": "你好,北京什么气候"
},
{
"role": "assistant",
"content": "北京是亚热带气候。"
},
{
"role": "user",
"content": "那上海呢?"
}
]
},
})
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers = headers, data = payload, stream=True)
for x in response.iter_content(1024):
print(json.loads(x.decode("utf-8")))
将文件保存到一个方便的位置(例如/path/to/http_request.py)。在命令行中导航到该文件所在的目录,然后运行以下命令:
python http_request.py
步骤4:测试API并收集数据
使用Python生成API请求,然后收集并分析数据。这可以通过使用requests库的post方法来完成。例如,以下代码段将向API发送一个POST请求并获取返回的JSON数据:
import requests
import json
url = "https://brain-llm-saas.emotibot.com/api/v1/model/chat_completions_stream_endpoint?apiKey={key}"
payload = json.dumps({
"model_uid": "DokGt2E3jLrFWhyOsTcmKCif4RIu790glYanNVzpxSqdevPwbX",
"runtime_parameters": {
"max_tokens": 2096,
"top_p": 0.7,
"top_k": 30,
"temperature": 1,
"messages": [
{
"role": "user",
"content": "你好,北京什么气候"
},
{
"role": "assistant",
"content": "北京是亚热带气候。"
},
{
"role": "user",
"content": "那上海呢?"
}
]
},
})
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers = headers, data = payload, stream=True)
for x in response.iter_content(1024):
print(json.loads(x.decode("utf-8")))
请注意,根据API的要求,这个简单的示例可能需要进行调整。例如,可能需要将请求参数的值根据具体实际场景做修改验证,或者可能需要在请求中添加其他参数。