开始使用免费开始使用

请求结构化输出

在创建词汇图(lexical graph)时,您使用文本分割器从文本中提取角色名称和台词,但这种方法常常会在分割边界附近丢失上下文。例如,文本中的舞台指示可以用来判断该角色当时正在对谁说话。

您将把 Character 类嵌入到一个新的 Line 类中,用它来描述正在说的这句台词,同时包含说话人以及这句台词所指向的角色列表。您还将创建一个包装类 LineOutput,以便一次提取多条这样的台词。

已为您定义了包含提取说明的 prompt 变量,以及作为 llm 的一个 LLM 实例。

本练习是课程的一部分

使用 LangChain 和 Neo4j 的 Graph RAG

查看课程

练习说明

  • LineOutput 类更新为请求 Line 对象的列表。
  • 使用 LineOutput 类定义一个能生成结构化输出的 LLM。

交互式实操练习

通过完成这段示例代码来试试这个练习。

class Line(BaseModel):
    text: str = Field(..., description="The text of the line")
    spoken_by: Character = Field(..., description="The character who speaks the line")
    spoken_to: Optional[list[Character]] = Field(None, description="The character who the line is spoken to")

class LineOutput(BaseModel):
    # Request more than one line from the text
    lines: ____[Line] = Field(..., description="The lines from the text")

# Return an instance of LineOutput
structured_llm = llm.____(____)

for line in structured_llm.invoke(prompt.format_messages(text=text)):
	print(line)
编辑并运行代码