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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| import requests
class ChatGpt(): def __init__(self, api_key): """ 初始化ChatGpt实例 :param api_key: ChatGpt秘钥 """ self.headers = { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}" } self.proxies = { 'http': 'http://127.0.0.1:7890/', 'https': 'http://127.0.0.1:7890/' }
def _request(self, method, url, json=None): """ 发送 HTTP 请求 :param method: 请求方法 :param url: 请求的 URL :param json: 请求体 :return: 响应体 """ response = requests.request(method, url, headers=self.headers, json=json, proxies=self.proxies) response.raise_for_status() return response.json()
def chat(self, question): """ 聊天 :param question: 想要提问的问题 :return: 问题答案 """ url = "https://api.openai.com/v1/chat/completions" json = { "model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": f"{question}"}] } response = self._request('POST', url, json=json) return response['choices'][0]['message']['content']
def generate_images(self, prompt, n=1, size='1024x1024'): """ 根据提示创建图像 :param prompt: 所需图像的文本描述。最大长度为 1000 个字符。 :param n: 要生成的图像数。必须介于 1 和 10 之间。 :param size: 生成图像的大小。必须是256x256、512x512、 1024x1024之一。 :return: 图像链接列表 """ url = 'https://api.openai.com/v1/images/generations' json = { "prompt": prompt, "n": n, "size": size } response = self._request('POST', url, json=json) return [url['url'] for url in response['data']]
def transcribe_audio(self, file): """ 将音频转换为文本 :param file: 要转录的音频文件,采用以下格式之一:mp3、mp4、mpeg、mpga、m4a、wav 或 webm。 :return: 文本内容 """ url = 'https://api.openai.com/v1/audio/transcriptions' json = { "file": f"{file}", "model": "whisper-1" } response = self._request('POST', url, json=json) return response['text']
if __name__ == '__main__': gpt = ChatGpt(api_key='YOUR_API_KEY') print(gpt.generate_images('小猫'))
|