天天看点

Python 调用GPT-3 API访问ChatGPT模型

近来ChatGPT也是挺火热的,本人也了解了下,确实挺有趣,挺有帮助。在这里记录一下在Python中如何使用ChatGPT。

实际上,Python如何使用CahtGPT也是个问题,那我们可以来直接询问ChatGPT,让它给出这个答案。以下是对话内容:

Python 调用GPT-3 API访问ChatGPT模型
Python 调用GPT-3 API访问ChatGPT模型

那接下来我们就按照ChatGPT给出的示例来实现:

安装OpenAI:

pip install openai
           

示例:

import openai

# OpenAI API
openai.api_key="you_api_key"

# 使用text-davinci-002或003
model_engine="text-davinci-003"

# 想要询问的话
prompt = "How do you think about the game League of Legends?"

completion = openai.Completion.create(
    engine=model_engine,
    prompt=prompt,max_tokens=1024,
    n=1,
    stop=None,
    temperature=0.5)

Response = completion.choices[0].text
print(Response)
           
# output

I think League of Legends is an incredibly popular and engaging game that offers a lot of strategic depth and replayability. It has a huge and diverse player base, and the game is constantly evolving and improving. The game also has a vibrant esports scene, with many professional teams competing in tournaments around the world. Overall, I think League of Legends is 
a great game and a great way to spend time with friends.
           
# 想要询问的话
prompt = "What is Python?"

completion = openai.Completion.create(
    engine=model_engine,
    prompt=prompt,max_tokens=1024,
    n=1,
    stop=None,
    temperature=0.5)

Response = completion.choices[0].text
print(Response)


# output

Python is a high-level, general-purpose programming language used for web development, app development, data science, artificial intelligence, and more. It is a very popular programming language and is known for its easy-to-learn syntax and readability. Python can also be extended to other programming languages like C, C++, and Java. Python is used widely in the software development and data science industries.
           
# 想要询问的话
prompt = "英雄联盟最伟大的选手是谁?"

completion = openai.Completion.create(
    engine=model_engine,
    prompt=prompt,max_tokens=1024,
    n=1,
    stop=None,
    temperature=0.5)

Response = completion.choices[0].text
print(Response)


# output

英雄联盟最伟大的选手没有统一的评定标准,每个人都有自己的看法,但是有一些选手被公认为是当今最伟大的选手,包括Faker(韩服SKT T1)、Uzi(RNG)、Doublelift(TL)、Mata(KT)、PawN(KT)、Clearlove(EDG)等。
           

其中api_key需要注册登录OpenAI网站,然后申请一个属于自己的API Keys就行。至于怎么注册网上已有很多教程,这里就不再赘述。

本次分享到此结束,喜欢的小伙伴欢迎点点关注,点点赞,点点收藏。我们下期再见!