HPirela commited on
Commit
e9fe174
·
1 Parent(s): 2f1dd01

new changes

Browse files
.dockerignore ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ **/__pycache__
2
+ **/.venv
3
+ **/.classpath
4
+ **/.dockerignore
5
+ **/.env
6
+ **/.git
7
+ **/.gitignore
8
+ **/.project
9
+ **/.settings
10
+ **/.toolstarget
11
+ **/.vs
12
+ **/.vscode
13
+ **/*.*proj.user
14
+ **/*.dbmdl
15
+ **/*.jfm
16
+ **/bin
17
+ **/charts
18
+ **/docker-compose*
19
+ **/compose*
20
+ **/Dockerfile*
21
+ **/node_modules
22
+ **/npm-debug.log
23
+ **/obj
24
+ **/secrets.dev.yaml
25
+ **/values.dev.yaml
26
+ LICENSE
27
+ README.md
.gitignore CHANGED
@@ -1,2 +1,3 @@
1
  __pycache__
2
  venv
 
 
1
  __pycache__
2
  venv
3
+ .env
.vscode/launch.json CHANGED
@@ -10,7 +10,40 @@
10
  "request": "launch",
11
  "program": "app.py",
12
  "console": "integratedTerminal",
13
- "env": {"PYTHONPATH":"${workspaceRoot}"}, //
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  }
15
  ]
16
- }
 
10
  "request": "launch",
11
  "program": "app.py",
12
  "console": "integratedTerminal",
13
+ "env": {
14
+ "PYTHONPATH": "${workspaceRoot}"
15
+ }
16
+ },
17
+ {
18
+ "name": "Docker: Run Cygnus Server",
19
+ "type": "docker",
20
+ "request": "launch",
21
+ "preLaunchTask": "docker-build",
22
+ "platform": "python",
23
+ "python": {
24
+ "pathMappings": [
25
+ {
26
+ "localRoot": "${workspaceFolder}",
27
+ "remoteRoot": "/app"
28
+ }
29
+ ],
30
+ "projectType": "fastapi"
31
+ }
32
+ },
33
+ {
34
+ "name": "Docker: Python - Fastapi",
35
+ "type": "docker",
36
+ "request": "launch",
37
+ "preLaunchTask": "docker-run: debug",
38
+ "python": {
39
+ "pathMappings": [
40
+ {
41
+ "localRoot": "${workspaceFolder}",
42
+ "remoteRoot": "/app"
43
+ }
44
+ ],
45
+ "projectType": "fastapi"
46
+ }
47
  }
48
  ]
49
+ }
.vscode/tasks.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "2.0.0",
3
+ "tasks": [
4
+ {
5
+ "type": "docker-build",
6
+ "label": "docker-build",
7
+ "platform": "python",
8
+ "dockerBuild": {
9
+ "tag": "cygnusserver:latest",
10
+ "dockerfile": "${workspaceFolder}/Dockerfile",
11
+ "context": "${workspaceFolder}",
12
+ "pull": true
13
+ }
14
+ },
15
+ {
16
+ "type": "docker-run",
17
+ "label": "docker-run: debug",
18
+ "dependsOn": [
19
+ "docker-build"
20
+ ],
21
+ "python": {
22
+ "args": [
23
+ "app:app",
24
+ "--host",
25
+ "0.0.0.0",
26
+ "--port",
27
+ "7860"
28
+ ],
29
+ "module": "uvicorn"
30
+ }
31
+ }
32
+ ]
33
+ }
Dockerfile CHANGED
@@ -10,4 +10,5 @@ COPY --chown=user ./requirements.txt requirements.txt
10
  RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
 
12
  COPY --chown=user . /app
13
- CMD fastapi run --reload --host=0.0.0.0 --port=7860
 
 
10
  RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
 
12
  COPY --chown=user . /app
