大模型07-API调用之初探,python调用GPT-API

准备工作

  1. 关于如何开通gpt账号、API功能、获取API的key,请大家自行百度,当大家看到如下界面,代表第一步的准备工作完成:
  2. 关于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调用。

相关推荐
新智元6 小时前
世界首富换人!81 岁硅谷狂人 4000 亿身价碾压马斯克,33 岁华裔才女逆袭
人工智能·openai
lingling0096 小时前
分子生物学ELN系统:如何通过衍因科技实现实验室效率革命
人工智能
AI大模型6 小时前
无所不能的Embedding(06) - 跨入Transformer时代~模型详解&代码实现
程序员·llm·agent
max5006006 小时前
实时多模态电力交易决策系统:设计与实现
图像处理·人工智能·深度学习·算法·音视频
男孩李6 小时前
浅谈代理流程自动化 (APA)
运维·人工智能·自动化
君名余曰正则6 小时前
机器学习06——支持向量机(SVM核心思想与求解、核函数、软间隔与正则化、支持向量回归、核方法)
人工智能·机器学习·支持向量机
sjr20017 小时前
从huggingface下载模型时有哪些文件?
人工智能·机器学习
moz与京7 小时前
【面试向】热门技术话题(上)
人工智能·物联网·机器学习·面试·web3·区块链·元宇宙
wyfwyf___7 小时前
5G+IoT+AI:新质工业新图景,从预测性维护到全链路数智化
人工智能·科技·物联网·5g·信息与通信
gptplusplus8 小时前
AI智能体(Agent):从“辅助决策”到“自主行动”,重新定义下一个商业时代
人工智能