Fly to the sky & Return

chatGPT api 이용 sample code 본문

프로그래밍/파이썬

chatGPT api 이용 sample code

낼은어떻게 2023. 2. 5. 11:17
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
To use the OpenAI GPT API in Python, you can use the openai library, which provides a simple Python interface to interact with the OpenAI GPT API. Here's a basic example of how you could generate text using the GPT API:
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import openai
 
# Set the OpenAI API key
openai.api_key = "YOUR_API_KEY"
 
# Define the model and prompt to use
model_engine = "text-davinci-002"
prompt = "What is the capital of France?"
 
# Generate a response to the prompt
completion = openai.Completion.create(
    engine=model_engine,
    prompt=prompt,
    max_tokens=1024,
    n=1,
    stop=None,
    temperature=0.5,
)
 
message = completion.choices[0].text
print(message)
cs

In this example, you first set your OpenAI API key using the openai.api_key property. Then, you specify the model engine to use (in this case, text-davinci-002) and the prompt you want to generate a response for. Finally, you use the openai.Completion.create method to generate a response, passing in the model engine, prompt, and other parameters as required. The generated response is then stored in the message variable, which you can print or use as desired.

Note that you'll need to sign up for an OpenAI API key to use the GPT API. You can sign up for an API key at the OpenAI website: https://beta.openai.com/signup/.