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

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

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

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

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

unsetunsetHTTP 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   

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

unsetunsetFunction 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   

(完)

附上技术清单

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

学习大型人工智能模型,如GPT-3、BERT或任何其他先进的神经网络模型,需要系统的方法和持续的努力。既然要系统的学习大模型,那么学习路线是必不可少的,下面的这份路线能帮助你快速梳理知识,形成自己的体系。

L1级别:AI大模型时代的华丽登场

L2级别:AI大模型API应用开发工程

L3级别:大模型应用架构进阶实践

L4级别:大模型微调与私有化部署

一般掌握到第四个级别,市场上大多数岗位都是可以胜任,但要还不是天花板,天花板级别要求更加严格,对于算法和实战是非常苛刻的。建议普通人掌握到L4级别即可。

以上的AI大模型学习路线,不知道为什么发出来就有点糊,高清版可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费

请添加图片描述

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

这套包含640份报告的合集,涵盖了AI大模型的理论研究、技术实现、行业应用等多个方面。无论您是科研人员、工程师,还是对AI大模型感兴趣的爱好者,这套报告合集都将为您提供宝贵的信息和启示。

img

三、大模型经典PDF籍

随着人工智能技术的飞速发展,AI大模型已经成为了当今科技领域的一大热点。这些大型预训练模型,如GPT-3、BERT、XLNet等,以其强大的语言理解和生成能力,正在改变我们对人工智能的认识。 那以下这些PDF籍就是非常不错的学习资源。

img

四、AI大模型商业化落地方案

img

作为普通人,入局大模型时代需要持续学习和实践,不断提高自己的技能和认知水平,同时也需要有责任感和伦理意识,为人工智能的健康发展贡献力量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值