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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| import openai
openai.api_key = "sk-" openai.api_base = "https://api_gpt4.ai-gaochao.com/v1" DEBUG = False
def gpt_api_stream(messages: list): """为提供的对话消息创建新的回答 (流式传输) gpt4长问题需要用流式传输,不然容易报错 Args: messages (list): 完整的对话消息 api_key (str): OpenAI API 密钥 Returns: tuple: (results, error_desc) """ try: response = openai.ChatCompletion.create( model='gpt-4', messages=messages, stream=True, ) completion = {'role': '', 'content': ''} for event in response: if event['choices'][0]['finish_reason'] == 'stop': if DEBUG: print(f'收到的完成数据: {completion}') break for delta_k, delta_v in event['choices'][0]['delta'].items(): if DEBUG: print(f'流响应数据: {delta_k} = {delta_v}') completion[delta_k] += delta_v messages.append(completion) msg = completion['content'] return (True, msg) except Exception as err: return (False, f'OpenAI API 异常: {err}') def gpt_api_no_stream(messages: list):
try: completion = openai.ChatCompletion.create( model="gpt-4-0613", messages=messages ) msg = None choices = completion.get('choices', None) if choices: msg = choices[0]['message']['content'] else: msg = completion['message']['content'] return (True, msg) except Exception as err: return (False, f'OpenAI API 异常: {err}') if __name__ == '__main__': prompt = 'There are 9 birds in the tree, the hunter shoots one, how many birds are left in the tree?' prompt = "鲁迅为什么暴打周树人" print("发送:", prompt) print("使用的apikey:", openai.api_key) messages = [{'role': 'user','content': prompt},] ret, msg = gpt_api_stream(messages) print("返回:", msg) if DEBUG: print("messages:", messages)
|