This repository has been archived by the owner on Jun 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathopenai.py
51 lines (43 loc) · 1.51 KB
/
openai.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# -*- coding: utf-8 -*-
# @Author : LaiJiahao
# @Time : 2022/12/8 16:44
# @File : openai.py
# @Project : openAI
import random
from config import configs
import requests
import pypandoc
class OpenAi:
def __init__(self):
# 使用的模型:功能最强大的 GPT-3
self.model = "text-davinci-003"
self.url = "https://api.openai.com/v1/completions"
def get_answer(self,prompt,max_tokens,temperature):
keys = configs['keys']
key = random.choices(keys)
api_key = key[0]
if max_tokens <= 4096 and temperature <= 0.9:
if prompt:
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
# Set up the API data
data = {
"model": "text-davinci-003",
"prompt": prompt,
"max_tokens": max_tokens,
"temperature": temperature,
}
# Make the API request
response = requests.post(self.url, headers=headers, json=data)
# Print the response
answer = response.json()['choices'][0]['text']
answer = pypandoc.convert_text(answer,'html',format='md')
else:
answer= "问题不能为空"
else:
answer = '你的max_tokens或temperature值过大!'
return answer
# ai = OpenAi(prompt='你好')
# print(ai.get_answer())