OpenAI的API调用之初探,python调用GPT-API(交互式,支持多轮对话)

准备工作

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

image.png

需求场景

有两个场景,单轮对话和多轮对话。

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")

效果呈现

image.png

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

大模型资源分享

“最先掌握 AI 的人,相较于较晚掌握 AI 的人而言,将具备竞争优势。”这句话放在计算机、互联网以及移动互联网的开局时期,同样适用。

我在一线互联网企业工作长达十余年,期间指导过众多同行后辈,助力许多人实现了学习与成长。为此,我将重要的 AI 大模型资料,包括 AI 大模型入门学习思维导图、精品 AI 大模型学习书籍手册、视频教程以及实战学习等录播视频免费分享出来。
在这里插入图片描述

一、全套 AGI 大模型学习路线

AI 大模型时代的精彩学习之旅:从根基铸就到前沿探索,牢牢掌握人工智能核心技能!

在这里插入图片描述

二、640 套 AI 大模型报告合集

此套涵盖 640 份报告的精彩合集,全面涉及 AI 大模型的理论研究、技术实现以及行业应用等诸多方面。无论你是科研工作者、工程师,还是对 AI 大模型满怀热忱的爱好者,这套报告合集都将为你呈上宝贵的信息与深刻的启示。

在这里插入图片描述

三、AI 大模型经典 PDF 书籍

伴随人工智能技术的迅猛发展,AI 大模型已然成为当今科技领域的一大热点。这些大型预训练模型,诸如 GPT-3、BERT、XLNet 等,凭借其强大的语言理解与生成能力,正在重塑我们对人工智能的认知。而以下这些 PDF 书籍无疑是极为出色的学习资源。
在这里插入图片描述
在这里插入图片描述

阶段 1:AI 大模型时代的基础认知

  • 目标:深入洞悉 AI 大模型的基本概念、发展历程以及核心原理。

  • 内容

    • L1.1 人工智能概述与大模型起源探寻。
    • L1.2 大模型与通用人工智能的紧密关联。
    • L1.3 GPT 模型的辉煌发展历程。
    • L1.4 模型工程解析。
    • L1.4.1 知识大模型阐释。
    • L1.4.2 生产大模型剖析。
    • L1.4.3 模型工程方法论阐述。
    • L1.4.4 模型工程实践展示。
    • L1.5 GPT 应用案例分享。

阶段 2:AI 大模型 API 应用开发工程

  • 目标:熟练掌握 AI 大模型 API 的运用与开发,以及相关编程技能。

  • 内容

    • L2.1 API 接口详解。
    • L2.1.1 OpenAI API 接口解读。
    • L2.1.2 Python 接口接入指南。
    • L2.1.3 BOT 工具类框架介绍。
    • L2.1.4 代码示例呈现。
    • L2.2 Prompt 框架阐释。
    • L2.2.1 何为 Prompt。
    • L2.2.2 Prompt 框架应用现状分析。
    • L2.2.3 基于 GPTAS 的 Prompt 框架剖析。
    • L2.2.4 Prompt 框架与 Thought 的关联探讨。
    • L2.2.5 Prompt 框架与提示词的深入解读。
    • L2.3 流水线工程阐述。
    • L2.3.1 流水线工程的概念解析。
    • L2.3.2 流水线工程的优势展现。
    • L2.3.3 流水线工程的应用场景探索。
    • L2.4 总结与展望。

阶段 3:AI 大模型应用架构实践

  • 目标:深刻理解 AI 大模型的应用架构,并能够实现私有化部署。

  • 内容

    • L3.1 Agent 模型框架解读。
    • L3.1.1 Agent 模型框架的设计理念阐述。
    • L3.1.2 Agent 模型框架的核心组件剖析。
    • L3.1.3 Agent 模型框架的实现细节展示。
    • L3.2 MetaGPT 详解。
    • L3.2.1 MetaGPT 的基本概念阐释。
    • L3.2.2 MetaGPT 的工作原理剖析。
    • L3.2.3 MetaGPT 的应用场景探讨。
    • L3.3 ChatGLM 解析。
    • L3.3.1 ChatGLM 的特色呈现。
    • L3.3.2 ChatGLM 的开发环境介绍。
    • L3.3.3 ChatGLM 的使用示例展示。
    • L3.4 LLAMA 阐释。
    • L3.4.1 LLAMA 的特点剖析。
    • L3.4.2 LLAMA 的开发环境说明。
    • L3.4.3 LLAMA 的使用示例呈现。
    • L3.5 其他大模型介绍。

阶段 4:AI 大模型私有化部署

  • 目标:熟练掌握多种 AI 大模型的私有化部署,包括多模态和特定领域模型。

  • 内容

    • L4.1 模型私有化部署概述。
    • L4.2 模型私有化部署的关键技术解析。
    • L4.3 模型私有化部署的实施步骤详解。
    • L4.4 模型私有化部署的应用场景探讨。

学习计划:

  • 阶段 1:历时 1 至 2 个月,构建起 AI 大模型的基础知识体系。
  • 阶段 2:花费 2 至 3 个月,专注于提升 API 应用开发能力。
  • 阶段 3:用 3 至 4 个月,深入实践 AI 大模型的应用架构与私有化部署。
  • 阶段 4:历经 4 至 5 个月,专注于高级模型的应用与部署。
  • 28
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值