Devchuz/llm_code
0
1from langchain_anthropic import ChatAnthropic2from pydantic import BaseModel, Field3from typing import List4import pandas as pd5from dotenv import load_dotenv6import os7import warnings8import json9# Ignorar todos los warnings10warnings.filterwarnings("ignore")11 12load_dotenv()13 14llm = ChatAnthropic(model="claude-3-haiku-20240307", temperature=0)15 16# Pydantic class definitions17 18 19class Title(BaseModel):20 text: str = Field(description="Title of the notification")21 22class Message(BaseModel):23 content: str = Field(description="Main content or message of the notification")24 25class Number(BaseModel):26 value: int = Field(description="Relevant number or identifier within the notification")27 28class NotificationAnalysis(BaseModel):29 title: List[Title] = Field(default=[], description="Title of the push notification")30 message: List[Message] = Field(default=[], description="Main message or content")31 number: List[Number] = Field(default=[], description="Relevant number or ID within the notification")32 33# Function to process notification text34def extract_from_notification(llm, notification_text):35 prompt = f"""36 Given the following push notification text, structure the content into JSON format under the sections "title", "message", and "number":37 - Extract the title of the notification and add it to "title".38 - Extract the main message or content and add it to "message".39 - If there is any relevant number or identifier, add it to "number".40 - Do not include information that is not directly related to title, message, or relevant number.41 42 Notification to process:43 {notification_text}44 45 Expected format:46 {{47 "title": [{{"text": "Title of the notification"}}],48 "message": [{{"content": "Main message or content"}}],49 "number": [{{"value": 123}}]50 }}51 """52 # Set up the LLM with structured output according to the NotificationAnalysis class53 structured_llm = llm.with_structured_output(NotificationAnalysis)54 55 # Invoke the structured model and obtain the response56 response = structured_llm.invoke(prompt)57 response = response.dict()58 59 60 return response61 62 63notification_text = """64New update available: Version 2.0 has been released with improved features. 65Your device ID is 12345. Tap to update now.66"""67 68# Ejecuta la función con el modelo Anthropic real69response = extract_from_notification(llm, notification_text)70 71# Muestra la respuesta72print(response)73print(type(response))