You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ollama Python库未关闭Socket资源警告问题求助

解决Ollama客户端未关闭Socket导致的ResourceWarning问题

问题描述

使用Python 3.11.7 + ollama库0.3.3开发时,创建Ollama客户端并多次调用嵌入函数,功能正常,但程序结束时抛出以下资源警告:

sys:1: ResourceWarning: unclosed <socket.socket fd=15, family=30, type=1, proto=6, laddr=('::1', 50598, 0, 0), raddr=('::1', 11434, 0, 0)>

相关代码如下:

创建Ollama客户端

ollama_client = ollama.Client(host='http://localhost:11434')

嵌入函数实现

from typing import List
import ollama

def get_embedding(text: str, ollama_client: ollama.Client) -> List[float]:
    """
    调用Ollama API获取文本嵌入,包含异常处理与资源回退机制。

    参数:
        text (str): 需要生成嵌入的文本。

    返回:
        List[float]: 嵌入向量,以浮点数列表形式返回。
    """
    try:
        response = ollama_client.embeddings(model=VECTORIZER_MODELNAME, prompt=text)
        return response['embedding']
    except Exception as e:
        print(f"获取嵌入时出错: {e}")
        # 返回零向量作为回退方案
        return [0.0] * VECTORIZER_DIMENSION

函数调用示例

highlight_vector = get_embedding(highlight, ollama_client)

解决方案

警告根源是ollama.Client底层的HTTP会话未被显式关闭,导致socket资源未释放。以下是三种解决方式:

  • 显式关闭客户端会话
    在所有嵌入调用完成后,手动调用客户端的close()方法释放资源:

    ollama_client = ollama.Client(host='http://localhost:11434')
    
    # 执行所有嵌入调用逻辑...
    highlight_vector = get_embedding(highlight, ollama_client)
    # 其他调用...
    
    # 程序收尾时关闭客户端
    ollama_client.close()
    
  • 使用上下文管理器(推荐)
    用with语句管理客户端生命周期,块结束时自动关闭会话,无需手动操作:

    with ollama.Client(host='http://localhost:11434') as ollama_client:
        highlight_vector = get_embedding(highlight, ollama_client)
        # 所有需要客户端的操作都放在此块内
    
  • 临时抑制警告(不推荐)
    若暂时无法修改代码结构,可添加以下代码隐藏警告,但这只是规避问题而非解决:

    import warnings
    warnings.filterwarnings("ignore", category=ResourceWarning)
    

内容的提问来源于stack exchange,提问作者Robert Alexander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 02:30:55