Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/local_models/pdf_scraper_ollama.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

graph_config = {
"llm": {
"model": "ollama/llama3",
"model": "ollama/mistral",
"temperature": 0,
"format": "json", # Ollama needs the format to be specified explicitly
"model_tokens": 4000,
Expand Down
61 changes: 28 additions & 33 deletions examples/openai/pdf_scraper_multi_openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,63 +6,58 @@
from dotenv import load_dotenv
from scrapegraphai.graphs import PdfScraperMultiGraph

from pydantic import BaseModel, Field
from typing import List

load_dotenv()

openai_key = os.getenv("OPENAI_APIKEY")

# ************************************************
# Define the configuration for the graph
# ************************************************

graph_config = {
"llm": {
"api_key": openai_key,
"model": "gpt-3.5-turbo",
},
"verbose": True,
}

# Covert to list
sources = [
"This paper provides evidence from a natural experiment on the relationship between positive affect and productivity. We link highly detailed administrative data on the behaviors and performance of all telesales workers at a large telecommunications company with survey reports of employee happiness that we collected on a weekly basis. We use variation in worker mood arising from visual exposure to weather—the interaction between call center architecture and outdoor weather conditions—in order to provide a quasi-experimental test of the effect of happiness on productivity. We find evidence of a positive impact on sales performance, which is driven by changes in labor productivity – largely through workers converting more calls into sales, and to a lesser extent by making more calls per hour and adhering more closely to their schedule. We find no evidence in our setting of effects on measures of high-frequency labor supply such as attendance and break-taking.",
"This paper provides evidence from a natural experiment on the relationship between positive affect and productivity. We link highly detailed administrative data on the behaviors and performance of all telesales workers at a large telecommunications company with survey reports of employee happiness that we collected on a weekly basis. We use variation in worker mood arising from visual exposure to weather—the interaction between call center architecture and outdoor weather conditions—in order to provide a quasi-experimental test of the effect of happiness on productivity. We find evidence of a positive impact on sales performance, which is driven by changes in labor productivity – largely through workers converting more calls into sales, and to a lesser extent by making more calls per hour and adhering more closely to their schedule. We find no evidence in our setting of effects on measures of high-frequency labor supply such as attendance and break-taking.",
"This paper provides evidence from a natural experiment on the relationship between positive affect and productivity. We link highly detailed administrative data on the behaviors and performance of all telesales workers at a large telecommunications company with survey reports of employee happiness that we collected on a weekly basis. We use variation in worker mood arising from visual exposure to weather—the interaction between call center architecture and outdoor weather conditions—in order to provide a quasi-experimental test of the effect of happiness on productivity. We find evidence of a positive impact on sales performance, which is driven by changes in labor productivity – largely through workers converting more calls into sales, and to a lesser extent by making more calls per hour and adhering more closely to their schedule. We find no evidence in our setting of effects on measures of high-frequency labor supply such as attendance and break-taking.",
"This paper provides evidence from a natural experiment on the relationship between positive affect and productivity. We link highly detailed administrative data on the behaviors and performance of all telesales workers at a large telecommunications company with survey reports of employee happiness that we collected on a weekly basis. We use variation in worker mood arising from visual exposure to weather—the interaction between call center architecture and outdoor weather conditions—in order to provide a quasi-experimental test of the effect of happiness on productivity. We find evidence of a positive impact on sales performance, which is driven by changes in labor productivity – largely through workers converting more calls into sales, and to a lesser extent by making more calls per hour and adhering more closely to their schedule. We find no evidence in our setting of effects on measures of high-frequency labor supply such as attendance and break-taking.",
]

prompt = """
You are an expert in reviewing academic manuscripts. Please analyze the abstracts provided from an academic journal article to extract and clearly identify the following elements:

Independent Variable (IV): The variable that is manipulated or considered as the primary cause affecting other variables.
Dependent Variable (DV): The variable that is measured or observed, which is expected to change as a result of variations in the Independent Variable.
Exogenous Shock: Identify any external or unexpected events used in the study that serve as a natural experiment or provide a unique setting for observing the effects on the IV and DV.
Response Format: For each abstract, present your response in the following structured format:
# ************************************************
# Define the output schema for the graph
# ************************************************

Independent Variable (IV):
Dependent Variable (DV):
Exogenous Shock:
class Article(BaseModel):
independent_variable: str = Field(description="(IV): The variable that is manipulated or considered as the primary cause affecting other variables.")
dependent_variable: str = Field(description="(DV) The variable that is measured or observed, which is expected to change as a result of variations in the Independent Variable.")
exogenous_shock: str = Field(description="Identify any external or unexpected events used in the study that serve as a natural experiment or provide a unique setting for observing the effects on the IV and DV.")

Example Queries and Responses:
class Articles(BaseModel):
articles: List[Article]

Query: This paper provides evidence from a natural experiment on the relationship between positive affect and productivity. We link highly detailed administrative data on the behaviors and performance of all telesales workers at a large telecommunications company with survey reports of employee happiness that we collected on a weekly basis. We use variation in worker mood arising from visual exposure to weather the interaction between call center architecture and outdoor weather conditions in order to provide a quasi-experimental test of the effect of happiness on productivity. We find evidence of a positive impact on sales performance, which is driven by changes in labor productivity largely through workers converting more calls into sales, and to a lesser extent by making more calls per hour and adhering more closely to their schedule. We find no evidence in our setting of effects on measures of high-frequency labor supply such as attendance and break-taking.
# ************************************************
# Define the sources for the graph
# ************************************************

Response:

Independent Variable (IV): Employee happiness.
Dependent Variable (DV): Overall firm productivity.
Exogenous Shock: Sudden company-wide increase in bonus payments.

Query: The diffusion of social media coincided with a worsening of mental health conditions among adolescents and young adults in the United States, giving rise to speculation that social media might be detrimental to mental health. In this paper, we provide quasi-experimental estimates of the impact of social media on mental health by leveraging a unique natural experiment: the staggered introduction of Facebook across U.S. colleges. Our analysis couples data on student mental health around the years of Facebook's expansion with a generalized difference-in-differences empirical strategy. We find that the roll-out of Facebook at a college increased symptoms of poor mental health, especially depression. We also find that, among students predicted to be most susceptible to mental illness, the introduction of Facebook led to increased utilization of mental healthcare services. Lastly, we find that, after the introduction of Facebook, students were more likely to report experiencing impairments to academic performance resulting from poor mental health. Additional evidence on mechanisms suggests that the results are due to Facebook fostering unfavorable social comparisons.

Response:
sources = [
"This paper provides evidence from a natural experiment on the relationship between positive affect and productivity. We link highly detailed administrative data on the behaviors and performance of all telesales workers at a large telecommunications company with survey reports of employee happiness that we collected on a weekly basis. We use variation in worker mood arising from visual exposure to weather the interaction between call center architecture and outdoor weather conditions in order to provide a quasi-experimental test of the effect of happiness on productivity. We find evidence of a positive impact on sales performance, which is driven by changes in labor productivity largely through workers converting more calls into sales, and to a lesser extent by making more calls per hour and adhering more closely to their schedule. We find no evidence in our setting of effects on measures of high-frequency labor supply such as attendance and break-taking.",
"The diffusion of social media coincided with a worsening of mental health conditions among adolescents and young adults in the United States, giving rise to speculation that social media might be detrimental to mental health. Our analysis couples data on student mental health around the years of Facebook's expansion with a generalized difference-in-differences empirical strategy. We find that the roll-out of Facebook at a college increased symptoms of poor mental health, especially depression. We also find that, among students predicted to be most susceptible to mental illness, the introduction of Facebook led to increased utilization of mental healthcare services. Lastly, we find that, after the introduction of Facebook, students were more likely to report experiencing impairments to academic performance resulting from poor mental health. Additional evidence on mechanisms suggests that the results are due to Facebook fostering unfavorable social comparisons."
]

Independent Variable (IV): Exposure to social media.
Dependent Variable (DV): Mental health outcomes.
Exogenous Shock: staggered introduction of Facebook across U.S. colleges.
prompt = """
Analyze the abstracts provided from an academic journal article to extract and clearly identify the Independent Variable (IV), Dependent Variable (DV), and Exogenous Shock.
"""

# *******************************************************
# Create the SmartScraperMultiGraph instance and run it
# *******************************************************

multiple_search_graph = PdfScraperMultiGraph(
prompt=prompt,
source= sources,
schema=None,
schema=Articles,
config=graph_config
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

pdf_scraper_graph = PDFScraperGraph(
prompt="Summarize the text and find the main topics",
source=source,
source="Laureaconanniaccademici.pdf",
config=graph_config,
)
result = pdf_scraper_graph.run()
Expand Down
14 changes: 13 additions & 1 deletion scrapegraphai/graphs/pdf_scraper_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from ..nodes import (
FetchNode,
ParseNode,
RAGNode,
GenerateAnswerPDFNode
)
Expand Down Expand Up @@ -66,6 +67,15 @@ def _create_graph(self) -> BaseGraph:
output=["doc"],
)

parse_node = ParseNode(
input="doc",
output=["parsed_doc"],
node_config={
"parse_html": False,
"chunk_size": self.model_token
}
)

rag_node = RAGNode(
input="user_prompt & (parsed_doc | doc)",
output=["relevant_chunks"],
Expand All @@ -86,11 +96,13 @@ def _create_graph(self) -> BaseGraph:
return BaseGraph(
nodes=[
fetch_node,
parse_node,
rag_node,
generate_answer_node_pdf,
],
edges=[
(fetch_node, rag_node),
(fetch_node, parse_node),
(parse_node, rag_node),
(rag_node, generate_answer_node_pdf)
],
entry_point=fetch_node
Expand Down
6 changes: 5 additions & 1 deletion scrapegraphai/graphs/pdf_scraper_multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from copy import copy, deepcopy
from typing import List, Optional
from pydantic import BaseModel

from .base_graph import BaseGraph
from .abstract_graph import AbstractGraph
Expand Down Expand Up @@ -43,7 +44,7 @@ class PdfScraperMultiGraph(AbstractGraph):
>>> result = search_graph.run()
"""

def __init__(self, prompt: str, source: List[str], config: dict, schema: Optional[str] = None):
def __init__(self, prompt: str, source: List[str], config: dict, schema: Optional[BaseModel] = None):

self.max_results = config.get("max_results", 3)

Expand All @@ -52,6 +53,8 @@ def __init__(self, prompt: str, source: List[str], config: dict, schema: Optiona
else:
self.copy_config = deepcopy(config)

self.copy_schema = deepcopy(schema)

super().__init__(prompt, config, source, schema)

def _create_graph(self) -> BaseGraph:
Expand All @@ -70,6 +73,7 @@ def _create_graph(self) -> BaseGraph:
prompt="",
source="",
config=self.copy_config,
schema=self.copy_schema
)

# ************************************************
Expand Down
3 changes: 1 addition & 2 deletions scrapegraphai/graphs/smart_scraper_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
"""

from typing import Optional
import logging
from pydantic import BaseModel

from .base_graph import BaseGraph
from .abstract_graph import AbstractGraph

Expand Down Expand Up @@ -68,7 +68,6 @@ def _create_graph(self) -> BaseGraph:
"loader_kwargs": self.config.get("loader_kwargs", {}),
}
)

parse_node = ParseNode(
input="doc",
output=["parsed_doc"],
Expand Down
4 changes: 3 additions & 1 deletion scrapegraphai/nodes/fetch_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,10 @@ def execute(self, state):

state.update({self.output[0]: compressed_document})
return state
# handling for pdf
# handling pdf
elif input_keys[0] == "pdf":

# TODO: fix bytes content issue
loader = PyPDFLoader(source)
compressed_document = loader.load()
state.update({self.output[0]: compressed_document})
Expand Down
2 changes: 1 addition & 1 deletion scrapegraphai/nodes/generate_answer_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def execute(self, state: dict) -> dict:
"format_instructions": format_instructions})
chain = prompt | self.llm_model | output_parser
answer = chain.invoke({"question": user_prompt})

else:
prompt = PromptTemplate(
template=template_chunks,
Expand Down
4 changes: 2 additions & 2 deletions scrapegraphai/nodes/generate_answer_pdf_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,13 +113,13 @@ def execute(self, state):
template=template_no_chunks_pdf,
input_variables=["question"],
partial_variables={
"context":chunk,
"context":chunk.page_content,
"format_instructions": format_instructions,
},
)

chain = prompt | self.llm_model | output_parser
answer = chain.invoke({"question": user_prompt})

else:
prompt = PromptTemplate(
template=template_chunks_pdf,
Expand Down
28 changes: 22 additions & 6 deletions scrapegraphai/nodes/parse_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import List, Optional
from semchunk import chunk
from langchain_community.document_transformers import Html2TextTransformer
from langchain_core.documents import Document
from ..utils.logging import get_logger
from .base_node import BaseNode

Expand Down Expand Up @@ -70,12 +71,27 @@ def execute(self, state: dict) -> dict:
docs_transformed = input_data[0]
if self.parse_html:
docs_transformed = Html2TextTransformer().transform_documents(input_data[0])
docs_transformed = docs_transformed[0]

chunks = chunk(text=docs_transformed.page_content,
chunk_size= self.node_config.get("chunk_size", 4096),
token_counter=lambda x: len(x.split()),
memoize=False)
docs_transformed = docs_transformed[0]

chunks = chunk(text=docs_transformed.page_content,
chunk_size= self.node_config.get("chunk_size", 4096),
token_counter=lambda x: len(x.split()),
memoize=False)
else:
docs_transformed = docs_transformed[0]

if type(docs_transformed) == Document:
chunks = chunk(text=docs_transformed.page_content,
chunk_size= self.node_config.get("chunk_size", 4096),
token_counter=lambda x: len(x.split()),
memoize=False)
else:

chunks = chunk(text=docs_transformed,
chunk_size= self.node_config.get("chunk_size", 4096),
token_counter=lambda x: len(x.split()),
memoize=False)

state.update({self.output[0]: chunks})

return state