OpenAI的接口有多种不同的类型,这里介绍一种常见的文本生成类型的接口。
输入参数:
- prompt:要生成的文本的上下文。这可以是一个字符串,表示要生成的文本的前缀或后缀。
- max_tokens:生成的文本的最大长度。
- temperature:生成文本的随机性程度。值越大,生成的文本越随机;值越小,生成的文本越保守。
返回值:
- 生成的文本。这将是一个字符串。
例如,你可以使用以下代码调用OpenAI的文本生成接口:
response = openai.Completion.create(
engine="text-davinci-002",
prompt="Once upon a time, in a land far far away, there lived a young princess named Aurora. She was known for her beauty and kindness, and was loved by all who knew her. One day, Aurora was out walking in the forest when she came across a handsome prince. The prince was lost and alone, and Aurora took pity on him. She offered to help him find his way home, and the two of them set off together. As they walked, they fell in love and decided to get married. They lived happily ever after, ruling over the kingdom with kindness and fairness.",
max_tokens=1024,
temperature=0.5
)
generated_text = response["choices"][0]["text"]
在这个例子中,我们向OpenAI发出了一个请求,要求它使用文本生成引擎 "text-davinci-002" 生成一段文本,文本的上下文是一个童话故事的开头,最多生成 1024 个令牌(即单词),并使用 temperature=0.5 的随机性。返回的结果是生成的文本。