大模型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调用。

相关推荐
紫雾凌寒2 小时前
计算机视觉应用|自动驾驶的感知革命:多传感器融合架构的技术演进与落地实践
人工智能·机器学习·计算机视觉·架构·自动驾驶·多传感器融合·waymo
sauTCc2 小时前
DataWhale-三月学习任务-大语言模型初探(一、二、五章学习)
人工智能·学习·语言模型
暴力袋鼠哥2 小时前
基于深度学习的中文文本情感分析系统
人工智能·深度学习
视觉语言导航2 小时前
RAG助力机器人场景理解与具身操作!EmbodiedRAG:基于动态三维场景图检索的机器人任务规划
人工智能·深度学习·具身智能
岱宗夫up2 小时前
《加快应急机器人发展的指导意见》中智能化升级的思考——传统应急设备智能化升级路径与落地实践
人工智能·aigc
訾博ZiBo2 小时前
AI日报 - 2025年3月12日
人工智能
龚大龙2 小时前
机器学习(李宏毅)——Auto-Encoder
人工智能·机器学习
snow@li3 小时前
AI问答:transformer 架构 / 模型 / 自注意力机制实现序列数据的并行处理 / AI的底层
人工智能·深度学习·transformer
cv2016_DL3 小时前
siglip2推理教程
人工智能·transformer
小枫小疯4 小时前
Pytorch 转向TFConv过程中的卷积转换
人工智能·pytorch·python