GLM-4.7-Flash代码实例:使用curl与Python requests双方式调用本地API

桦漫AIGC集成开发 | 微信: henryhan1117 | 技术支持 · 定制开发 · 模型部署

1. 快速了解GLM-4.7-Flash的强大能力

GLM-4.7-Flash是智谱AI推出的新一代大语言模型,采用了先进的MoE(混合专家)架构,总参数量达到300亿。这个模型最大的特点就是在保持强大能力的同时,推理速度非常快,特别适合需要实时响应的应用场景。

简单来说,这个模型就像是一个知识渊博又反应迅速的智能助手。你问它问题,它能快速给出高质量的回答,而且特别擅长中文理解和生成。无论是写文章、写代码、回答问题,还是进行多轮对话,它都能表现得非常出色。

2. 环境准备与API服务确认

在开始调用API之前,我们需要先确认几件事情:

2.1 检查服务状态

首先确保GLM-4.7-Flash的API服务已经正常运行。打开终端,输入以下命令:

# 检查服务状态
supervisorctl status

# 应该看到类似这样的输出
# glm_vllm                        RUNNING   pid 123, uptime 0:10:00
# glm_ui                          RUNNING   pid 124, uptime 0:10:00

如果服务没有运行,可以使用以下命令启动:

# 启动所有服务
supervisorctl start all

# 等待约30秒让模型加载完成

2.2 确认API端点

GLM-4.7-Flash提供了OpenAI兼容的API接口,地址是:

http://127.0.0.1:8000/v1/chat/completions

你可以通过浏览器访问 http://127.0.0.1:8000/docs 查看完整的API文档。

3. 使用curl命令调用API

curl是一个命令行工具,可以用来发送HTTP请求。下面我们来看看如何使用curl来调用GLM-4.7-Flash的API。

3.1 基础调用示例

curl -X POST "http://127.0.0.1:8000/v1/chat/completions" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
    "messages": [
      {"role": "user", "content": "请用中文介绍一下你自己"}
    ],
    "temperature": 0.7,
    "max_tokens": 500
  }'

这个命令会向API发送一个请求,询问模型"请用中文介绍一下你自己"。你会得到一个JSON格式的响应,其中包含模型的回答。

3.2 流式输出调用

如果你想要实时看到模型的回答,可以使用流式输出:

curl -X POST "http://127.0.0.1:8000/v1/chat/completions" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
    "messages": [
      {"role": "user", "content": "写一首关于春天的诗"}
    ],
    "temperature": 0.7,
    "max_tokens": 300,
    "stream": true
  }'

使用流式输出时,你会看到模型一个字一个字地生成回答,而不是等待完整回答后再一次性返回。

3.3 多轮对话示例

curl -X POST "http://127.0.0.1:8000/v1/chat/completions" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
    "messages": [
      {"role": "user", "content": "Python是什么?"},
      {"role": "assistant", "content": "Python是一种高级编程语言,以简洁易读的语法著称。"},
      {"role": "user", "content": "那它适合用来做什么类型的开发?"}
    ],
    "temperature": 0.7,
    "max_tokens": 400
  }'

在这个例子中,我们模拟了一个多轮对话。模型能够理解之前的对话上下文,并给出连贯的回答。

4. 使用Python requests调用API

对于Python开发者来说,使用requests库调用API更加方便。下面我们来看几个实际的例子。

4.1 基础调用代码

import requests
import json

def call_glm_api(prompt):
    """基础API调用函数"""
    url = "http://127.0.0.1:8000/v1/chat/completions"
    
    payload = {
        "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.7,
        "max_tokens": 1000
    }
    
    try:
        response = requests.post(url, json=payload)
        response.raise_for_status()  # 检查请求是否成功
        
        result = response.json()
        return result['choices'][0]['message']['content']
    
    except requests.exceptions.RequestException as e:
        return f"请求失败: {e}"
    except KeyError as e:
        return f"解析响应失败: {e}"

# 使用示例
answer = call_glm_api("用简单的语言解释人工智能是什么")
print(answer)

4.2 流式输出处理

import requests

def stream_glm_response(prompt):
    """流式输出处理函数"""
    url = "http://127.0.0.1:8000/v1/chat/completions"
    
    payload = {
        "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.7,
        "max_tokens": 500,
        "stream": True
    }
    
    try:
        response = requests.post(url, json=payload, stream=True)
        response.raise_for_status()
        
        print("模型回答: ", end="", flush=True)
        
        for line in response.iter_lines():
            if line:
                line_str = line.decode('utf-8')
                if line_str.startswith('data: '):
                    data_str = line_str[6:]  # 去掉'data: '前缀
                    if data_str != '[DONE]':
                        try:
                            data = json.loads(data_str)
                            content = data['choices'][0]['delta'].get('content', '')
                            print(content, end="", flush=True)
                        except json.JSONDecodeError:
                            continue
    
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")

# 使用示例
stream_glm_response("讲述一个关于冒险的短故事")

4.3 完整的对话类实现

import requests
import json
from typing import List, Dict

class GLMChat:
    """GLM-4.7-Flash对话类"""
    
    def __init__(self):
        self.api_url = "http://127.0.0.1:8000/v1/chat/completions"
        self.conversation_history: List[Dict] = []
    
    def add_message(self, role: str, content: str):
        """添加消息到对话历史"""
        self.conversation_history.append({"role": role, "content": content})
    
    def chat(self, user_input: str, temperature: float = 0.7, max_tokens: int = 800) -> str:
        """发送消息并获取回复"""
        self.add_message("user", user_input)
        
        payload = {
            "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
            "messages": self.conversation_history,
            "temperature": temperature,
            "max_tokens": max_tokens
        }
        
        try:
            response = requests.post(self.api_url, json=payload)
            response.raise_for_status()
            
            result = response.json()
            assistant_reply = result['choices'][0]['message']['content']
            
            self.add_message("assistant", assistant_reply)
            return assistant_reply
            
        except requests.exceptions.RequestException as e:
            return f"请求失败: {e}"
        except KeyError as e:
            return f"解析响应失败: {e}"
    
    def clear_history(self):
        """清空对话历史"""
        self.conversation_history = []

# 使用示例
chat_bot = GLMChat()

# 多轮对话
print("用户: 你好,请帮我规划一下学习Python的路线")
reply1 = chat_bot.chat("你好,请帮我规划一下学习Python的路线")
print(f"AI: {reply1}")

print("用户: 我应该先学哪些库?")
reply2 = chat_bot.chat("我应该先学哪些库?")
print(f"AI: {reply2}")

print("用户: 这些学完之后呢?")
reply3 = chat_bot.chat("这些学完之后呢?")
print(f"AI: {reply3}")

5. 实际应用场景示例

现在让我们看几个实际的应用场景,看看如何将API调用应用到真实项目中。

5.1 智能客服机器人

import requests
import time

class CustomerServiceBot:
    """智能客服机器人"""
    
    def __init__(self):
        self.api_url = "http://127.0.0.1:8000/v1/chat/completions"
        self.system_prompt = """你是一个专业的客服助手,请用友好、专业的态度回答用户问题。
        如果遇到无法回答的问题,建议用户联系人工客服。"""
    
    def respond_to_customer(self, user_question: str) -> str:
        """响应客户问题"""
        messages = [
            {"role": "system", "content": self.system_prompt},
            {"role": "user", "content": user_question}
        ]
        
        payload = {
            "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
            "messages": messages,
            "temperature": 0.3,  # 较低的温度让回答更稳定
            "max_tokens": 300
        }
        
        try:
            response = requests.post(self.api_url, json=payload, timeout=30)
            response.raise_for_status()
            
            result = response.json()
            return result['choices'][0]['message']['content']
            
        except requests.exceptions.Timeout:
            return "抱歉,响应超时,请稍后再试。"
        except Exception as e:
            return f"系统繁忙,请稍后重试。错误信息: {str(e)}"

# 使用示例
bot = CustomerServiceBot()
questions = [
    "我的订单什么时候发货?",
    "如何办理退货?",
    "产品有质量问题怎么办?"
]

for question in questions:
    print(f"客户: {question}")
    response = bot.respond_to_customer(question)
    print(f"客服: {response}")
    print("-" * 50)
    time.sleep(1)

5.2 内容生成助手

import requests

class ContentGenerator:
    """内容生成助手"""
    
    def generate_article(self, topic: str, style: str = "专业") -> str:
        """生成文章"""
        prompt = f"""请以{style}的风格,写一篇关于{topic}的文章。
        要求内容详实、结构清晰、语言流畅。字数在800字左右。"""
        
        payload = {
            "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
            "messages": [{"role": "user", "content": prompt}],
            "temperature": 0.8,  # 较高的温度让内容更有创意
            "max_tokens": 1500
        }
        
        response = requests.post(self.api_url, json=payload)
        result = response.json()
        return result['choices'][0]['message']['content']
    
    def generate_summary(self, text: str, max_length: int = 200) -> str:
        """生成摘要"""
        prompt = f"""请为以下文本生成一个简洁的摘要,长度不超过{max_length}字:
        
        {text}
        """
        
        payload = {
            "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
            "messages": [{"role": "user", "content": prompt}],
            "temperature": 0.3,
            "max_tokens": max_length + 50
        }
        
        response = requests.post(self.api_url, json=payload)
        result = response.json()
        return result['choices'][0]['message']['content']

# 使用示例
generator = ContentGenerator()

# 生成技术文章
article = generator.generate_article("人工智能在医疗领域的应用", "技术分析")
print("生成的文章:")
print(article)
print("\n" + "="*50 + "\n")

# 生成摘要
summary = generator.generate_summary(article)
print("文章摘要:")
print(summary)

6. 常见问题与解决方案

在使用API的过程中,可能会遇到一些问题。这里总结了一些常见问题和解决方法:

6.1 连接问题

问题:连接被拒绝或超时

# 检查服务是否运行
supervisorctl status

# 如果服务未运行,启动服务
supervisorctl start all

# 检查端口是否被占用
netstat -tlnp | grep 8000

# 检查防火墙设置
sudo ufw status

6.2 响应速度慢

问题:API响应时间过长

# 可以调整请求超时时间
response = requests.post(api_url, json=payload, timeout=60)  # 60秒超时

# 或者使用异步请求
import asyncio
import aiohttp

async def async_api_call(prompt):
    async with aiohttp.ClientSession() as session:
        async with session.post(api_url, json=payload) as response:
            return await response.json()

6.3 处理大文本

问题:输入文本过长导致错误

def chunk_text(text, max_length=2000):
    """将长文本分块"""
    words = text.split()
    chunks = []
    current_chunk = []
    
    for word in words:
        if len(' '.join(current_chunk + [word])) <= max_length:
            current_chunk.append(word)
        else:
            chunks.append(' '.join(current_chunk))
            current_chunk = [word]
    
    if current_chunk:
        chunks.append(' '.join(current_chunk))
    
    return chunks

# 分段处理长文本
long_text = "你的很长很长的文本..."
chunks = chunk_text(long_text)

for chunk in chunks:
    response = call_glm_api(f"处理这段文本: {chunk}")
    print(response)

7. 总结

通过本文的学习,你应该已经掌握了如何使用curl和Python requests两种方式来调用GLM-4.7-Flash的本地API。这两种方法各有优势:

  • curl命令:适合快速测试和调试,不需要编写代码
  • Python requests:适合集成到应用程序中,功能更强大灵活

无论你选择哪种方式,GLM-4.7-Flash都能提供高质量的文字生成服务。这个模型在中文处理方面表现特别出色,响应速度也很快,非常适合各种实时应用场景。

在实际使用中,记得根据你的具体需求调整参数:

  • temperature:控制回答的创造性(0.1-1.0)
  • max_tokens:控制生成长度
  • stream:是否使用流式输出

如果你在使用的过程中遇到任何问题,或者有特殊的定制需求,可以参考文章开头的联系方式获取技术支持。


获取更多AI镜像

想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