大模型输出json

# 大模型输出json的最好方案.
        from langchain_core.messages import HumanMessage, SystemMessage
        from langchain_openai import ChatOpenAI
        from pydantic import BaseModel, Field
        # 替换后
        from typing import List, Optional

        class ChunkMetadata(BaseModel):
            summary: str = Field(description="1-2句话总结这个块的内容")
            keywords: List[str] = Field(description="5-7个关键词")
            hypothetical_questions: List[str] = Field(description="这个块能回答什么问题")
            table_summary: Optional[str] = Field(description="如果是表格,用自然语言描述")

        # 用结构化输出,比解析文本可靠多了
        enrichment_llm = ChatOpenAI(temperature=0, base_url=base_url,
                                     api_key=api_key,
                                     model="qwen-plus").with_structured_output(ChunkMetadata)

        import asyncio
        semaphore = asyncio.Semaphore(10)
        print(enrichment_llm.invoke([
            SystemMessage(content=""),
            HumanMessage(content="1. 2023年1月1日,xxx在北京举行。2. 2023年1月1日,xxx二十届")]),
            )

posted on 2026-01-21 09:05  张博的博客  阅读(3)  评论(0)    收藏  举报

导航