要求結構化輸出
在建立 lexical graph 時,你曾用文字分割器從文本中擷取角色名稱與台詞,但這種作法常會在分割邊界附近遺失語境。例如,文本中的舞臺指示可以用來判斷當下角色是在對誰說話。
你將在新的 Line 類別中使用 Character 類別,來描述一段台詞,並包含說話者與這段台詞的對象清單。你也會建立一個包裝用的 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)