跳转至

集成大语言模型

点击这里,边看视频讲解 边学习

目前主流的 大语言模型 的 API调用接口 都兼容 OpenAI 标准(包含身份认证、接口协议)

所以我们开发使用这些 API 时,可以使用同样的代码,只需要配置不同的 服务商参数即可。

下面就给大家介绍一下 如何调用这些API接口。

开通账号

使用服务商提供的大语言模型的API,首先当然是要开通账号了。

这个不用多说,大家都会。

开通大模型服务

开通了帐号之后,还要开通大模型服务

另外,OpenAI 标准 的 API调用, 必须使用 API key ,所以要创建一个。

下面介绍的这些厂商 , 大都有一定的免费额度, 简单试用 可以不用充值。

而 DeepSeek, 目前是必须要充值的,可以充最低额度的钱先试用一下。

字节 火山方舟

点击这里,进入 字节 火山方舟的界面


然后 点击左侧菜单的 系统管理 -> API Key 管理 ,点击 创建 API Key 如果没有实名认证,需要先实名认证

然后根据界面引导 选择开通模型,可以选择 一键开通所有模型。


可以在左侧菜单的 系统管理 -> 开通管理 选择开通模型

点击这些模型,可以查看详细信息

阿里 百炼

点击这里,进入阿里云百炼


然后,点击右下角图标 , 开通百炼大模型服务,并领取免费额度

然后 创建 API Key


这里给出了 阿里支持的模型 列表

百度千帆

点击这里,进入 百度智能云 控制台界面

然后 点击这里,进入 API Key 管理界面

点击 创建 API Key


这个网址,是 百度千帆大模型开发平台 的文档中心,

比如要看图片上传接口 , 可以左侧菜单, 推理服务API -> 推理服务API V2 -> 多模态

然后 右侧目录 图片 Base64 编码输入

DeepSeek

点击这里, 进入 DeepSeek 平台管理界面

充值,然后创建 API KEY

示例代码

文本终端界面

import requests,json

class LLM_SP:    
    url     = "https://ark.cn-beijing.volces.com/api/v3/chat/completions"
    api_key = "你的  api key"
    model   = "doubao-1-5-thinking-pro-250415" 
    # doubao-1-5-lite-32k-250115 
    # doubao-1-5-thinking-pro-250415
    # doubao-1.5-vision-lite-250315

def read_file_base64(file_path):
    import base64
    with open(file_path, 'rb') as file:
        file_content = file.read()
        base64_encoded = base64.b64encode(file_content).decode('utf-8')
        return base64_encoded

def openai_send(llm, prompt, temperature=None):

    data = {
        "model": llm.model,
        "messages": [
            {"role": "user", "content": prompt}
        ],
        "stream": True
    }

    if temperature is not None:
        data["temperature"] = temperature

    response = requests.post(
        llm.url,
        headers={ "Authorization": f"Bearer {llm.api_key}"},
        json=data,
        stream=True,
    )

    if response.status_code == 200:
        for line in response.iter_lines():
            if line:
                try:
                    json_string = line.decode('utf-8').split('data: ')[1]
                    if json_string != '[DONE]':
                        json_data = json.loads(json_string)
                        content = json_data['choices'][0]['delta'].get('content')
                        if content:
                            print(content, end='', flush=True)
                except (json.JSONDecodeError, KeyError, IndexError) as e:
                    print(f"Error processing line: {line}, error: {e}")
        print()
    else:
        print(f"Error: {response.status_code} - {response.text}")

# 示例问题 1
question_1  = """

以高三学生标准 给下面的议论文作文 评语

    挫折使人走上成功
 

  人生中的挫折并不可怕,可怕的是我们不能直面挫折。请相信人只有战胜了挫折才会明白生命的意义。正如“阳光总在风雨后,请相信有彩虹”。请将挫折视为垫脚石吧,让我们直面挫折、战胜自我、走向成功!
"""


# # 示例问题 2
# question_2  = [
#     { "type": "text", "text": "以高三学生标准给下面的议论文 评语" },
#     {
#         "type": "image_url",
#         "image_url": {
#             "url": f"data:image/png;base64,{read_file_base64('2.png')}",
#         },
#     },
# ]

openai_send(LLM_SP, question_1)

Python Qt 图形界面

下面示例代码实现了 PySide6 图形界面 发送 文本数据 给大模型服务。

代码使用了 hyqt 这个库,方便图形界面的开发。 需要先执行 pip install hyqt 安装。

如果还需要 图形界面支持 图片嵌入发送 的参考代码 , 请将 这个视频分享到朋友圈(点击打开),截屏微信发给 byhy44

import requests, json, threading
from hyqt import *

from PySide6.QtCore import Signal,QObject
class MySignals(QObject):
    ai_respond = Signal(str)
global_ms = MySignals()   # 实例化


class LLM_SP:    
    url     = "https://ark.cn-beijing.volces.com/api/v3/chat/completions"
    api_key = "你的  api key"
    model   = "doubao-1-5-thinking-pro-250415" 
    # doubao-1-5-lite-32k-250115 
    # doubao-1-5-thinking-pro-250415
    # doubao-1.5-vision-lite-250315

def openai_send(llm, prompt, temperature=None):

    data = {
        "model": llm.model,
        "messages": [
            {"role": "user", "content": prompt}
        ],
        "stream": True
    }

    if temperature is not None:
        data["temperature"] = temperature

    response = requests.post(
        llm.url,
        headers={ "Authorization": f"Bearer {llm.api_key}"},
        json=data,
        stream=True,
    )

    if response.status_code == 200:
        for line in response.iter_lines():
            if line:
                try:
                    json_string = line.decode('utf-8').split('data: ')[1]
                    if json_string != '[DONE]':
                        json_data = json.loads(json_string)
                        content = json_data['choices'][0]['delta'].get('content')
                        if content:
                            global_ms.ai_respond.emit(content)
                except (json.JSONDecodeError, KeyError, IndexError) as e:
                    print(f"Error processing line: {line}, error: {e}")
        print()
    else:
        print(f"Error: {response.status_code} - {response.text}")


app = QApplication()

win =  Column(
    s__(windowTitle='大模型对话', bgColor='aliceblue', size=(1200,700),
        styleSheet='*{font-size: 14px;font-family: consolas, 微软雅黑; color: DimGray;}',),   

    # 操作栏
    Row(s__(vExpanding=False), 
        btnSend := ButtonNB('发送', onClick=lambda:sendQuestion()),
        ButtonNB('清空问题', onClick=lambda:te_question.clear()),
        ButtonNB('清空回答', onClick=lambda:tb_answer.clear()),
    ),

    # 问题
    te_question := TextArea(hExpanding=True, vExpanding=True, 
            border='1px solid lightgray'),

    # 回答
    tb_answer := TextBrowser(
        hExpanding=True, vExpanding=True, 
            border='1px solid lightblue', 
    ),
)

def sendQuestion():
    mdTxt = te_question.toMarkdown()
    threading.Thread(target=openai_send, args=(LLM_SP, mdTxt)).start()

def getStreamToken(token):
    tb_answer.insertPlainText(token)
    tb_answer.ensureCursorVisible()

global_ms.ai_respond.connect(getStreamToken)   

win.show()
app.exec()