Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏多维度架构

第 21 章 OpenAI

目录

21.1. ChatGPT
21.1.1. gpt-3.5-turbo
21.1.2. 流式输出
21.2. Embedding

21.1. ChatGPT

21.1.1. gpt-3.5-turbo

			
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##############################################
# Home	: https://www.netkiller.cn
# Author: Neo <netkiller@msn.com>
# Upgrade: 2023-06-25
##############################################
import os
import openai

# openai.api_key = os.getenv("OPENAI_API_KEY")
openai.api_key = "sk-DNsMaVmxxIm3Xp7ZTZrZw2mcGgDF1nev5OT3BlbkFJ8wb3Y8"

completion = openai.ChatCompletion.create(
    model="gpt-3.5-turbo", messages=[{"role": "user", "content": "谁是netkiller?"}]
)
print(openai.Model.list())
print(completion)
response = completion.choices[0].message.content
print(response)	
			
			

21.1.2. 流式输出

			
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##############################################
# Home	: https://www.netkiller.cn
# Author: Neo <netkiller@msn.com>
# Upgrade: 2023-10-07
##############################################
import openai

# openai.api_key = os.getenv("OPENAI_API_KEY")
openai.api_key = "sk-UB5SdJmlbkFJnPC9GjYuY0sAEHzyuotulWBFgT3BQ70vTnKr"

question = "netkiller 写了那些电子书?"

response = openai.ChatCompletion.create(
    model="gpt-4",
    messages=[{"role": "user", "content": question}],
    stream=True,
)

print(f"问题:{question}")

for chunk in response:
    content = chunk["choices"][0].get("delta", {}).get("content")
    if content is not None:
        print(content, end="")

print()