天天看點

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就行。至于怎麼注冊網上已有很多教程,這裡就不再贅述。

本次分享到此結束,喜歡的小夥伴歡迎點點關注,點點贊,點點收藏。我們下期再見!