惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google Online Security Blog
Google Online Security Blog
博客园_首页
酷 壳 – CoolShell
酷 壳 – CoolShell
Jina AI
Jina AI
博客园 - Franky
大猫的无限游戏
大猫的无限游戏
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
V
V2EX
雷峰网
雷峰网
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
F
Full Disclosure
Y
Y Combinator Blog
V
V2EX - 技术
Attack and Defense Labs
Attack and Defense Labs
S
Security @ Cisco Blogs
Schneier on Security
Schneier on Security
Microsoft Azure Blog
Microsoft Azure Blog
SecWiki News
SecWiki News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
量子位
PCI Perspectives
PCI Perspectives
S
Secure Thoughts
D
Darknet – Hacking Tools, Hacker News & Cyber Security
AWS News Blog
AWS News Blog
Blog — PlanetScale
Blog — PlanetScale
爱范儿
爱范儿
K
Kaspersky official blog
B
Blog
A
Arctic Wolf
Hacker News: Ask HN
Hacker News: Ask HN
L
LangChain Blog
T
Tor Project blog
P
Privacy & Cybersecurity Law Blog
Recent Announcements
Recent Announcements
宝玉的分享
宝玉的分享
The Register - Security
The Register - Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
L
Lohrmann on Cybersecurity
D
Docker
A
About on SuperTechFans
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
The Last Watchdog
The Last Watchdog
S
Security Affairs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Privacy International News Feed
Simon Willison's Weblog
Simon Willison's Weblog

博客园 - 全栈测试笔记

博文阅读密码验证 - 博客园 FastAPI系列(24):ORM操作之删除接口开发 博文阅读密码验证 - 博客园 FastAPI系列(23):ORM操作之编辑接口开发 FastAPI系列(22):ORM之多对多查询记录 FastAPI系列(21):ORM之多对多添加记录 CC Switch配置模型 Claude Code安装 FastAPI系列(20):ORM添加表记录 FastAPI系列(19):ORM响应页面数据 博文阅读密码验证 - 博客园 FastAPI系列(18):ORM查询操作 FastAPI系列(17):ORM的迁移命令 FastAPI系列(16):ORM创建模型类 FastAPI系列(15):Jinja2模板语法之控制结构 FastAPI系列(14):Jinja2模板语法之过滤器 FastAPI系列(13):Jinja2模板介绍、模板语法之变量渲染 FastAPI系列(12):响应模型参数 【汇总】FastAPI系列教程
单例模式管理模型客户端的几种实现方式
全栈测试笔记 · 2026-02-08 · via 博客园 - 全栈测试笔记

使用大模型的时候,模型客户端只需要创建一个,这就要用到单例模式。

1. 使用类变量存储实例

通过类变量保存唯一的实例对象,确保全局只有一个实例。

class ModelClientManager:
    _instance = None  # 类变量,用于存储唯一实例

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.client = cls._create_model_client()
        return cls._instance

    @staticmethod
    def _create_model_client():
        # 创建模型客户端的逻辑
        return OpenAIChatCompletionClient(
            model=os.getenv("MODEL", "glm-4.7"),
            base_url=os.getenv("BASE_URL", "https://open.bigmodel.cn/api/paas/v4/"),
            api_key=os.getenv("API_KEY"),
        )

    def get_client(self):
        return self.client

说明:

  • __new__ 方法控制实例的创建过程,确保只创建一次
  • _create_model_client 是静态方法,用于初始化模型客户端
  • cls._instance.client = cls._create_model_client(),表示为这个新实例初始化 client 属性,值为 _create_model_client() 方法创建的模型客户端

2. 线程安全的单例实现

如果需要支持多线程环境,可以引入锁机制保证线程安全。

import threading

class ThreadSafeModelClientManager:
    _instance = None
    _lock = threading.Lock()  # 线程锁

    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
                    cls._instance.client = cls._create_model_client()
        return cls._instance

    @staticmethod
    def _create_model_client():
        return OpenAIChatCompletionClient(
            model=os.getenv("MODEL", "glm-4.7"),
            base_url=os.getenv("BASE_URL", "https://open.bigmodel.cn/api/paas/v4/"),
            api_key=os.getenv("API_KEY"),
        )

    def get_client(self):
        return self.client

说明:

  • 使用 threading.Lock() 确保在多线程环境下实例创建的原子性。

3. 装饰器实现单例

通过装饰器简化单例模式的实现

def singleton(cls):
    instances = {}

    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return get_instance

@singleton
class DecoratorModelClientManager:
    def __init__(self):
        self.client = self._create_model_client()

    @staticmethod
    def _create_model_client():
        return OpenAIChatCompletionClient(
            model=os.getenv("MODEL", "glm-4.7"),
            base_url=os.getenv("BASE_URL", "https://open.bigmodel.cn/api/paas/v4/"),
            api_key=os.getenv("API_KEY"),
        )

    def get_client(self):
        return self.client

说明:

  • 装饰器 singleton 统一管理实例的创建和访问。
  • 适用于希望以更简洁方式实现单例的场景。

4. 模块级单例

将实例定义在模块级别,天然具备单例特性。

# model_client_manager.py
import os
from autogen_ext.models.openai import OpenAIChatCompletionClient

class ModelClientManager:
    def __init__(self):
        self.client = self._create_model_client()

    @staticmethod
    def _create_model_client():
        return OpenAIChatCompletionClient(
            model=os.getenv("MODEL", "glm-4.7"),
            base_url=os.getenv("BASE_URL", "https://open.bigmodel.cn/api/paas/v4/"),
            api_key=os.getenv("API_KEY"),
        )

    def get_client(self):
        return self.client

# 模块级单例实例
model_client = ModelClientManager()

说明:

  • 在模块中直接创建实例 manager,其他模块导入时共享同一实例。
  • 简单直观,适合小型项目或无需复杂控制的场景。

5. 使用示例

无论采用哪种方式,调用时均通过单例获取客户端:

# 获取模型客户端
client = ModelClientManager().get_client()
# 或者(模块级单例)
from model_client_manager import model_client
client = model_client.get_client()