【使用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 模型,大幅缩短开发时间。
相关推荐
魔乐社区几秒前
DeepSeek在昇腾上的模型部署 - 常见问题及解决方案
人工智能·深度学习·deepseek
夜幕龙13 分钟前
深度生成模型(二)——基本概念与数学建模
人工智能·深度学习·transformer
游王子17 分钟前
OpenCV(11):人脸检测、物体识别
人工智能·opencv·计算机视觉
山海青风19 分钟前
从零开始玩转TensorFlow:小明的机器学习故事 3
人工智能·机器学习·tensorflow
@心都20 分钟前
机器学习数学基础:35.效度
人工智能·机器学习
幻想趾于现实22 分钟前
傅里叶分析
人工智能
春末的南方城市29 分钟前
VidSketch:具有扩散控制的手绘草图驱动视频生成
人工智能·深度学习·计算机视觉·aigc
Toky丶36 分钟前
【文献阅读】A Survey on Model Compression for Large Language Models
人工智能·语言模型·自然语言处理
Williams101 小时前
解锁高效开发新姿势:Trae AI编辑器深度体验
人工智能·编辑器
Francek Chen1 小时前
【大模型科普】AIGC技术发展与应用实践(一文读懂AIGC)
人工智能·深度学习·语言模型·大模型·aigc