Guide étape par étape: Utilisation de langextract avec openai

Voyez comment commencer avec le nouveau Langextract de Google!
Récemment, Google a lancé une bibliothèque appelée Langextract. Langextract est une bibliothèque Python open source qui permet aux développeurs de transformer du texte non structuré en informations structurées à l’aide de modèles de grande langue (LLMS).
Il offre une interface légère compatible avec plusieurs backends de modèles, y compris les Gémeaux et le GPT, ce qui le rend bien adapté pour traiter un grand texte non structuré en informations structurées.
Certaines caractéristiques clés de Langextract sont:
- Prise en charge multi-modes – Fonctionne avec divers fournisseurs de LLM, notamment Gemini, Lama, GPT.
- Règles d’extraction personnalisées – Définissez vos propres instructions pour s’adapter à des cas d’utilisation spécifiques.
- Interface légère – frais généraux minimaux pour une intégration plus rapide dans les workflows existants.
- Sorties traçables – Mécanismes intégrés pour surveiller et vérifier comment les résultats sont générés.
- Traitement à volume élevé – Manipulation efficace des grands ensembles de données sans sacrifier le contrôle.
Installation de la bibliothèque de base
Passons, étape par étape, comment utiliser Langextract avec le modèle Openai GPT. Commencez par l’installation de la bibliothèque de base.
pip3 install langextract
Ensuite, pour travailler avec les modèles Openai GPT, installez l’intégration OpenAI:
pip3 install "langextract[openai]"
Après avoir installé les dépendances, importez les packages nécessaires dans votre fichier.
import langextract as lx
Créer une invite
La première étape consiste à créer une invite qui fournit des instructions au modèle à l’aide de la bibliothèque Langextract. Définissons l’invite comme indiqué ci-dessous:
prompt = textwrap.dedent("""\
Extract characters, emotions, and relationships in order of appearance.
Use exact text for extractions. Do not paraphrase or overlap entities.
Provide meaningful attributes for each entity to add context.""")
Créer un exemple
Ensuite, créez un exemple pour passer à la bibliothèque. Dans le code ci-dessous, nous utilisons le ExampleData
Fonction de la bibliothèque Langextract pour la définir. Cet exemple spécifie différents types de classes d’extraction, tels que le caractère et l’émotion.
examples = [
lx.data.ExampleData(
text="ROMEO. But soft! What light through yonder window breaks? It is the east, and Juliet is the sun.",
extractions=[
lx.data.Extraction(
extraction_class="character",
extraction_text="ROMEO",
attributes={"emotional_state": "wonder"}
),
lx.data.Extraction(
extraction_class="emotion",
extraction_text="But soft!",
attributes={"feeling": "gentle awe"}
),
lx.data.Extraction(
extraction_class="relationship",
extraction_text="Juliet is the sun",
attributes={"type": "metaphor"}
),
]
)
]
Préparer le texte d’entrée
Ensuite, préparez le texte d’entrée qui sera transmis à Langextract pour analyse.
input_text = textwrap.dedent("""
The rain tapped softly against the old library windows, blurring the outline of the cobblestone streets beyond. Elara traced her fingers over the spine of a book she’d read a hundred times, feeling the faint indent of gold-pressed letters.
“Still looking for answers in those dusty pages?” asked a voice from the doorway.She turned, startled. It was Rowan, his coat dripping with rain. The same distant look lingered in his eyes, the one that always made her wonder what storms he carried inside.
“I’m not looking for answers,” she said quietly. “I’m trying to remember the right questions.”Rowan stepped into the room, the scent of damp earth and pine following him. “Then maybe I’ve found one for you.” He reached into his coat pocket and placed a small brass key on the desk. It was warm, as if it had been pressed in his palm for hours.
“Where did you get this?” Elara whispered.His gaze met hers, unflinching. “From the man who swore it could open something that should never be opened.”
The silence between them seemed to thicken, the air heavy with a secret neither was ready to speak.
""")
Après avoir défini l’invite, l’exemple et le texte d’entrée, nous pouvons appeler Langextract extract
Fonction pour récupérer les informations souhaitées à partir du texte fourni, comme indiqué ci-dessous.
result = lx.extract(
text_or_documents=input_text,
prompt_description=prompt,
examples=examples,
model_id="gpt-4o",
api_key= os.getenv("OPENAI_API_KEY"),
fence_output=True,
use_schema_constraints=False
)
print("------result------")
print(result.extractions)
Pour travailler avec le modèle Openai, assurez-vous de définir le fence_output
valeur de True
. Vous devriez obtenir des extractions imprimées comme ci-dessous:
Vous pouvez imprimer tous les noms de caractères et les extractions comme indiqué ci-dessous.
character_names = [e.extraction_text for e in result.extractions if e.extraction_class == "character"]
print("=" * 40)
print("CHARACTER NAMES FOUND")
print("=" * 40)
for i, name in enumerate(character_names, 1):
print(f"{i}. {name}")
print("\n" + "=" * 40)
print("ALL EXTRACTIONS")
print("=" * 40)
for extraction in result.extractions:
print(f"📌 {extraction.extraction_class.upper()}: {extraction.extraction_text}")
if extraction.attributes:
print(f" Attributes: {extraction.attributes}")
print()
Vous devez obtenir la sortie comme indiqué ci-dessous:
Vous pouvez également stocker les données extraites dans un fichier .jsonl et visualiser les résultats comme indiqué ci-dessous.
lx.io.save_annotated_documents([result], output_name="extraction_results.jsonl")
html_content = lx.visualize(result)
with open("visualization.html", "w") as f:
f.write(html_content)
Lorsque vous ouvrez le fichier HTML dans un navigateur, la visualisation apparaîtra comme indiqué ci-dessous.
Tout à fait
Aménagement tout, vous pouvez utiliser la bibliothèque Langextract de Google avec le modèle Openai GPT comme indiqué ci-dessous:
import os
from dotenv import load_dotenv
from openai import OpenAI
from langchain_openai import ChatOpenAI
from langchain.schema import HumanMessage
from langchain_core.messages import AIMessage, SystemMessage
from langchain_core.prompts import PromptTemplate
import textwrap
import langextract as lx
load_dotenv()
prompt = textwrap.dedent("""\
Extract characters, emotions, and relationships in order of appearance.
Use exact text for extractions. Do not paraphrase or overlap entities.
Provide meaningful attributes for each entity to add context.""")
input_text = textwrap.dedent("""
The rain tapped softly against the old library windows, blurring the outline of the cobblestone streets beyond. Elara traced her fingers over the spine of a book she’d read a hundred times, feeling the faint indent of gold-pressed letters.
“Still looking for answers in those dusty pages?” asked a voice from the doorway.She turned, startled. It was Rowan, his coat dripping with rain. The same distant look lingered in his eyes, the one that always made her wonder what storms he carried inside.
“I’m not looking for answers,” she said quietly. “I’m trying to remember the right questions.”Rowan stepped into the room, the scent of damp earth and pine following him. “Then maybe I’ve found one for you.” He reached into his coat pocket and placed a small brass key on the desk. It was warm, as if it had been pressed in his palm for hours.
“Where did you get this?” Elara whispered.His gaze met hers, unflinching. “From the man who swore it could open something that should never be opened.”
The silence between them seemed to thicken, the air heavy with a secret neither was ready to speak.
""")
examples = [
lx.data.ExampleData(
text="ROMEO. But soft! What light through yonder window breaks? It is the east, and Juliet is the sun.",
extractions=[
lx.data.Extraction(
extraction_class="character",
extraction_text="ROMEO",
attributes={"emotional_state": "wonder"}
),
lx.data.Extraction(
extraction_class="emotion",
extraction_text="But soft!",
attributes={"feeling": "gentle awe"}
),
lx.data.Extraction(
extraction_class="relationship",
extraction_text="Juliet is the sun",
attributes={"type": "metaphor"}
),
]
)
]
def extract_text():
result = lx.extract(
text_or_documents=input_text,
prompt_description=prompt,
examples=examples,
model_id="gpt-4o",
api_key= os.getenv("OPENAI_API_KEY"),
fence_output=True,
use_schema_constraints=False
)
print("------result------")
print(result.extractions)
character_names = [e.extraction_text for e in result.extractions if e.extraction_class == "character"]
print("=" * 40)
print("CHARACTER NAMES FOUND")
print("=" * 40)
for i, name in enumerate(character_names, 1):
print(f"{i}. {name}")
print("\n" + "=" * 40)
print("ALL EXTRACTIONS")
print("=" * 40)
for extraction in result.extractions:
print(f"📌 {extraction.extraction_class.upper()}: {extraction.extraction_text}")
if extraction.attributes:
print(f" Attributes: {extraction.attributes}")
print()
lx.io.save_annotated_documents([result], output_name="extraction_results.jsonl")
html_content = lx.visualize(result)
with open("visualization.html", "w") as f:
f.write(html_content)
return html_content
if __name__ == "__main__":
extract_text()
Vous pouvez suivre les mises à jour de la bibliothèque ici: https://github.com/google/langextract. J’espère que cet article vous aidera à démarrer avec Langextract et à explorer son vaste potentiel pour un large éventail de cas d’utilisation. Merci d’avoir lu.
Source link