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

相关推荐
小宋102114 分钟前
4 万 Star 的开源 ChatGPT 桌面端:用 Jan 把电脑变成离线 AI 工作站
人工智能·chatgpt·开源·jan
searchforAI15 分钟前
啥是LLM?大语言模型从原理到选型的完整科普
人工智能·科技·深度学习·ai·语言模型·知识图谱·agent
我就是全世界15 分钟前
具身智能难现“ChatGPT时刻”:缺统一范式,更缺优质数据
人工智能·chatgpt·机器人
bryant_meng17 分钟前
【Transformer】Why ChatGPT Is Decoder-Only
深度学习·chatgpt·transformer·decoder
NQBJT20 分钟前
告别复制粘贴!NQ-Assistant:一键将 DeepSeek/ChatGPT/Claude 回复导出为精美 Word 文档
人工智能
朱大喜1 小时前
数据可视化工具选型:matplotlib、Plotly 与 ECharts
人工智能
染指11107 小时前
26.RAG进阶(Advanced RAG)-假设性问题索引
人工智能·windows·agent·rag·advanced rag
闵孚龙7 小时前
动态图机制:为什么 PyTorch 调试起来更舒服
人工智能·pytorch·python
甲维斯8 小时前
还要啥Codex!DeepSeek接入Zcode远程连接!
人工智能
百胜软件@百胜软件8 小时前
百胜软件亮相“AI消费新生活”主题日活动,AI智能运营平台入选市级案例征集
人工智能·生活·零售数字化·数智中台·珠宝行业