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

相关推荐
浠寒AI21 分钟前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python
weixin_505154461 小时前
数字孪生在建设智慧城市中可以起到哪些作用或帮助?
大数据·人工智能·智慧城市·数字孪生·数据可视化
Best_Me071 小时前
深度学习模块缝合
人工智能·深度学习
YuTaoShao1 小时前
【论文阅读】YOLOv8在单目下视多车目标检测中的应用
人工智能·yolo·目标检测
算家计算2 小时前
字节开源代码模型——Seed-Coder 本地部署教程,模型自驱动数据筛选,让每行代码都精准落位!
人工智能·开源
伪_装2 小时前
大语言模型(LLM)面试问题集
人工智能·语言模型·自然语言处理
gs801402 小时前
Tavily 技术详解:为大模型提供实时搜索增强的利器
人工智能·rag
music&movie2 小时前
算法工程师认知水平要求总结
人工智能·算法
量子位3 小时前
苹果炮轰推理模型全是假思考!4 个游戏戳破神话,o3/DeepSeek 高难度全崩溃
人工智能·deepseek
黑鹿0223 小时前
机器学习基础(四) 决策树
人工智能·决策树·机器学习