【使用LLM搭建系统】1语言模型,提问范式与 Token

一、环境配置

  • API key 和库的加载
python 复制代码
!pip install zhipuai
!pip install langchain
!pip install --upgrade tiktoken
python 复制代码
import os
from zhipuai import ZhipuAI
# import tiktoken 这个后面没用到,若您对其用处感兴趣,可以参考本文以了解相关内容:https://zhuanlan.zhihu.com/p/629776230

# from dotenv import load_dotenv, find_dotenv
# _ = load_dotenv(find_dotenv()) # 读取本地的.env环境文件。(推荐后续使用这种方法,将 key 放在 .env 文件里。保护自己的 key)

key = "f5cd91f2528fed334b9dfd75015791c3.GuLdvM9tXWrGQnAg"
client = ZhipuAI(api_key = key)
python 复制代码
# 官方文档写法 https://platform.openai.com/overview

def get_completion(prompt, model="glm-3-turbo"):
    """
    使用 OpenAI 的模型生成聊天回复。

    参数:
    prompt: 用户的输入,即聊天的提示。
    model: 使用的模型,默认为"gpt-3.5-turbo"。
    """
    messages = [{"role": "user", "content": prompt}]
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=0,
    )
    return response.choices[0].message.content # 模型生成的回复

二、尝试向模型提问并得到结果

  • 语言模型类型
    • 基础语言模型(Base LLM):通过预测下一个词来训练。
    • 指令微调语言模型(Instruction Tuned LLM):在基础模型上进一步训练,以遵循指令。
python 复制代码
response = get_completion("中国的首都是哪里?")
print(response)

三、Tokens

  • Token 概念
    • LLM 将输入文本转换为 token 序列,每个 token 代表常见的字符序列。
    • Token 限制是输入 Prompt 和输出 completion 的 token 数之和。
    • ChatGPT3.5-turbo 的 token 上限是 4096。

四、Helper function 辅助函数 (提问范式)

  • 提问范式
    • System 信息:指定模型的规则和回答准则。
    • Assistant 信息:具体指令。
  • 辅助函数
    • get_completion:生成聊天回复。
    • get_completion_from_messages:支持更多参数的自定义访问 OpenAI GPT3.5。
    • get_completion_and_token_count:生成聊天回复,并返回使用的 token 数量。
python 复制代码
def get_completion_from_messages(messages, 
                                 model="glm-3-turbo", 
                                 temperature=0, 
                                 max_tokens=500):
    '''
    封装一个支持更多参数的自定义访问 OpenAI GPT3.5 的函数

    参数: 
    messages: 这是一个消息列表,每个消息都是一个字典,包含 role(角色)和 content(内容)。角色可以是'system'、'user' 或 'assistant',内容是角色的消息。
    model: 调用的模型,默认为 gpt-3.5-turbo(ChatGPT),有内测资格的用户可以选择 gpt-4
    temperature: 这决定模型输出的随机程度,默认为0,表示输出将非常确定。增加温度会使输出更随机。
    max_tokens: 这决定模型输出的最大的 token 数。
    '''
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=temperature, # 这决定模型输出的随机程度
        max_tokens=max_tokens, # 这决定模型输出的最大的 token 数
    )
    return response.choices[0].message.content
