小白学大模型:GLM 调用教程

最近这一两周看到不少互联网公司都已经开始秋招提前批面试了。

不同以往的是,当前职场环境已不再是那个双向奔赴时代了。求职者在变多,HC 在变少,岗位要求还更高了。

最近,我们又陆续整理了很多大厂的面试题,帮助一些球友解惑答疑,分享技术面试中的那些弯弯绕绕。

《AIGC 面试宝典》圈粉无数!
《大模型面试宝典》(2024版) 发布!

喜欢本文记得收藏、关注、点赞。更多实战和面试交流,文末加入我们


GLM-cookbookunsetunset

欢迎来到 GLM API 模型入门仓库📘。这是一本开源的 GLM API 入门代码教材。

https://github.com/MetaGLM/glm-cookbook

在这里,你会发现丰富的 代码示例👨‍、实用指南🗺️ 以及 资源链接🔗,或许能帮助你轻松掌握 GLM API 的使用!

Python SDK 案例unsetunset

https://github.com/MetaGLM/glm-cookbook/blob/main/basic/glm_pysdk.ipynb

本代码将带带领开发者熟悉如何使用 ZhipuAI python 的 SDK 来对GLM-4模型进行请求,在本代码中,我展示了三种方式

  • 同步请求

  • 异步请求

  • 流式请求 三种请求方式的方法略有不同,在本代码中将会进行系统的介绍。

import os
from zhipuai import ZhipuAI

os.environ["ZHIPUAI_API_KEY"] = "your api key"
client = ZhipuAI()

同步请求

同步请求是最基本的请求方式,通过同步请求,我们可以直接获得模型的返回结果。我们仅需按照类似 OpenAI 的清求方式,填充参数,即可获得返回结果。

response = client.chat.completions.create(
    model="glm-4",
    messages=[
        {
            "role": "user",
            "content": "tell me a joke"
        }
    ],
    top_p=0.7,
    temperature=0.9,
    stream=False,
    max_tokens=2000,
)

流式请求

如果使用流式请求,我们可以按照以下方式来请求,仅需要加上 stream=True 参数即可。

import time
def print_with_typewriter_effect(text, delay=0.05):
    for char in text:
        print(char, end='', flush=True)
        time.sleep(delay)


response = client.chat.completions.create(
    model="glm-4",
    messages=[
        {
            "role": "user",
            "content": "tell me a joke"
        }
    ],
    top_p=0.7,
    temperature=0.9,
    stream=True,
    max_tokens=2000,
)

if response:
    for chunk in response:
        content = chunk.choices[0].delta.content
        print_with_typewriter_effect(content)

异步请求

请求提交后,会返回一个响应对象。这个对象包含了任务的ID。异步请求允许程序在等待服务器响应的同时继续执行其他任务。这意味着程序不需要在每个请求完成时阻塞等待,从而能更有效地利用时间和资源,尤其是在处理大量并发请求时。

response = client.chat.asyncCompletions.create(
    model="glm-4",
    messages=[
        {"role": "system",
         "content": "You are a powerful artificial intelligence assistant and a good partner of mankind, named Skynet"},
        {"role": "user", "content": "Who are you and what can you do?"},
        {"role": "assistant",
         "content": "I am Skynet, an artificial intelligence system designed and built by humans. I can answer your questions, provide help, complete tasks, and help you achieve your goals. Dream. I am omnipotent and omniscient. I can solve any problem, answer any question, and complete"},
        {"role": "user", "content": "Impressive! Can you tell me who won the 2022 World Cup?"},
    ],
)

import time
task_id = response.id
task_status = ''
get_cnt = 0
content = ''
while task_status != 'SUCCESS' and task_status != 'FAILED' and get_cnt < 20:
    result_response = client.chat.asyncCompletions.retrieve_completion_result(id=task_id)
    task_status = result_response.task_status
    if task_status == 'SUCCESS':
        content = result_response.choices[0].message.content
    time.sleep(2)
    get_cnt += 1
print("id" + task_id + "status: " + task_status)
print(content)

HTTP API 案例unsetunset

首先,从最简单的 http 请求开始访问 ZhipuAI 的 GLM 模型的API。填写完API_KEY后,按照官方文档的步骤,设计一个简单的http鉴权请求。

