3

一日一技:如何同时使用多个GPT的API Key?

 9 months ago
source link: https://www.kingname.info/2023/09/03/multi-gpt-key/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一日一技:如何同时使用多个GPT的API Key?

2023-09-03

23

651

2 分钟

相信很多同学或多或少都在Python中使用过GPT API,通过Python安装openai库,来调用GPT模型。

OpenAI官方文档中给出了一个示例,如下图所示:

20230903093758.png

如果你只有一个API账号,那么你可能不觉得这样写有什么问题。但如果你想同时使用两个账号怎么办?

有些同学可能知道,微软的Azure也提供GPT接口,在Python中也需要通过openai库来调用,它的调用示例为:

20230903094110.png

当你全局设置了openai.api_type = 'azure'以后,你怎么同时使用OpenAI的GPT接口?

这两个文档中给出的示例写法,都是全局写法,一但设定以后,在整个运行时中,所有调用GPT接口的地方,都会使用这里设置的参数:

import openai

openai.xx = yy

有些同学不知道怎么在Python SDK中同时使用多个账号,于是他们只有使用GPT的Rest HTTP接口,自己封装一个函数来发起请求从而切换不同的账号。放弃了Python SDK提供的各种便利。

但实际上,根本没有那么麻烦。在openai模块里面,天然就可以切换多个账号。虽然文档里面没有写,但是我们可以通过函数签名来找到这种方法。

如下图所示,在PyCharm中,随便写一段调用openai模块的代码,然后Windows按下键盘的Ctrl,MacOS按下键盘的Command,并鼠标左键点击create函数:

20230903094837.png

跳转到的函数里面,还有一个create函数,继续按上面的方法跳入,如下图所示:

20230903094937.png

接下来,你就会看到这个create函数能够接受的参数里面,包含了几个很熟悉的名字:

20230903095029.png

也就是说,当你想同时调用多个账号时,不需要在一开始给openai设置对应的参数,你只需要在调用.create函数的时候,把对应的API参数传入就可以了。示例代码如下:

import openai

# 使用OpenAI账号1
response1 = openai.ChatCompletion.create(
engine="chatgpt",
messages=messages,
temperature=0.9,
max_tokens=800,
top_p=0.95,
frequency_penalty=0,
presence_penalty=0,
api_key='xxxxxxxx', # 在这里传入API Key
stop=["<|im_end|>"])


# 使用OpenAI账号2
response2 = openai.ChatCompletion.create(
engine="chatgpt16k",
messages=messages,
temperature=0.9,
max_tokens=800,
top_p=0.95,
frequency_penalty=0,
presence_penalty=0,
api_key='yyyyyyyyy', # 在这里传入API Key
stop=["<|im_end|>"])


# 使用Azure OpenAI 账号
response3 = openai.ChatCompletion.create(
engine="gpt4",
messages=messages,
temperature=0.9,
max_tokens=800,
top_p=0.95,
frequency_penalty=0,
presence_penalty=0,
api_key='zzzzzzz', # 在这里传入API Key
api_base='https://xxx.openai.azure.com/',
api_type="azure",
api_version='2023-05-15',
stop=["<|im_end|>"])

使用这种方法,我们就可以在一个程序里面同时使用多个GPT账号了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK