GLM-4.7-Flash代码实例:Python调用本地vLLM服务生成高质量文本

1. 快速了解GLM-4.7-Flash

GLM-4.7-Flash是智谱AI推出的新一代大语言模型,采用先进的混合专家架构,总参数量达到300亿。这个模型特别适合中文场景,理解和生成能力都很出色,而且推理速度经过专门优化,响应非常迅速。

简单来说,它就像一个超级智能的写作助手,能够帮你生成各种高质量的文本内容,从创意文案到技术文档都能胜任。

2. 环境准备与快速部署

2.1 系统要求

要运行GLM-4.7-Flash,你需要准备以下环境:

  • 操作系统:Linux Ubuntu 18.04+
  • GPU:至少4张RTX 4090 D显卡
  • 内存:64GB以上
  • 存储:至少100GB可用空间

2.2 一键启动服务

镜像已经预装了所有需要的组件,启动后服务会自动运行。你可以通过以下命令检查服务状态:

# 查看服务运行状态
supervisorctl status

# 预期输出应该显示两个服务都在运行
# glm_vllm                          RUNNING   pid 123, uptime 0:05:43
# glm_ui                            RUNNING   pid 124, uptime 0:05:43

如果服务没有自动启动,可以手动启动:

# 启动所有服务
supervisorctl start all

3. Python调用vLLM服务实战

3.1 基础调用示例

让我们从最简单的调用开始。首先确保你的Python环境安装了requests库:

pip install requests

然后使用以下代码进行基础调用:

import requests
import json

def simple_chat():
    # API端点地址
    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": "请用200字介绍人工智能的发展历程"}
        ],
        "temperature": 0.7,
        "max_tokens": 500
    }
    
    # 发送请求
    response = requests.post(api_url, json=payload)
    
    # 解析响应
    if response.status_code == 200:
        result = response.json()
        print("生成的文本:")
        print(result['choices'][0]['message']['content'])
    else:
        print(f"请求失败,状态码:{response.status_code}")
        print(response.text)

# 执行调用
simple_chat()

这段代码会向本地vLLM服务发送请求,让GLM-4.7-Flash生成一段关于人工智能发展历程的介绍文字。

3.2 流式输出实现

如果你想要实时看到生成过程,可以使用流式输出:

def stream_chat():
    import requests
    
    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": "写一篇关于深度学习的科普文章"}
        ],
        "temperature": 0.7,
        "max_tokens": 1000,
        "stream": True  # 启用流式输出
    }
    
    print("开始生成:", end="", flush=True)
    
    # 流式请求
    response = requests.post(api_url, json=payload, stream=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)
                        if 'choices' in data and len(data['choices']) > 0:
                            delta = data['choices'][0].get('delta', {})
                            if 'content' in delta:
                                print(delta['content'], end="", flush=True)
                    except json.JSONDecodeError:
                        continue

# 执行流式调用
stream_chat()

3.3 多轮对话实现

GLM-4.7-Flash支持多轮对话,可以记住之前的对话内容:

def multi_turn_chat():
    # 初始化对话历史
    conversation_history = []
    
    def chat_with_model(message):
        # 添加用户消息到历史
        conversation_history.append({"role": "user", "content": message})
        
        # 准备请求
        payload = {
            "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
            "messages": conversation_history,
            "temperature": 0.7,
            "max_tokens": 500
        }
        
        # 发送请求
        response = requests.post("http://127.0.0.1:8000/v1/chat/completions", json=payload)
        
        if response.status_code == 200:
            result = response.json()
            assistant_reply = result['choices'][0]['message']['content']
            
            # 添加助手回复到历史
            conversation_history.append({"role": "assistant", "content": assistant_reply})
            
            return assistant_reply
        else:
            return f"请求失败: {response.status_code}"
    
    # 示例多轮对话
    print("用户: 什么是机器学习?")
    reply1 = chat_with_model("什么是机器学习?")
    print(f"助手: {reply1}\n")
    
    print("用户: 它和深度学习有什么区别?")
    reply2 = chat_with_model("它和深度学习有什么区别?")
    print(f"助手: {reply2}\n")
    
    print("用户: 请举例说明深度学习的应用")
    reply3 = chat_with_model("请举例说明深度学习的应用")
    print(f"助手: {reply3}")

# 执行多轮对话
multi_turn_chat()

4. 高级应用场景

4.1 批量文本生成

如果你需要一次性生成多个文本,可以使用批量处理:

def batch_text_generation():
    prompts = [
        "写一首关于春天的诗",
        "生成一篇产品发布会新闻稿",
        "创建一个关于健康饮食的博客大纲"
    ]
    
    results = []
    
    for prompt in prompts:
        payload = {
            "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
            "messages": [{"role": "user", "content": prompt}],
            "temperature": 0.7,
            "max_tokens": 300
        }
        
        response = requests.post("http://127.0.0.1:8000/v1/chat/completions", json=payload)
        
        if response.status_code == 200:
            result = response.json()
            generated_text = result['choices'][0]['message']['content']
            results.append({
                "prompt": prompt,
                "generated_text": generated_text
            })
        else:
            results.append({
                "prompt": prompt,
                "error": f"生成失败: {response.status_code}"
            })
    
    # 输出结果
    for i, result in enumerate(results, 1):
        print(f"【生成结果 {i}】")
        print(f"输入: {result['prompt']}")
        if 'generated_text' in result:
            print(f"输出: {result['generated_text']}")
        else:
            print(f"错误: {result['error']}")
        print("-" * 50)

