import json from operator import itemgetter from typing import Any, Dict, List, Optional, Sequence import uuid from langchain_groq import ChatGroq from langchain.text_splitter import CharacterTextSplitter,TokenTextSplitter from langchain_core.runnables import RunnableLambda from db.models import DDRHEADER,DAILYOPERATIONS,FLUID,Example from database import get_mongo_client from langchain_huggingface import HuggingFaceEmbeddings from typing_extensions import TypedDict from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch from langserve import CustomUserType from pydantic import BaseModel, Field from langchain_core.runnables import chain from langchain_core.prompts import ChatPromptTemplate,MessagesPlaceholder from langchain_core.messages import AIMessage, HumanMessage, ToolMessage class ExtractRequest(CustomUserType): """Request body for the extract endpoint.""" text: str = Field(..., description="The text to extract from.") examples: Optional[List[Example]] = Field( None, description="Examples of extractions." ) class ExtractResponse(TypedDict, total=False): """Response body for the extract endpoint.""" data: Any # content to long will be set to true if the content is too long # and had to be truncated content_too_long: Optional[bool] def deduplicate( extract_responses: Sequence[ExtractResponse], ) -> ExtractResponse: """Deduplicate the results. The deduplication is done by comparing the serialized JSON of each of the results and only keeping the unique ones. """ unique_extracted = [] seen = set() for response in extract_responses: for data_item in response["data"]: # Serialize the data item for comparison purposes serialized = json.dumps(data_item, sort_keys=True) if serialized not in seen: seen.add(serialized) unique_extracted.append(data_item) return { "data": unique_extracted, } def _make_prompt_template( examples: Optional[Sequence[Example]], function_name: str, ) -> ChatPromptTemplate: """Make a system message from instructions and examples.""" prefix = ( "You are a top-tier algorithm for extracting information from text. " "Only extract information that is relevant to the provided text. " "If no information is relevant, use the schema and output " "an empty list where appropriate." ) system_message = ("system", prefix) prompt_components = [system_message] if examples is not None: few_shot_prompt = [] for example in examples: # TODO: We'll need to refactor this at some point to # support other encoding strategies. The function calling logic here # has some hard-coded assumptions (e.g., name of parameters like `data`). _id = uuid.uuid4().hex[:] tool_call = { "args": {"data": example.output}, "name": function_name, "id": _id, } few_shot_prompt.extend( [ HumanMessage(content=example.text), AIMessage(content="", tool_calls=[tool_call]), ToolMessage( content="You have correctly called this tool.", tool_call_id=_id ), ] ) prompt_components.extend(few_shot_prompt) prompt_components.append( ( "human", "I need to extract information from " "the following text: ```\n{text}\n```\n", ), ) return ChatPromptTemplate.from_messages(prompt_components) @chain async def extraction_runnable(extraction_request: ExtractRequest) -> ExtractResponse: """An end point to extract content from a given text object.""" prompt = _make_prompt_template( extraction_request.examples, "DDR" ) model = ChatGroq( temperature=0, groq_api_key='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', model_name="llama3-8b-8192" ) runnable = (prompt | model.with_structured_output(schema=DAILYOPERATIONS)).with_config( {"run_name": "extraction"} ) return await runnable.ainvoke({"text": extraction_request.text}) def _make_extract_requests(input_dict: Dict[str, Any]) -> List[ExtractRequest]: docs = input_dict.pop("text") return [ExtractRequest(text=doc.page_content, **input_dict) for doc in docs] async def extract_from_content( content: str, *, text_splitter_kwargs: Optional[Dict[str, Any]] = None, ) -> ExtractResponse: """Extract from potentially long-form content.""" if text_splitter_kwargs is None: text_splitter_kwargs = { "separator": "\n\n", "chunk_size": 2000, "chunk_overlap": 50, } text_splitter = CharacterTextSplitter(**text_splitter_kwargs) docs = text_splitter.create_documents([content]) #doc_contents = [doc.page_content for doc in docs] db = get_mongo_client().Cygnus part_collection = db["pdfparts"] embedding_function = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2") vector_store = MongoDBAtlasVectorSearch( collection=part_collection, embedding=embedding_function, index_name="pdf_sections", relevance_score_fn="cosine", ) #for doc_content in doc_contents: # document = {"page_content": doc_content} vector_store.add_documents(docs) retriever=vector_store.as_retriever() runnable = ( { "text": itemgetter("query") | retriever, "schema": itemgetter("schema"), "examples": lambda x: x.get("examples") } | RunnableLambda(_make_extract_requests) | extraction_runnable.abatch ) schema = DAILYOPERATIONS examples = [] description = content # TODO: improve this result = await runnable.ainvoke( { "query": description, "schema": schema, "examples": examples } ) return deduplicate(result) async def extract_entire_document( content: str, ) -> ExtractResponse: """Extract from entire document.""" #json_schema = DAILYREPORT #examples = get_examples_from_extractor(extractor) text_splitter = TokenTextSplitter( chunk_size=8192, chunk_overlap=0 ) texts = text_splitter.split_text(content) extraction_requests = [ ExtractRequest( text=text, examples=[] #examples ) for text in texts ] # Limit the number of chunks to process if len(extraction_requests) > 1: content_too_long = True extraction_requests = extraction_requests[: 1] else: content_too_long = False prompt = ChatPromptTemplate.from_messages( [ ( "system", "You are an expert extraction algorithm, you are specialized in Oil Drilling Reports," "Only extract relevant information entities mentioned in the following passage, together with their properties, " "If you do not know the value of an attribute asked to extract, return 'null' for the attribute's value." ), ("user", "{text}"), ] ) model = ChatGroq( temperature=0, groq_api_key='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', model_name="mixtral-8x7b-32768" ) chain = prompt | model.with_structured_output(schema=DDRHEADER) resultado = chain.invoke({"text":extraction_requests[0].text}) try: resultado_json = resultado.model_dump_json() except json.JSONDecodeError as e: raise ValueError("Failed to decode JSON from the model output") from e chain2 = prompt | model.with_structured_output(schema=DAILYOPERATIONS) resultado2 = chain2.invoke({"text":extraction_requests[0].text}) try: resultado_json2 = resultado2.model_dump_json() except json.JSONDecodeError as e: raise ValueError("Failed to decode JSON from the model output") from e chain3 = prompt | model.with_structured_output(schema=FLUID) resultado3 = chain3.invoke({"text":extraction_requests[0].text}) try: resultado_json3 = resultado3.model_dump_json() except json.JSONDecodeError as e: raise ValueError("Failed to decode JSON from the model output") from e return { "data":{"ddrheader":resultado_json, "dailyoper":resultado_json2, "fluid": resultado_json3 } , # deduplicate(extract_responses)["data"], "content_too_long": content_too_long }