Spaces:
Sleeping
Sleeping
File size: 8,842 Bytes
f3aae92 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | 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
}
|