使用Langsmith,Pydantic,Langchain和Claude 3.7十四行詩來提取結構化數據的編碼實現

用Langchain和Claude 3.7十四行詩解鎖結構化數據提取的功能,將原始文本轉化為可行的見解。本教程的重點是追踪LLM工具使用Langsmith調用,從而實現了您的提取系統的實時調試和性能監視。我們利用pydantic模式進行精確的數據格式,並使用Langchain的靈活提示來指導Claude。體驗示例驅動的改進,消除了對複雜培訓的需求。這是對Langsmith的功能的一瞥​​,展示瞭如何為從文檔處理到自動數據輸入的各種應用程序構建強大的提取管道。

首先,我們需要安裝必要的軟件包。我們將使用Langchain-Core和Langchain_anthropic與Claude模型接口。

!pip install --upgrade langchain-core
!pip install langchain_anthropic

如果您正在使用Langsmith進行跟踪和調試,則可以設置環境變量:

LANGSMITH_TRACING=True
LANGSMITH_ENDPOINT="https://api.smith.langchain.com"
LANGSMITH_API_KEY="Your API KEY"
LANGSMITH_PROJECT="extraction_api"

接下來,我們必須為要提取的信息定義架構。我們將使用Pydantic模型來創建一個人的結構化表示。

from typing import Optional
from pydantic import BaseModel, Field


class Person(BaseModel):
    """Information about a person."""


    name: Optional(str) = Field(default=None, description="The name of the person")
    hair_color: Optional(str) = Field(
        default=None, description="The color of the person's hair if known"
    )
    height_in_meters: Optional(str) = Field(
        default=None, description="Height measured in meters"
    )

現在,我們將定義一個提示模板,該模板指示Claude如何執行提取任務:

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder




prompt_template = ChatPromptTemplate.from_messages(
    (
        (
            "system",
            "You are an expert extraction algorithm. "
            "Only extract relevant information from the text. "
            "If you do not know the value of an attribute asked to extract, "
            "return null for the attribute's value.",
        ),


        ("human", "{text}"),
    )
)

該模板為模型提供了有關其任務以及如何處理丟失信息的明確說明。

接下來,我們將初始化將執行我們的信息提取的Claude模型:

import getpass
import os


if not os.environ.get("ANTHROPIC_API_KEY"):
    os.environ("ANTHROPIC_API_KEY") = getpass.getpass("Enter API key for Anthropic: ")


from langchain.chat_models import init_chat_model


llm = init_chat_model("claude-3-7-sonnet-20250219", model_provider="anthropic")

現在,我們將根據我們的模式配置LLM以返回結構化輸出:

structured_llm = llm.with_structured_output(schema=Person)

這個關鍵步驟告訴模型根據我們的人模式格式化其響應。

讓我們以一個簡單的示例測試我們的提取系統:

text = "Alan Smith is 6 feet tall and has blond hair."
prompt = prompt_template.invoke({"text": text})
result = structured_llm.invoke(prompt)
print(result)

現在,讓我們嘗試一個更複雜的例子:

from typing import List


class Data(BaseModel):
    """Container for extracted information about people."""
    people: List(Person) = Field(default_factory=list, description="List of people mentioned in the text")


structured_llm = llm.with_structured_output(schema=Data)


text = "My name is Jeff, my hair is black and I am 6 feet tall. Anna has the same color hair as me."
prompt = prompt_template.invoke({"text": text})
result = structured_llm.invoke(prompt)
print(result)




# Next example
text = "The solar system is large, (it was discovered by Nicolaus Copernicus), but earth has only 1 moon."
prompt = prompt_template.invoke({"text": text})
result = structured_llm.invoke(prompt)
print(result)

總之,該教程證明了使用Langchain和Claude構建結構化信息提取系統,該系統將非結構化的文本轉換為有關人的有組織數據。該方法使用Pydantic模式,自定義提示和示例驅動的改進,而無需專門的培訓管道。該系統的功率來自其靈活性,域的適應性和高級LLM推理功能的利用。


這是 COLAB筆記本。另外,別忘了跟隨我們 嘰嘰喳喳 並加入我們 電報頻道LinkedIn GrOUP。別忘了加入我們的 85k+ ml子雷迪特


Asif Razzaq是Marktechpost Media Inc.的首席執行官。作為一位有遠見的企業家和工程師,ASIF致力於利用人工智能的潛力來實現社會利益。他最近的努力是推出了人工智能媒體平台Marktechpost,該平台的深入覆蓋了機器學習和深度學習新聞,既在技術上都可以聽起來,既可以通過技術上的聲音,又可以被廣泛的受眾理解。該平台每月有超過200萬個觀點,說明了其在受眾中的受歡迎程度。

Source link

Scroll to Top