# 执行批量生成
batch_text_generation()

4.2 参数调优示例

不同的参数设置会影响生成效果,这里展示几个常用参数的调整:

def parameter_tuning_example():
    prompt = "写一篇关于远程办公优势的文章"
    
    # 不同温度值对比
    temperatures = [0.3, 0.7, 1.2]
    
    for temp in temperatures:
        print(f"\n=== 温度值: {temp} ===")
        
        payload = {
            "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
            "messages": [{"role": "user", "content": prompt}],
            "temperature": temp,
            "max_tokens": 200
        }
        
        response = requests.post("http://127.0.0.1:8000/v1/chat/completions", json=payload)
        
        if response.status_code == 200:
            result = response.json()
            print(result['choices'][0]['message']['content'][:100] + "...")
        else:
            print("生成失败")

# 执行参数调优示例
parameter_tuning_example()

5. 实用技巧与最佳实践

5.1 错误处理与重试机制

在实际应用中,添加适当的错误处理很重要:

def robust_chat_request(prompt, max_retries=3):
    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": 500
    }
    
    for attempt in range(max_retries):
        try:
            response = requests.post(api_url, json=payload, timeout=30)
            
            if response.status_code == 200:
                result = response.json()
                return result['choices'][0]['message']['content']
            else:
                print(f"尝试 {attempt + 1} 失败,状态码: {response.status_code}")
                time.sleep(2)  # 等待2秒后重试
                
        except requests.exceptions.RequestException as e:
            print(f"尝试 {attempt + 1} 网络错误: {e}")
            time.sleep(2)
    
    return "生成失败,请检查服务状态"

# 使用加强版的调用函数
result = robust_chat_request("解释一下神经网络的工作原理")
print(result)

5.2 性能优化建议

对于生产环境,可以考虑以下优化措施:

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# 创建具有重试机制的会话
def create_retry_session():
    session = requests.Session()
    
    # 配置重试策略
    retry_strategy = Retry(
        total=3,  # 最大重试次数
        backoff_factor=1,  # 重试等待时间因子
        status_forcelist=[429, 500, 502, 503, 504]  # 需要重试的状态码
    )
    
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    
    return session

# 使用优化后的会话
session = create_retry_session()

def optimized_chat_request(prompt):
    payload = {
        "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.7,
        "max_tokens": 500
    }
    
    try:
        response = session.post(
            "http://127.0.0.1:8000/v1/chat/completions",
            json=payload,
            timeout=30
        )
        
        if response.status_code == 200:
            result = response.json()
            return result['choices'][0]['message']['content']
        else:
            return f"请求失败: {response.status_code}"
            
    except requests.exceptions.RequestException as e:
        return f"网络错误: {e}"

# 使用优化后的请求
result = optimized_chat_request("生成一段产品描述")
print(result)

6. 常见问题解决

在实际使用过程中,可能会遇到一些问题,这里提供一些解决方案:

问题1:连接超时或服务无响应

检查服务状态,确保vLLM服务正常运行:

# 检查服务状态
supervisorctl status

# 如果服务停止,重新启动
supervisorctl start glm_vllm

问题2:生成内容不符合预期

调整温度参数和提示词:

# 降低温度值获得更确定性的结果
payload = {
    "model": "/root/.cache/huggingface/ZhipuAI/GLM-4.7-Flash",
    "messages": [{"role": "user", "content": "你的提示词"}],
    "temperature": 0.3,  # 降低温度值
    "max_tokens": 500
}

问题3:生成速度慢

检查GPU使用情况,确保没有其他程序占用大量资源:

# 查看GPU使用情况
nvidia-smi

7. 总结

通过本文的代码实例,你应该已经掌握了如何使用Python调用本地vLLM服务来生成高质量文本。GLM-4.7-Flash作为一个强大的开源大模型,在中文文本生成方面表现出色,无论是创意写作、技术文档还是日常对话都能胜任。

关键要点回顾:

  • 使用简单的HTTP请求就能调用vLLM服务
  • 流式输出可以实时查看生成过程
  • 多轮对话让交互更加自然
  • 适当的参数调优可以改善生成效果
  • 错误处理和性能优化对生产环境很重要

现在你可以开始尝试将这些代码示例应用到自己的项目中,探索GLM-4.7-Flash的更多可能性。


获取更多AI镜像

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

┌─────────────────────────────────────┐
│     桦漫AIGC集成开发                 │
│     微信: henryhan1117              │
├─────────────────────────────────────┤
│  技术支持 · 定制开发 · 模型部署      │
└─────────────────────────────────────┘
Logo

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

更多推荐