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

Python3.9 FastAPI集成Pinecone时QueryResponse无法JSON序列化

解决Pinecone QueryResponse对象序列化返回的问题

问题背景

调用Pinecone的index.query()接口后,返回的QueryResponse对象无法直接在FastAPI控制器中返回,尝试多种方式均报错:

  • 直接返回对象触发RecursionError: maximum recursion depth exceeded in comparison
  • 使用json.dumps()触发TypeError: Object of type QueryResponse is not JSON serializable
  • 使用jsonpickle.encode()返回"null"

核心原因

Pinecone返回的QueryResponse是自定义类实例,并非原生Python字典,默认JSON序列化机制无法处理该对象,且对象内部可能存在循环引用导致递归错误。

解决方案

方案1:使用官方to_dict()方法转换为字典

Pinecone的QueryResponse对象内置to_dict()方法,可直接将对象转换为可序列化的Python字典,这是最可靠的官方解决方案。

修改服务层代码:

@staticmethod
async def query(query) -> dict:
    index = PineConeService.get_or_create_index("openai")
    embed = GPT3Service.get_embedding(query)
    query_results = index.query(
        vector=embed,
        top_k=2,
        include_metadata=True
    )
    # 转换为可序列化的字典
    return query_results.to_dict()

控制器层直接返回该字典即可,FastAPI会自动将其序列化为JSON响应:

@router.post("/query/")
async def semantic_search(query: str):
    result = await TopicQueryService.query(query)
    return result

方案2:自定义JSON编码器(备用方案)

如果to_dict()方法不可用,可自定义JSON编码器处理QueryResponse对象:

import json
from pinecone.core.client.model.query_response import QueryResponse

class QueryResponseEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, QueryResponse):
            # 提取对象属性字典进行序列化
            return obj.__dict__
        return super().default(obj)

服务层使用该编码器序列化:

@staticmethod
async def query(query) -> str:
    index = PineConeService.get_or_create_index("openai")
    embed = GPT3Service.get_embedding(query)
    query_results = index.query(
        vector=embed,
        top_k=2,
        include_metadata=True
    )
    return json.dumps(query_results, cls=QueryResponseEncoder)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 04:20:55