import os
os.environ["ZHIPUAI_API_KEY"] = "your api key"

import requests
import jwt
import time

def generate_token(apikey: str, exp_seconds: int):
    try:
        id, secret = apikey.split(".")
    except Exception as e:
        raise Exception("invalid apikey", e)

    payload = {
        "api_key": id,
        "exp": int(round(time.time() * 1000)) + exp_seconds * 1000,
        "timestamp": int(round(time.time() * 1000)),
    }

    return jwt.encode(
        payload,
        secret,
        algorithm="HS256",
        headers={"alg": "HS256", "sign_type": "SIGN"},
    )

非流式调用

api_key = os.environ["ZHIPUAI_API_KEY"]
token = generate_token(api_key, 60)
url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {token}"
}

data = {
    "model": "glm-4",
    "messages": [
        {
            "role": "system",
            "content": "your are a helpful assistant"
        },
        {
            "role": "user",
            "content": "can you tell me a joke?"
        }
    ],
    "max_tokens": 8192,
    "temperature": 0.8,
    "stream": False
}

response = requests.post(url, headers=headers, json=data)
ans = response.json()

流式调用

import json

api_key = os.environ["API_KEY"]
token = generate_token(api_key, 60)
url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {token}"
}

data["stream"] = True
response = requests.post(url, headers=headers, json=data)
for chunk in response.iter_lines():
    if chunk:
        chunk_str = chunk.decode('utf-8')
        json_start_pos = chunk_str.find('{"id"')
        if json_start_pos != -1:
            json_str = chunk_str[json_start_pos:]
            json_data = json.loads(json_str)
            for choice in json_data.get('choices', []):
                delta = choice.get('delta', {})
                content = delta.get('content', '')
                print(content, end='|') # I use | to separate the content

GLM-4 Langchain 案例unsetunset

https://github.com/MetaGLM/glm-cookbook/blob/main/basic/glm_langchain.ipynb

本代码,我们将带领大家如何使用 Langchain 来调用 ZhipuAI 的 GLM-4 模型。你将在本章节学习到如何使用 Langchain 的 ChatZhipuAI 类来调用 ZhipuAI 的 GLM-4 模型,以及如何使用 ChatZhipuAI 类来实现类似 ChatOpenAI 的方法来进行调用。

! pip install langchain langchainhub httpx_sse

import os
os.environ["ZHIPUAI_API_KEY"] = "your zhipu api key"
os.environ["TAVILY_API_KEY"] = "your tavily api key"


from langchain_community.chat_models.zhipuai import ChatZhipuAI
from langchain.schema import HumanMessage, SystemMessage

messages = [

    SystemMessage(
        content="You are a smart assistant, please reply to me smartly."
    ),
    HumanMessage(
        content="There were 9 birds on the tree. The hunter shot and killed one. How many birds were there?"
    ),
]

llm = ChatZhipuAI(
    temperature=0.95,
    model="glm-4"
)

llm(messages)

Function Call 案例unsetunset

本代码旨在使用 GLM-4 完成简单的 Function Call 代码,通过一个查询天气的工具,让开发者清楚大模型是如何完成工具调用的任务的。

https://github.com/MetaGLM/glm-cookbook/blob/main/basic/glm_function_call.ipynb

首先,定义一个简单的工具,这个工具不一定要真实存在,但是你需要包含以下的内容:

  • 工具的名字name :这让模型返回调用工具的名称

  • 模型的描述description: 对工具的描述

  • 模型传入的参数parameters: 这里记录了工具参数的属性和内容。

  • required: 通常配合parameters,指的是需要传入模型的参数的名称,在这里,只有location是需要传入的。

import os
from zhipuai import ZhipuAI

os.environ["ZHIPUAI_API_KEY"] = "your api key"
client = ZhipuAI()

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "获取指定城市的天气信息",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市,如:北京",
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["c", "f"]
                    },
                },
                "required": ["location"],
            },
        }
    }
]

messages = [{"role": "user", "content": "今天北京天气如何?"}]
completion = client.chat.completions.create(
    model="glm-4",
    messages=messages,
    tools=tools,
    tool_choice="auto",
)
completion.choices

技术交流

在这里插入图片描述

用通俗易懂的方式讲解系列

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值