之前写过一篇 《Python 调用API访问Chatgpt》,由于没有采用stream=True的方式,而且max_tokens也设置的比较小,导致在获取答案的时候会经常不完整。于是重新写一个stream方式的。

# -*- coding: utf-8 -*-
"""
Created on Thu Apr  6 21:59:11 2023

@author: F
"""

import openai
import os
import time

openai.api_key = ""

def askChatGPT(content):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "assistant", "content": content}
        ],
        # temperature=0.1,
        max_tokens=1000,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0,
        stream=True
    )
    print(response)
    ans = ''
    for r in response:
        if 'content' in r.choices[0].delta:
          ans += r.choices[0].delta['content']
    return ans


if __name__ == '__main__':
    ask = '你有意识吗'
    ans = askChatGPT(ask)
    content = u'{}'.format(ans)
    print('Q: ', ask)
    print('A: ', content)