准备工作
- 关于如何开通gpt账号、API功能、获取API的key,请大家自行百度,当大家看到如下界面,代表第一步的准备工作完成:
- 关于python的环境安装以及OpenAI 第三方库的安装: pip list

需求场景
有两个场景,单轮对话和多轮对话。
1.prompt的输入:
能够支持从文件路径下直接读取已经准备好的prompt(通常是比较复杂的,有准备的),同时能够支持实时对话输入。
2.计算输入prompt的token,根据每个版本的gpt接口token限制给出可用的model列表
3.GPT返回的对话结果能够保存文件到本地
单轮对话的实现
1.引入需要的包
javascript
import os
import tiktoken
import inquirer
import datetime
from openai import OpenAI
from common.openapi_invoke import openapi_invoke, openapi_choice_model
2.获取基础参数
ini
client = OpenAI()
#计算token的方法
encoding = tiktoken.get_encoding("cl100k_base")
#取api-key,为了防止泄露,大家可以配置在环境变量中
client.api_key = os.getenv("OPENAI_API_KEY")
3.输入输出的声明
ini
# 获取input目录下的所有txt文件
input_dir = "input"
txt_files = [os.path.join(input_dir, f) for f in os.listdir(input_dir) if
os.path.isfile(os.path.join(input_dir, f)) and f.endswith('.txt')]
# 定义结果输出目录,使用时间戳
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
output_dir = "output"
output_file = f"{timestamp}.txt"
4.prompt方式选择
ini
prompt_type = input("\n请选择:\n1.选择已有prompt\n2.直接进行对话\n")
if prompt_type == "1":
prompt = prompt_read()
else:
prompt = input("\nprompt:\n")
5.api的调用
ini
selected_model = openapi_choice_model(prompt)
dialogue = openapi_invoke(prompt, selected_model)
6.获取api的对话返回并存储
python
with open(os.path.join(output_dir, output_file), 'w', encoding='utf-8') as file:
file.write(f"Input Content:\n{prompt}\n\nOutput Dialogue:\n{dialogue}")
交互式prompt文件读取选择的方法定义
ini
def prompt_read():
# 用户选择需要的prompt
questions = [inquirer.List('file',
message="Choose a file",
choices=txt_files,
carousel=True
)]
answers = inquirer.prompt(questions)
selected_file = answers['file']
# 读取用户选择的文件
with open(selected_file, 'r', encoding='utf-8') as file:
prompt_file = file.read()
return prompt_file
model选择的方法定义
ini
def openapi_choice_model(question):
# 计算token数量
token_count = len(encoding.encode(question))
# 定义模型列表,每个模型都有一个最大的token数限制
models = [
{"name": "gpt-3.5-turbo-0613", "max_tokens": 4000},
{"name": "gpt-3.5-turbo-16k-0613", "max_tokens": 16300},
{"name": "gpt-4-0613", "max_tokens": 8100},
{"name": "gpt-4-1106-preview", "max_tokens": 128000},
# 添加更多模型...
]
# 找出所有能处理该token数量的模型
suitable_models = [model for model in models if token_count <= model["max_tokens"]]
if not suitable_models:
print(f"No suitable model found for prompt with {token_count} tokens.")
else:
# 列出所有符合条件的模型,让用户选择
questions = [inquirer.List('model',
message="Choose a model",
choices=[model["name"] for model in suitable_models],
carousel=True
)]
answers = inquirer.prompt(questions)
selected_model = answers['model']
return selected_model
api接口调用的定义
python
def openapi_invoke(question, selected_model):
global dialogue
# 调用用户选择的模型生成对话
try:
response = client.chat.completions.create(
model=selected_model,
# 短语效应(在-2.0至2.0之间)
# frequency_penalty=,
# 阻止调整(在-2.0至2.0之间)
# presence_penalty=,
# 最大令牌
# max_tokens=,
# 控制采样(在0和1之间)
# top_p=,
# 文风的温度(温度的范围是从0到1)
# temperature=,
messages=[
{"role": "user", "content": question},
]
)
# 获取对话内容
dialogue = response.choices[0].message.content
print(dialogue)
print("\n--Token usage--")
print(f"Input tokens: ", response.usage.prompt_tokens)
print(f"Output tokens: ", response.usage.completion_tokens)
print(f"Total tokens: ", response.usage.total_tokens)
except Exception as exc:
print("openai执行异常:", exc)
return dialogue
多轮对话
其他逻辑和单轮对话的实现逻辑是一样的,核心在于如下的代码:
swift
# 多轮对话
while True:
question = input("\n请按照prompt提示输入,若输入exit退出\n")
dialogues_list.append("question:\n" + question + "\n")
if question == "exit":
break
dialogue = openapi_invoke(question, selected_model)
if dialogue.strip() == "":
print("openapi调用响应无返回值")
break
else:
dialogues_list.append("answer:\n" + dialogue + "\n")
效果呈现

以上就完成了我们简单的gpt的api调用。