上面的代码单独用一个方法做
时间: 2024-02-05 11:10:25 浏览: 30
可以将上面的代码封装成一个方法,方便调用和复用。以下是一个示例方法:
```python
import openai
import json
def generate_response(prompt):
# Set up OpenAI API credentials
openai.api_key = "YOUR_API_KEY"
# Define the prompt
prompt_text = f"Prompt: {prompt}\nResponse:"
# Generate the completions
response = openai.Completion.create(
engine="text-davinci-002",
prompt=prompt_text,
max_tokens=60,
n=1,
stop=None,
temperature=0.7,
)
# Extract the generated text from the response
generated_text = response.choices[0].text.strip()
# Return the generated text as a string
return generated_text
```
这个方法接受一个字符串作为输入,并返回一个字符串作为输出,表示 AI 对该输入的回应。要使用这个方法,只需将所需的输入作为参数传递给 `generate_response` 方法即可,例如:
```python
prompt = "What is the meaning of life?"
response = generate_response(prompt)
print(response)
```
输出:
```
To find meaning in life, one must look within themselves and what they value most. It is different for everyone, but ultimately it is about finding purpose and fulfillment in one's existence.
```