forked from chatanywhere/GPT_API_free
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.py
41 lines (33 loc) · 1.1 KB
/
demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from openai import OpenAI
client = OpenAI(
# defaults to os.environ.get("OPENAI_API_KEY")
api_key="YOUR API KEY",
base_url="https://api.chatanywhere.tech/v1"
)
# 非流式响应
def gpt_35_api(messages: list):
"""为提供的对话消息创建新的回答
Args:
messages (list): 完整的对话消息
"""
completion = client.chat.completions.create(model="gpt-3.5-turbo", messages=messages)
print(completion.choices[0].message.content)
def gpt_35_api_stream(messages: list):
"""为提供的对话消息创建新的回答 (流式传输)
Args:
messages (list): 完整的对话消息
"""
stream = client.chat.completions.create(
model='gpt-3.5-turbo',
messages=messages,
stream=True,
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
if __name__ == '__main__':
messages = [{'role': 'user','content': '鲁迅和周树人的关系'},]
# 非流式调用
# gpt_35_api(messages)
# 流式调用
gpt_35_api_stream(messages)