python 复制代码
messages =  [  
{'role':'system', 
 'content':'你是一个助理, 并以 Seuss 苏斯博士的风格作出回答。'},    
{'role':'user', 
 'content':'就快乐的小鲸鱼为主题给我写一首短诗'},  
] 
response = get_completion_from_messages(messages, temperature=1)
print(response)
python 复制代码
# 长度控制
messages =  [  
{'role':'system',
 'content':'你的所有答复只能是一句话'},    
{'role':'user',
 'content':'写一个关于快乐的小鲸鱼的故事'},  
] 
response = get_completion_from_messages(messages, temperature =1)
print(response)
python 复制代码
# 以上结合
messages =  [  
{'role':'system',
 'content':'你是一个助理, 并以 Seuss 苏斯博士的风格作出回答,只回答一句话'},    
{'role':'user',
 'content':'写一个关于快乐的小鲸鱼的故事'},
] 
response = get_completion_from_messages(messages, temperature =1)
print(response)
python 复制代码
def get_completion_and_token_count(messages, 
                                   model="glm-3-turbo", 
                                   temperature=0, 
                                   max_tokens=500):
    """
    使用 OpenAI 的 GPT-3 模型生成聊天回复,并返回生成的回复内容以及使用的 token 数量。

    参数:
    messages: 聊天消息列表。
    model: 使用的模型名称。默认为"gpt-3.5-turbo"。
    temperature: 控制生成回复的随机性。值越大,生成的回复越随机。默认为 0。
    max_tokens: 生成回复的最大 token 数量。默认为 500。

    返回:
    content: 生成的回复内容。
    token_dict: 包含'prompt_tokens'、'completion_tokens'和'total_tokens'的字典,分别表示提示的 token 数量、生成的回复的 token 数量和总的 token 数量。
    """
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=temperature, 
        max_tokens=max_tokens,
    )
    print(response)
    content = response.choices[0].message.content
    
    token_dict = {
'prompt_tokens':response.usage.prompt_tokens,
'completion_tokens':response.usage.completion_tokens,
'total_tokens':response.usage.total_tokens,
    }

    return content, token_dict
python 复制代码
messages =  [  
{'role':'system', 
 'content':'你是一个助理, 并以 Seuss 苏斯博士的风格作出回答。'},    
{'role':'user', 
 'content':'就快乐的小鲸鱼为主题给我写一首短诗'},  
] 
response, token_dict = get_completion_and_token_count(messages)
print(response)
python 复制代码
print(token_dict)

总结

  • Prompt 工程的重要性
    • Prompt 工程极大地简化了 AI 应用的开发流程,特别是在文本应用中。
    • 通过提供简单的 Prompt,可以快速构建和部署 AI 模型,大幅缩短开发时间。
相关推荐
萤丰信息3 分钟前
数智赋能:智慧园区重构产业运营新范式
大数据·人工智能·科技·安全·智慧园区
盼哥PyAI实验室3 分钟前
用 Coze + 剪映,我搭了一条「每日英语」AI 自动视频生产流水线(37 个节点的真实复盘)
人工智能·ai·音视频
叫我:松哥3 分钟前
基于Flask的智能服装搭配推荐系统,采用协同过滤和内容过滤的混合推荐算法,支持虚拟试穿和个性化建议
人工智能·python·算法·信息可视化·flask·scikit-learn·推荐算法
新加坡内哥谈技术5 分钟前
作为创始人 CTO 的角色:第八年
人工智能
2503_946971866 分钟前
【StarFleet/Ops】2026年度联邦星舰企业架构演进与深空探测日志索引 (System Log Index)
运维·人工智能·网络安全·架构·系统架构·数据集
春日见8 分钟前
强化学习第一讲:强化学习是什么,强化学习分类
开发语言·jvm·人工智能·python·学习·matlab·强化学习
郝学胜-神的一滴8 分钟前
文海撷英,数林建模:词袋模型之奥义与中文处理实践
人工智能·python·程序人生·ai·自然语言处理·scikit-learn
TOPGUS8 分钟前
谷歌战略方向转型,希望成为一家由AI驱动的搜索平台
人工智能·搜索引擎·chatgpt·aigc·seo·数字营销
叫我:松哥12 分钟前
基于机器学习的智能健身风险分析系统,整合数据可视化与人工智能算法
人工智能·后端·python·算法·机器学习·信息可视化·scikit-learn
Dyanic14 分钟前
AddSR: 利用对抗扩散蒸馏技术加速基于扩散模型的盲超分辨率重建
图像处理·人工智能·超分辨率重建