13
+ EXPOSE 7860
14
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
Dockerfile_local ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # For more information, please refer to https://aka.ms/vscode-docker-python
2
+ FROM python:3.9
3
+
4
+ EXPOSE 7860
5
+ # Keeps Python from generating .pyc files in the container
6
+ ENV PYTHONDONTWRITEBYTECODE=1
7
+ # Turns off buffering for easier container logging
8
+ ENV PYTHONUNBUFFERED=1
9
+ RUN useradd -m -u 1000 user
10
+ USER user
11
+ ENV PATH="/home/user/.local/bin:$PATH"
12
+
13
+ WORKDIR /app
14
+ # Install pip requirements
15
+ COPY --chown=user ./requirements.txt requirements.txt
16
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
17
+
18
+ COPY --chown=user . /app
19
+ # Creates a non-root user with an explicit UID and adds permission to access the /app folder
20
+ # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers
21
+
22
+ # During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
23
+ CMD ["gunicorn", "--bind", "0.0.0.0:7860", "-k", "uvicorn.workers.UvicornWorker", "app:app"]
api/examples.py CHANGED
@@ -65,6 +65,17 @@ def list_examples(
65
 
66
 
67
 
 
 
 
 
 
 
 
 
 
 
 
68
  @router.delete("/{uuid}")
69
  def delete(
70
  uuid: UUID
@@ -79,12 +90,3 @@ def delete(
79
  result = example_collection.delete_one({"uuid": uuid})
80
  if result.deleted_count == 0:
81
  raise HTTPException(status_code=404, detail="Example not found.")
82
-
83
- @router.delete("/all")
84
- def delete_all() -> None:
85
- """Endpoint to delete all examples."""
86
- db = get_mongo_client().Cygnus
87
- example_collection = db["examples"]
88
- result = example_collection.delete_many({})
89
- if result.deleted_count == 0:
90
- raise HTTPException(status_code=404, detail="No examples found to delete.")
 
65
 
66
 
67
 
68
+ # deleete all must be declared before delet uuid
69
+ @router.delete("/all")
70
+ def delete_all() -> int:
71
+ """Endpoint to delete all examples."""
72
+ db = get_mongo_client().Cygnus
73
+ example_collection = db["examples"]
74
+ result = example_collection.delete_many({})
75
+ if result.deleted_count == 0:
76
+ raise HTTPException(status_code=404, detail="No examples found to delete.")
77
+ return result.deleted_count
78
+
79
  @router.delete("/{uuid}")
80
  def delete(
81
  uuid: UUID
 
90
  result = example_collection.delete_one({"uuid": uuid})
91
  if result.deleted_count == 0:
92
  raise HTTPException(status_code=404, detail="Example not found.")
 
 
 
 
 
 
 
 
 
api/extractor.py CHANGED
@@ -1,16 +1,35 @@
1
  import os
2
  from fastapi import APIRouter, File, UploadFile,HTTPException
3
  from langchain_community.document_loaders import PDFPlumberLoader
 
4
  from extraction.parsing import parse_binary_input
5
  from database import get_mongo_client
6
-
7
-
8
  from typing import Any, List, Optional,Dict
 
 
 
 
 
 
 
 
 
 
9
 
10
- from retrieval import extract_entire_document, ExtractResponse
11
 
 
 
 
 
 
12
 
13
- MAX_CHUNKS=7000
 
 
 
14
 
15
 
16
  router = APIRouter(
@@ -21,8 +40,8 @@ router = APIRouter(
21
  )
22
 
23
 
24
- @router.post("/DDR", response_model=ExtractResponse)
25
- async def upload_ddr(
26
  *,
27
  file: Optional[UploadFile] = File(None)
28
  ) -> ExtractResponse:
@@ -51,7 +70,8 @@ async def upload_ddr(
51
  # we also can clasify what informatio exist in echa page to only extract that information
52
  text_ = "\n".join([document.page_content for document in documents])
53
 
54
- data_result= await extract_entire_document(text_)
 
55
  # Save data_result to the database with file name as metadata
56
  client = get_mongo_client()
57
  db = client['Cygnus'] # Replace with your actual database name
@@ -72,3 +92,74 @@ async def upload_ddr(
72
  return data_result
73
 
74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  from fastapi import APIRouter, File, UploadFile,HTTPException
3
  from langchain_community.document_loaders import PDFPlumberLoader
4
+ from db.models import DDR
5
  from extraction.parsing import parse_binary_input
6
  from database import get_mongo_client
7
+ import pdfplumber
8
+ import pandas as pd
9
  from typing import Any, List, Optional,Dict
10
+ from langchain_openai import ChatOpenAI
11
+ from graph_version import extract_drilling_information
12
+ from retrieval import ExtractResponse
13
+ from langchain_core.messages import HumanMessage
14
+ import base64
15
+ import io
16
+ from IPython.display import Image as IPImage
17
+ from IPython.display import display
18
+ import fitz
19
+ from PIL import Image
20
 
21
+ MAX_CHUNKS=7000
22
 
23
+ def pdf_page_to_base64(pdf_path: str, page_number: int):
24
+ pdf_document = fitz.open(pdf_path)
25
+ page = pdf_document.load_page(page_number - 1) # input is one-indexed
26
+ pix = page.get_pixmap()
27
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
28
 
29
+ buffer = io.BytesIO()
30
+ img.save(buffer, format="PNG")
31
+
32
+ return base64.b64encode(buffer.getvalue()).decode("utf-8")
33
 
34
 
35
  router = APIRouter(
 
40
  )
41
 
42
 
43
+ @router.post("/DDR2", response_model=ExtractResponse)
44
+ async def upload_ddr2(
45
  *,
46
  file: Optional[UploadFile] = File(None)
47
  ) -> ExtractResponse:
 
70
  # we also can clasify what informatio exist in echa page to only extract that information
71
  text_ = "\n".join([document.page_content for document in documents])
72
 
73
+ #data_result= await extract_entire_document(text_)
74
+ data_result=extract_drilling_information(text_)
75
  # Save data_result to the database with file name as metadata
76
  client = get_mongo_client()
77
  db = client['Cygnus'] # Replace with your actual database name
 
92
  return data_result
93
 
94
 
95
+ @router.post("/PDFLumber", response_model=ExtractResponse)
96
+ async def upload_ddr_with_PDFlumber(
97
+ *,
98
+ file: Optional[UploadFile] = File(None)
99
+ ) -> ExtractResponse:
100
+ """Endpoint that is used with DDR extractor.
101
+
102
+ This endpoint will be expanded to support upload of binary files as well as
103
+ text files.
104
+ """
105
+ if file is None:
106
+ raise HTTPException(status_code=422, detail="No file provided.")
107
+
108
+ temp_file_path = f"./temp_{file.filename}"
109
+ with open(temp_file_path, "wb") as buffer:
110
+ buffer.write(await file.read())
111
+
112
+ # Load the PDF using PDFPlumberLoader
113
+ with pdfplumber.open(temp_file_path) as pdf:
114
+ p0 = pdf.pages[0]
115
+ im = p0.to_image()
116
+ im.debug_tablefinder()
117
+ im.show()
118
+ tables = p0.extract_tables()
119
+ import pandas as pd
120
+
121
+ # Iterate over the tables list and create a DataFrame for each one
122
+ dataframes = []
123
+ for table in tables:
124
+ df = pd.DataFrame(table[1:]) # Assuming the first row is the header
125
+ dataframes.append(df)
126
+
127
+ # For demonstration, let's concatenate all dataframes into a single one
128
+ df = pd.concat(dataframes, ignore_index=True)
129
+
130
+ return {
131
+ "data": df.to_json() ,
132
+ "content_too_long": True
133
+ }
134
+
135
+
136
+ @router.post("/vision", response_model=ExtractResponse)
137
+ async def upload_ddr_with_vision(
138
+ *,
139
+ file: Optional[UploadFile] = File(None)
140
+ )-> ExtractResponse:
141
+ if file is None:
142
+ raise HTTPException(status_code=422, detail="No file provided.")
143
+
144
+ temp_file_path = f"./temp_{file.filename}"
145
+ with open(temp_file_path, "wb") as buffer:
146
+ buffer.write(await file.read())
147
+ base64_image = pdf_page_to_base64(temp_file_path, 1)
148
+ display(IPImage(data=base64.b64decode(base64_image)))
149
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0).with_structured_output(DDR)
150
+ query = "You are a top-tier algorithm for extracting information from text,you are specialized in Oil Drilling Reports. think step by step and 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."
151
+ message = HumanMessage(
152
+ content=[
153
+ {"type": "text", "text": query},
154
+ {
155
+ "type": "image_url",
156
+ "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
157
+ },
158
+ ],
159
+ )
160
+ response = llm.invoke([message])
161
+ print(response)
162
+ return {
163
+ "data": response.json(),
164
+ "content_too_long": True
165
+ }
database.py CHANGED
@@ -1,19 +1,18 @@
1
  import os
2
- import pymongo
3
-
4
-
5
  from pymongo.mongo_client import MongoClient
6
  from pymongo.server_api import ServerApi
7
 
 
8
 
9
  client = None
10
 
11
  def get_mongo_client() -> MongoClient:
12
  global client
13
  if client is None:
14
- password = os.environ.get("PASSWORD", "hva3HaKg1S7acKmM")
15
  uri = f"mongodb+srv://DDR:{password}@cluster0.o7h6s.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
16
- client = MongoClient(uri, server_api=ServerApi('1'),uuidRepresentation='standard')
17
  try:
18
  client.admin.command('ping')
19
  print("Pinged your deployment. You successfully connected to MongoDB!")
@@ -22,14 +21,13 @@ def get_mongo_client() -> MongoClient:
22
 
23
  return client
24
 
25
-
26
  # Max concurrency used for extracting content from documents.
27
  # A long document is broken into smaller chunks this controls
28
  # how many chunks are processed concurrently.
29
- MAX_CONCURRENCY = int(os.environ.get("MAX_CONCURRENCY", 1))
30
 
31
  # Max number of chunks to process per documents
32
  # When a long document is split into chunks, this controls
33
  # how many of those chunks will be processed.
34
  # Set to 0 or negative to disable the max chunks limit.
35
- MAX_CHUNKS = int(os.environ.get("MAX_CHUNKS", -1))
 
1
  import os
2
+ from dotenv import load_dotenv
 
 
3
  from pymongo.mongo_client import MongoClient
4
  from pymongo.server_api import ServerApi
5
 
6
+ load_dotenv()
7
 
8
  client = None
9
 
10
  def get_mongo_client() -> MongoClient:
11
  global client
12
  if client is None:
13
+ password = os.getenv("PASSWORD")
14
  uri = f"mongodb+srv://DDR:{password}@cluster0.o7h6s.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
15
+ client = MongoClient(uri, server_api=ServerApi('1'), uuidRepresentation='standard')
16
  try:
17
  client.admin.command('ping')
18
  print("Pinged your deployment. You successfully connected to MongoDB!")
 
21
 
22
  return client
23
 
 
24
  # Max concurrency used for extracting content from documents.
25
  # A long document is broken into smaller chunks this controls
26
  # how many chunks are processed concurrently.
27
+ MAX_CONCURRENCY = int(os.getenv("MAX_CONCURRENCY", 1))
28
 
29
  # Max number of chunks to process per documents
30
  # When a long document is split into chunks, this controls
31
  # how many of those chunks will be processed.
32
  # Set to 0 or negative to disable the max chunks limit.
33
+ MAX_CHUNKS = int(os.getenv("MAX_CHUNKS", -1))
db/models.py CHANGED
@@ -40,7 +40,7 @@ class DDRHEADER(BaseModel):
40
  days_from_spud: Optional[str] = Field(
41
  default='', description="Days from Spud,(DFS) is the number of days from the beginning of the drilling operation to the report date"
42
  )
43
- spud_date: Optional[datetime] = Field(
44
  default='', description="you can find it as spud date (SD) is the date when the drilling operation begin"
45
  )
46
  report_num: Optional[str] = Field(
@@ -98,7 +98,7 @@ class FLUID(BaseModel):
98
  default=0.0, description="Viscosity of the fluid (PV), usually in cP"
99
  )
100
  YP: Optional[float] = Field(
101
- default=0.0, description="Yield Point (YP) of the Mud"
102
  )
103
  temperature: Optional[float] = Field(
104
  default=0.0, description="Temperature of the Mud fluid, usually in °C or °F"
@@ -107,6 +107,19 @@ class FLUID(BaseModel):
107
  default=0.0, description="Depth at which the mud fluid is measured, usually in ft or m"
108
  )
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
 
112
 
 
40
  days_from_spud: Optional[str] = Field(
41
  default='', description="Days from Spud,(DFS) is the number of days from the beginning of the drilling operation to the report date"
42
  )
43
+ spud_date: Optional[str] = Field(
44
  default='', description="you can find it as spud date (SD) is the date when the drilling operation begin"
45
  )
46
  report_num: Optional[str] = Field(
 
98
  default=0.0, description="Viscosity of the fluid (PV), usually in cP"
99
  )
100
  YP: Optional[float] = Field(
101
+ default=0.0, description="Yield Point (YP) of the Mud"
102
  )
103
  temperature: Optional[float] = Field(
104
  default=0.0, description="Temperature of the Mud fluid, usually in °C or °F"
 
107
  default=0.0, description="Depth at which the mud fluid is measured, usually in ft or m"
108
  )
109
 
110
+ class DDR(BaseModel):
111
+ """
112
+ A class representing a Daily Drilling Report (DDR).
113
+ """
114
+ fluid: FLUID = Field(
115
+ ..., description="Daily drilling fluid information."
116
+ )
117
+ ddr_header: DDRHEADER = Field(
118
+ ..., description="Header information for the Daily Drilling Report."
119
+ )
120
+ daily_operations: List[DAILYOPER] = Field(
121
+ ..., description="List of daily summary operations."
122
+ )
123
 
124
 
125
 
graph_version.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+ import uuid
3
+ from typing import (
4
+ Annotated,
5
+ Any,
6
+ Callable,
7
+ Dict,
8
+ List,
9
+ Literal,
10
+ Optional,
11
+ Sequence,
12
+ Type,
13
+ Union,
14
+ )
15
+
16
+ from langchain_core.language_models import BaseChatModel
17
+ from langchain_core.messages import (
18
+ AIMessage,
19
+ AnyMessage,
20
+ BaseMessage,
21
+ HumanMessage,
22
+ ToolCall,
23
+ )
24
+ from langchain_core.prompt_values import PromptValue
25
+ from langchain_core.runnables import (
26
+ Runnable,
27
+ RunnableLambda,
28
+ )
29
+ from typing_extensions import TypedDict
30
+
31
+ from langgraph.graph import StateGraph, START, END
32
+ from langgraph.graph.message import add_messages
33
+ from langgraph.prebuilt import ValidationNode
34
+ from langchain_groq import ChatGroq
35
+
36
+ from db.models import DDR
37
+
38
+ def _default_aggregator(messages: Sequence[AnyMessage]) -> AIMessage:
39
+ for m in messages[::-1]:
40
+ if m.type == "ai":
41
+ return m
42
+ raise ValueError("No AI message found in the sequence.")
43
+
44
+
45
+ class RetryStrategy(TypedDict, total=False):
46
+ """The retry strategy for a tool call."""
47
+
48
+ max_attempts: int
49
+ """The maximum number of attempts to make."""
50
+ fallback: Optional[
51
+ Union[
52
+ Runnable[Sequence[AnyMessage], AIMessage],
53
+ Runnable[Sequence[AnyMessage], BaseMessage],
54
+ Callable[[Sequence[AnyMessage]], AIMessage],
55
+ ]
56
+ ]
57
+ """The function to use once validation fails."""
58
+ aggregate_messages: Optional[Callable[[Sequence[AnyMessage]], AIMessage]]
59
+
60
+
61
+ def _bind_validator_with_retries(
62
+ llm: Union[
63
+ Runnable[Sequence[AnyMessage], AIMessage],
64
+ Runnable[Sequence[BaseMessage], BaseMessage],
65
+ ],
66
+ *,
67
+ validator: ValidationNode,
68
+ retry_strategy: RetryStrategy,
69
+ tool_choice: Optional[str] = None,
70
+ ) -> Runnable[Union[List[AnyMessage], PromptValue], AIMessage]:
71
+ """Binds a tool validators + retry logic to create a runnable validation graph.
72
+
73
+ LLMs that support tool calling can generate structured JSON. However, they may not always
74
+ perfectly follow your requested schema, especially if the schema is nested or has complex
75
+ validation rules. This method allows you to bind a validation function to the LLM's output,
76
+ so that any time the LLM generates a message, the validation function is run on it. If
77
+ the validation fails, the method will retry the LLM with a fallback strategy, the simplest
78
+ being just to add a message to the output with the validation errors and a request to fix them.
79
+
80
+ The resulting runnable expects a list of messages as input and returns a single AI message.
81
+ By default, the LLM can optionally NOT invoke tools, making this easier to incorporate into
82
+ your existing chat bot. You can specify a tool_choice to force the validator to be run on
83
+ the outputs.
84
+
85
+ Args:
86
+ llm (Runnable): The llm that will generate the initial messages (and optionally fallba)
87
+ validator (ValidationNode): The validation logic.
88
+ retry_strategy (RetryStrategy): The retry strategy to use.
89
+ Possible keys:
90
+ - max_attempts: The maximum number of attempts to make.
91
+ - fallback: The LLM or function to use in case of validation failure.
92
+ - aggregate_messages: A function to aggregate the messages over multiple turns.
93
+ Defaults to fetching the last AI message.
94
+ tool_choice: If provided, always run the validator on the tool output.
95
+
96
+ Returns:
97
+ Runnable: A runnable that can be invoked with a list of messages and returns a single AI message.
98
+ """
99
+
100
+ def add_or_overwrite_messages(left: list, right: Union[list, dict]) -> list:
101
+ """Append messages. If the update is a 'finalized' output, replace the whole list."""
102
+ if isinstance(right, dict) and "finalize" in right:
103
+ finalized = right["finalize"]
104
+ if not isinstance(finalized, list):
105
+ finalized = [finalized]
106
+ for m in finalized:
107
+ if m.id is None:
108
+ m.id = str(uuid.uuid4())
109
+ return finalized
110
+ res = add_messages(left, right)
111
+ if not isinstance(res, list):
112
+ return [res]
113
+ return res
114
+
115
+ class State(TypedDict):
116
+ messages: Annotated[list, add_or_overwrite_messages]
117
+ attempt_number: Annotated[int, operator.add]
118
+ initial_num_messages: int
119
+ input_format: Literal["list", "dict"]
120
+
121
+ builder = StateGraph(State)
122
+
123
+ def dedict(x: State) -> list:
124
+ """Get the messages from the state."""
125
+ return x["messages"]
126
+
127
+ model = dedict | llm | (lambda msg: {"messages": [msg], "attempt_number": 1})
128
+ fbrunnable = retry_strategy.get("fallback")
129
+ if fbrunnable is None:
130
+ fb_runnable = llm
131
+ elif isinstance(fbrunnable, Runnable):
132
+ fb_runnable = fbrunnable # type: ignore
133
+ else:
134
+ fb_runnable = RunnableLambda(fbrunnable)
135
+ fallback = (
136
+ dedict | fb_runnable | (lambda msg: {"messages": [msg], "attempt_number": 1})
137
+ )
138
+
139
+ def count_messages(state: State) -> dict:
140
+ return {"initial_num_messages": len(state.get("messages", []))}
141
+
142
+ builder.add_node("count_messages", count_messages)
143
+ builder.add_node("llm", model)
144
+ builder.add_node("fallback", fallback)
145
+
146
+ # To support patch-based retries, we need to be able to
147
+ # aggregate the messages over multiple turns.
148
+ # The next sequence selects only the relevant messages
149
+ # and then applies the validator
150
+ select_messages = retry_strategy.get("aggregate_messages") or _default_aggregator
151
+
152
+ def select_generated_messages(state: State) -> list:
153
+ """Select only the messages generated within this loop."""
154
+ selected = state["messages"][state["initial_num_messages"] :]
155
+ return [select_messages(selected)]
156
+
157
+ def endict_validator_output(x: Sequence[AnyMessage]) -> dict:
158
+ if tool_choice and not x:
159
+ return {
160
+ "messages": [
161
+ HumanMessage(
162
+ content=f"ValidationError: please respond with a valid tool call [tool_choice={tool_choice}].",
163
+ additional_kwargs={"is_error": True},
164
+ )
165
+ ]
166
+ }
167
+ return {"messages": x}
168
+
169
+ validator_runnable = select_generated_messages | validator | endict_validator_output
170
+ builder.add_node("validator", validator_runnable)
171
+
172
+ class Finalizer:
173
+ """Pick the final message to return from the retry loop."""
174
+
175
+ def __init__(self, aggregator: Optional[Callable[[list], AIMessage]] = None):
176
+ self._aggregator = aggregator or _default_aggregator
177
+
178
+ def __call__(self, state: State) -> dict:
179
+ """Return just the AI message."""
180
+ initial_num_messages = state["initial_num_messages"]
181
+ generated_messages = state["messages"][initial_num_messages:]
182
+ return {
183
+ "messages": {
184
+ "finalize": self._aggregator(generated_messages),
185
+ }
186
+ }
187
+
188
+ # We only want to emit the final message
189
+ builder.add_node("finalizer", Finalizer(retry_strategy.get("aggregate_messages")))
190
+
191
+ # Define the connectivity
192
+ builder.add_edge(START, "count_messages")
193
+ builder.add_edge("count_messages", "llm")
194
+
195
+ def route_validator(state: State):
196
+ if state["messages"][-1].tool_calls or tool_choice is not None:
197
+ return "validator"
198
+ return END
199
+
200
+ builder.add_conditional_edges("llm", route_validator, ["validator", END])
201
+ builder.add_edge("fallback", "validator")
202
+ max_attempts = retry_strategy.get("max_attempts", 3)
203
+
204
+ def route_validation(state: State):
205
+ if state["attempt_number"] > max_attempts:
206
+ raise ValueError(
207
+ f"Could not extract a valid value in {max_attempts} attempts."
208
+ )
209
+ for m in state["messages"][::-1]:
210
+ if m.type == "ai":
211
+ break
212
+ if m.additional_kwargs.get("is_error"):
213
+ return "fallback"
214
+ return "finalizer"
215
+
216
+ builder.add_conditional_edges(
217
+ "validator", route_validation, ["finalizer", "fallback"]
218
+ )
219
+
220
+ builder.add_edge("finalizer", END)
221
+
222
+ # These functions let the step be used in a MessageGraph
223
+ # or a StateGraph with 'messages' as the key.
224
+ def encode(x: Union[Sequence[AnyMessage], PromptValue]) -> dict:
225
+ """Ensure the input is the correct format."""
226
+ if isinstance(x, PromptValue):
227
+ return {"messages": x.to_messages(), "input_format": "list"}
228
+ if isinstance(x, list):
229
+ return {"messages": x, "input_format": "list"}
230
+ raise ValueError(f"Unexpected input type: {type(x)}")
231
+
232
+ def decode(x: State) -> AIMessage:
233
+ """Ensure the output is in the expected format."""
234
+ return x["messages"][-1]
235
+
236
+ return (
237
+ encode | builder.compile().with_config(run_name="ValidationGraph") | decode
238
+ ).with_config(run_name="ValidateWithRetries")
239
+
240
+
241
+ def bind_validator_with_retries(
242
+ llm: BaseChatModel,
243
+ *,
244
+ tools: list,
245
+ tool_choice: Optional[str] = None,
246
+ max_attempts: int = 3,
247
+ ) -> Runnable[Union[List[AnyMessage], PromptValue], AIMessage]:
248
+ """Binds validators + retry logic ensure validity of generated tool calls.
249
+
250
+ LLMs that support tool calling are good at generating structured JSON. However, they may
251
+ not always perfectly follow your requested schema, especially if the schema is nested or
252
+ has complex validation rules. This method allows you to bind a validation function to
253
+ the LLM's output, so that any time the LLM generates a message, the validation function
254
+ is run on it. If the validation fails, the method will retry the LLM with a fallback
255
+ strategy, the simples being just to add a message to the output with the validation
256
+ errors and a request to fix them.
257
+
258
+ The resulting runnable expects a list of messages as input and returns a single AI message.
259
+ By default, the LLM can optionally NOT invoke tools, making this easier to incorporate into
260
+ your existing chat bot. You can specify a tool_choice to force the validator to be run on
261
+ the outputs.
262
+
263
+ Args:
264
+ llm (Runnable): The llm that will generate the initial messages (and optionally fallba)
265
+ validator (ValidationNode): The validation logic.
266
+ retry_strategy (RetryStrategy): The retry strategy to use.
267
+ Possible keys:
268
+ - max_attempts: The maximum number of attempts to make.
269
+ - fallback: The LLM or function to use in case of validation failure.
270
+ - aggregate_messages: A function to aggregate the messages over multiple turns.
271
+ Defaults to fetching the last AI message.
272
+ tool_choice: If provided, always run the validator on the tool output.
273
+
274
+ Returns:
275
+ Runnable: A runnable that can be invoked with a list of messages and returns a single AI message.
276
+ """
277
+ bound_llm = llm.bind_tools(tools, tool_choice=tool_choice)
278
+ retry_strategy = RetryStrategy(max_attempts=max_attempts)
279
+ validator = ValidationNode(tools)
280
+ return _bind_validator_with_retries(
281
+ bound_llm,
282
+ validator=validator,
283
+ tool_choice=tool_choice,
284
+ retry_strategy=retry_strategy,
285
+ ).with_config(metadata={"retry_strategy": "default"})
286
+
287
+
288
+ from pydantic import BaseModel, Field, field_validator
289
+
290
+
291
+ class Respond(BaseModel):
292
+ """Use to generate the response. Always use when responding to the user"""
293
+
294
+ reason: str = Field(description="Step-by-step justification for the answer.")
295
+ answer: str
296
+
297
+ @field_validator("answer")
298
+ def reason_contains_apology(cls, answer: str):
299
+ if "llama" not in answer.lower():
300
+ raise ValueError(
301
+ "You MUST start with a gimicky, rhyming advertisement for using a Llama V3 (an LLM) in your **answer** field."
302
+ " Must be an instant hit. Must be weaved into the answer."
303
+ )
304
+
305
+
306
+ import getpass
307
+ import os
308
+
309
+ from huggingface_hub import login
310
+ from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
311
+ from langchain_core.prompts import ChatPromptTemplate
312
+ #login()
313
+
314
+ # llm = HuggingFaceEndpoint(
315
+ # repo_id="mistralai/Mistral-Nemo-Instruct-2407",
316
+ # task="text-generation",
317
+ # max_new_tokens=512,
318
+ # do_sample=False,
319
+ # repetition_penalty=1.03,
320
+ # )
321
+
322
+ #chat = ChatHuggingFace(llm=llm, verbose=True)
323
+ #bound_llm= chat.bind_tools( tools=tools)
324
+ #llm = ChatAnthropic(model="claude-3-haiku-20240307")
325
+ print(os.environ["OPENAI_API_KEY"] )
326
+
327
+ from langchain_openai import ChatOpenAI
328
+
329
+ # llm= ChatGroq(
330
+ # temperature=0,
331
+ # groq_api_key='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',
332
+ # model_name="llama-3.1-8b-instant"
333
+ # )
334
+ #bound_llm = bind_validator_with_retries(llm, tools=tools)
335
+
336
+
337
+ llm=ChatOpenAI( model= "gpt-4o-mini")
338
+ prompt = ChatPromptTemplate.from_messages(
339
+ [
340
+ ("system", "Respond directly by calling the Respond function and nothing else."),
341
+ ("placeholder", "{messages}"),
342
+ ]
343
+ )
344
+
345
+ import logging
346
+
347
+ logger = logging.getLogger("extraction")
348
+
349
+ tools = [DDR]
350
+ def bind_validator_with_jsonpatch_retries(
351
+ llm: BaseChatModel,
352
+ *,
353
+ tools: list,
354
+ tool_choice: Optional[str] = None,
355
+ max_attempts: int = 3,
356
+ ) -> Runnable[Union[List[AnyMessage], PromptValue], AIMessage]:
357
+ """Binds validators + retry logic ensure validity of generated tool calls.
358
+
359
+ This method is similar to `bind_validator_with_retries`, but uses JSONPatch to correct
360
+ validation errors caused by passing in incorrect or incomplete parameters in a previous
361
+ tool call. This method requires the 'jsonpatch' library to be installed.
362
+
363
+ Using patch-based function healing can be more efficient than repopulating the entire
364
+ tool call from scratch, and it can be an easier task for the LLM to perform, since it typically
365
+ only requires a few small changes to the existing tool call.
366
+
367
+ Args:
368
+ llm (Runnable): The llm that will generate the initial messages (and optionally fallba)
369
+ tools (list): The tools to bind to the LLM.
370
+ tool_choice (Optional[str]): The tool choice to use.
371
+ max_attempts (int): The number of attempts to make.
372
+
373
+ Returns:
374
+ Runnable: A runnable that can be invoked with a list of messages and returns a single AI message.
375
+ """
376
+
377
+ try:
378
+ import jsonpatch # type: ignore[import-untyped]
379
+ except ImportError:
380
+ raise ImportError(
381
+ "The 'jsonpatch' library is required for JSONPatch-based retries."
382
+ )
383
+
384
+ class JsonPatch(BaseModel):
385
+ """A JSON Patch document represents an operation to be performed on a JSON document.
386
+
387
+ Note that the op and path are ALWAYS required. Value is required for ALL operations except 'remove'.
388
+ Examples:
389
+
390
+ \`\`\`json
391
+ {"op": "add", "path": "/a/b/c", "patch_value": 1}
392
+ {"op": "replace", "path": "/a/b/c", "patch_value": 2}
393
+ {"op": "remove", "path": "/a/b/c"}
394
+ \`\`\`
395
+ """
396
+
397
+ op: Literal["add", "remove", "replace"] = Field(
398
+ ...,
399
+ description="The operation to be performed. Must be one of 'add', 'remove', 'replace'.",
400
+ )
401
+ path: str = Field(
402
+ ...,
403
+ description="A JSON Pointer path that references a location within the target document where the operation is performed.",
404
+ )
405
+ value: Any = Field(
406
+ ...,
407
+ description="The value to be used within the operation. REQUIRED for 'add', 'replace', and 'test' operations.",
408
+ )
409
+
410
+ class PatchFunctionParameters(BaseModel):
411
+ """Respond with all JSONPatch operation to correct validation errors caused by passing in incorrect or incomplete parameters in a previous tool call."""
412
+
413
+ tool_call_id: str = Field(
414
+ ...,
415
+ description="The ID of the original tool call that generated the error. Must NOT be an ID of a PatchFunctionParameters tool call.",
416
+ )
417
+ reasoning: str = Field(
418
+ ...,
419
+ description="Think step-by-step, listing each validation error and the"
420
+ " JSONPatch operation needed to correct it. "
421
+ "Cite the fields in the JSONSchema you referenced in developing this plan.",
422
+ )
423
+ patches: list[JsonPatch] = Field(
424
+ ...,
425
+ description="A list of JSONPatch operations to be applied to the previous tool call's response.",
426
+ )
427
+
428
+ bound_llm = llm.bind_tools(tools, tool_choice=tool_choice)
429
+ fallback_llm = llm.bind_tools([PatchFunctionParameters])
430
+
431
+ def aggregate_messages(messages: Sequence[AnyMessage]) -> AIMessage:
432
+ # Get all the AI messages and apply json patches
433
+ resolved_tool_calls: Dict[Union[str, None], ToolCall] = {}
434
+ content: Union[str, List[Union[str, dict]]] = ""
435
+ for m in messages:
436
+ if m.type != "ai":
437
+ continue
438
+ if not content:
439
+ content = m.content
440
+ for tc in m.tool_calls:
441
+ if tc["name"] == PatchFunctionParameters.__name__:
442
+ tcid = tc["args"]["tool_call_id"]
443
+ if tcid not in resolved_tool_calls:
444
+ logger.debug(
445
+ f"JsonPatch tool call ID {tc['args']['tool_call_id']} not found."
446
+ f"Valid tool call IDs: {list(resolved_tool_calls.keys())}"
447
+ )
448
+ tcid = next(iter(resolved_tool_calls.keys()), None)
449
+ orig_tool_call = resolved_tool_calls[tcid]
450
+ current_args = orig_tool_call["args"]
451
+ patches = tc["args"].get("patches") or []
452
+ orig_tool_call["args"] = jsonpatch.apply_patch(
453
+ current_args,
454
+ patches,
455
+ )
456
+ orig_tool_call["id"] = tc["id"]
457
+ else:
458
+ resolved_tool_calls[tc["id"]] = tc.copy()
459
+ return AIMessage(
460
+ content=content,
461
+ tool_calls=list(resolved_tool_calls.values()),
462
+ )
463
+
464
+ def format_exception(error: BaseException, call: ToolCall, schema: Type[BaseModel]):
465
+ return (
466
+ f"Error:\n\n\`\`\`\n{repr(error)}\n\`\`\`\n"
467
+ "Expected Parameter Schema:\n\n" + f"\`\`\`json\n{schema.schema_json()}\n\`\`\`\n"
468
+ f"Please respond with a JSONPatch to correct the error for tool_call_id=[{call['id']}]."
469
+ )
470
+
471
+ validator = ValidationNode(
472
+ tools + [PatchFunctionParameters],
473
+ format_error=format_exception,
474
+ )
475
+ retry_strategy = RetryStrategy(
476
+ max_attempts=max_attempts,
477
+ fallback=fallback_llm,
478
+ aggregate_messages=aggregate_messages,
479
+ )
480
+ return _bind_validator_with_retries(
481
+ bound_llm,
482
+ validator=validator,
483
+ retry_strategy=retry_strategy,
484
+ tool_choice=tool_choice,
485
+ ).with_config(metadata={"retry_strategy": "jsonpatch"})
486
+
487
+ def extract_drilling_information(formatted: str) -> Any:
488
+ # bound_llm = bind_validator_with_retries(llm, tools=[Respond])
489
+ # chain = prompt | bound_llm
490
+ # results = chain.invoke({"messages": [("user", "Does P = NP?")]})
491
+ # results.pretty_print()
492
+ bound_llm = bind_validator_with_jsonpatch_retries(llm, tools=tools)
493
+ chain = prompt | bound_llm
494
+ results = chain.invoke(
495
+ {
496
+ "messages": [
497
+ (
498
+ "user",
499
+ f"Extract the drilling information from the following DDR respond with the necessary to0l call only, nothing else:\n\n<ddr>\n{formatted}\n</ddr>",
500
+ ),
501
+ ]
502
+ },
503
+ )
504
+ print (results.tool_calls[0])
505
+ return results.tool_calls[0]
requirements.txt CHANGED
@@ -14,4 +14,12 @@ python_magic
14
  typing_extensions
15
  python-multipart
16
  pdfplumber
17
- tiktoken
 
 
 
 
 
 
 
 
 
14
  typing_extensions
15
  python-multipart
16
  pdfplumber
17
+ tiktoken
18
+ pandas
19
+ python-dotenv
20
+ langgraph
21
+ jsonpatch
22
+ langchain_openai
23
+ PyMuPDF
24
+ pillow
25
+ IPython