repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
gpt-researcher
gpt_researcher/llm_provider/generic/__init__.py
.py
from .base import GenericLLMProvider __all__ = ["GenericLLMProvider"]
3
70
gpt-researcher
gpt_researcher/llm_provider/generic/base.py
.py
import aiofiles import asyncio import importlib import json import subprocess import sys import traceback from typing import Any from colorama import Fore, Style, init import os from enum import Enum _SUPPORTED_PROVIDERS = { "openai", "anthropic", "azure_openai", "cohere", "google_vertexai", "g...
421
14,789
gpt-researcher
gpt_researcher/context/__init__.py
.py
from .compression import ContextCompressor from .retriever import SearchAPIRetriever __all__ = ['ContextCompressor', 'SearchAPIRetriever']
5
140
gpt-researcher
gpt_researcher/context/retriever.py
.py
import os from enum import Enum from typing import Any, Dict, List, Optional from langchain_core.callbacks import CallbackManagerForRetrieverRun from langchain_core.documents import Document from langchain_core.retrievers import BaseRetriever # Maximum characters of raw_content to embed per document. # Large document...
71
2,275
gpt-researcher
gpt_researcher/context/compression.py
.py
"""Context compression utilities for GPT Researcher. This module provides classes for compressing and retrieving relevant context from documents using embeddings and similarity filtering. The compression pipeline: 1. Splits documents into chunks 2. Filters chunks by embedding similarity to the query 3. Returns the mo...
266
10,655
gpt-researcher
gpt_researcher/document/azure_document_loader.py
.py
from azure.storage.blob import BlobServiceClient import tempfile from pathlib import Path, PurePosixPath class AzureDocumentLoader: def __init__(self, container_name, connection_string): self.client = BlobServiceClient.from_connection_string(connection_string) self.container = self.client.get_cont...
38
1,618
gpt-researcher
gpt_researcher/document/online_document.py
.py
import os import aiohttp import tempfile from langchain_community.document_loaders import ( PyMuPDFLoader, TextLoader, UnstructuredCSVLoader, UnstructuredExcelLoader, UnstructuredMarkdownLoader, UnstructuredPowerPointLoader, UnstructuredWordDocumentLoader ) class OnlineDocumentLoader: ...
96
3,459
gpt-researcher
gpt_researcher/document/document.py
.py
import asyncio import os from typing import List, Union from langchain_community.document_loaders import ( PyMuPDFLoader, TextLoader, UnstructuredCSVLoader, UnstructuredExcelLoader, UnstructuredMarkdownLoader, UnstructuredPowerPointLoader, UnstructuredWordDocumentLoader ) from langchain_comm...
93
3,690
gpt-researcher
gpt_researcher/document/langchain_document.py
.py
import asyncio import os from langchain_core.documents import Document from typing import List, Dict # Supports the base Document class from langchain # - https://github.com/langchain-ai/langchain/blob/master/libs/core/langchain_core/documents/base.py class LangChainDocumentLoader: def __init__(self, documents:...
25
743
gpt-researcher
gpt_researcher/actions/agent_creator.py
.py
"""Agent creation and selection utilities for GPT Researcher. This module provides functions to automatically select and configure the appropriate research agent based on the query type. """ import json import logging import re import json_repair from ..prompts import PromptFamily from ..utils.llm import create_cha...
132
4,454
gpt-researcher
gpt_researcher/actions/utils.py
.py
from typing import Dict, Any, Callable from ..utils.logger import get_formatted_logger logger = get_formatted_logger() async def stream_output( type, content, output, websocket=None, output_log=True, metadata=None ): """ Streams output to the websocket Args: type: content: out...
163
4,689
gpt-researcher
gpt_researcher/actions/__init__.py
.py
from .retriever import get_retriever, get_retrievers from .query_processing import plan_research_outline, get_search_results from .agent_creator import extract_json_with_regex, choose_agent from .web_scraping import scrape_urls from .report_generation import write_conclusion, summarize_url, generate_draft_section_title...
27
935
gpt-researcher
gpt_researcher/actions/retriever.py
.py
"""Retriever factory and utilities for GPT Researcher. This module provides functions to instantiate and manage various search retriever implementations. """ def get_retriever(retriever: str): """Get a retriever class by name. Args: retriever: The name of the retriever to get (e.g., 'google', 'tavil...
179
5,795
gpt-researcher
gpt_researcher/actions/report_generation.py
.py
import asyncio from typing import List, Dict, Any from ..config.config import Config from ..utils.llm import create_chat_completion from ..utils.logger import get_formatted_logger from ..prompts import PromptFamily, get_prompt_by_report_type from ..utils.enum import Tone logger = get_formatted_logger() async def wri...
310
10,156
gpt-researcher
gpt_researcher/actions/markdown_processing.py
.py
import re import markdown from typing import List, Dict def extract_headers(markdown_text: str) -> List[Dict]: """ Extract headers from markdown text. Args: markdown_text (str): The markdown text to process. Returns: List[Dict]: A list of dictionaries representing the header structure...
116
3,716
gpt-researcher
gpt_researcher/actions/query_processing.py
.py
import json_repair from gpt_researcher.llm_provider.generic.base import ReasoningEfforts def _normalize_sub_queries(parsed: Any, fallback_query: str) -> List[str]: """Coerce a parsed LLM response into a flat list of query strings. ``json_repair.loads`` may return a list, a dict (e.g. ``{"queries": [...]}`` ...
215
7,624
gpt-researcher
gpt_researcher/actions/web_scraping.py
.py
from typing import Any from colorama import Fore, Style from gpt_researcher.utils.workers import WorkerPool from ..scraper import Scraper from ..config.config import Config from ..utils.logger import get_formatted_logger logger = get_formatted_logger() async def scrape_urls( urls, cfg: Config, worker_pool: Work...
108
3,367
gpt-researcher
gpt_researcher/retrievers/utils.py
.py
"""Utility functions for GPT Researcher retrievers. This module provides helper functions and constants used by the various search retriever implementations. """ import importlib.util import logging import os import sys logger = logging.getLogger(__name__) async def stream_output(log_type, step, content, websocket=...
108
2,782
gpt-researcher
gpt_researcher/retrievers/__init__.py
.py
from .arxiv.arxiv import ArxivSearch from .bing.bing import BingSearch from .brave.brave import BraveSearch from .custom.custom import CustomRetriever from .duckduckgo.duckduckgo import Duckduckgo from .google.google import GoogleSearch from .pubmed_central.pubmed_central import PubMedCentralSearch from .searx.searx im...
46
1,351
gpt-researcher
gpt_researcher/retrievers/pubmed_central/pubmed_central.py
.py
from typing import List, Dict, Any, Optional import os import xml.etree.ElementTree as ET import requests class PubMedCentralSearch: """ PubMed Central Full-Text Search """ def __init__(self, query: str, query_domains=None): self.base_search_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutil...
157
5,773
gpt-researcher
gpt_researcher/retrievers/exa/exa.py
.py
import os from ..utils import check_pkg class ExaSearch: """ Exa API Retriever """ def __init__(self, query, query_domains=None): """ Initializes the ExaSearch object. Args: query: The search query. """ # This validation is necessary since exa_py is...
114
3,889
gpt-researcher
gpt_researcher/retrievers/getxapi/getxapi.py
.py
"""GetXAPI X/Twitter retriever for GPT Researcher.""" import json import os import urllib.parse import urllib.request class GetXAPISearch: """ GetXAPI X/Twitter search retriever. Searches tweets via the GetXAPI REST API and returns results in the standard {title, href, body} format used by all GPT R...
92
3,217
gpt-researcher
gpt_researcher/retrievers/serper/serper.py
.py
# Google Serper Retriever # libraries import os import requests import json class SerperSearch(): """ Google Serper Retriever with support for country, language, and date filtering """ def __init__(self, query, query_domains=None, country=None, language=None, time_range=None, exclude_sites=None): ...
140
5,154
gpt-researcher
gpt_researcher/retrievers/bing/bing.py
.py
# Bing Search Retriever # libraries import os import requests import json import logging class BingSearch(): """ Bing Search Retriever """ def __init__(self, query, query_domains=None): """ Initializes the BingSearch object Args: query: """ self.qu...
96
2,690
gpt-researcher
gpt_researcher/retrievers/arxiv/arxiv.py
.py
import arxiv class ArxivSearch: """ Arxiv API Retriever """ def __init__(self, query, sort='Relevance', query_domains=None): self.arxiv = arxiv self.query = query assert sort in ['Relevance', 'SubmittedDate'], "Invalid sort criterion" self.sort = arxiv.SortCriterion.Sub...
40
1,019
gpt-researcher
gpt_researcher/retrievers/searx/searx.py
.py
import os import json import requests from typing import List, Dict from urllib.parse import urljoin class SearxSearch(): """ SearxNG API Retriever """ def __init__(self, query: str, query_domains=None): """ Initializes the SearxSearch object Args: query: Search que...
91
2,825
gpt-researcher
gpt_researcher/retrievers/brave/__init__.py
.py
from .brave import BraveSearch __all__ = ["BraveSearch"]
4
58
gpt-researcher
gpt_researcher/retrievers/brave/brave.py
.py
# Brave Search Retriever # libraries import logging import os import requests class BraveSearch: """ Brave Search API Retriever """ def __init__(self, query, query_domains=None): """ Initializes the BraveSearch object Args: query: """ self.query =...
87
2,410
gpt-researcher
gpt_researcher/retrievers/serpapi/serpapi.py
.py
# SerpApi Retriever # libraries import os import requests import urllib.parse class SerpApiSearch(): """ SerpApi Retriever """ def __init__(self, query, query_domains=None): """ Initializes the SerpApiSearch object Args: query: """ self.query = quer...
91
3,145
gpt-researcher
gpt_researcher/retrievers/openalex/openalex.py
.py
import os from typing import Dict, List, Optional import requests class OpenAlexSearch: """ OpenAlex API Retriever. OpenAlex (https://openalex.org) is an open catalog of scholarly works. No API key is required for default usage. Optional environment variables: - OPENALEX_EMAIL: adds the cal...
133
4,506
gpt-researcher
gpt_researcher/retrievers/groundroute/groundroute.py
.py
"""GroundRoute search retriever for GPT Researcher. GroundRoute routes each query across multiple web-search engines (Serper, Brave, Exa, Tavily, Firecrawl, Perplexity), picks the cheapest that meets a quality bar, caches repeats, and fails over — exposed as one search API. """ import os import requests class Grou...
77
2,667
gpt-researcher
gpt_researcher/retrievers/custom/custom.py
.py
from typing import Any, Dict, List import requests import os class CustomRetriever: """ Custom API Retriever """ def __init__(self, query: str, query_domains=None): self.endpoint = os.getenv('RETRIEVER_ENDPOINT') if not self.endpoint: raise ValueError("RETRIEVER_ENDPOINT e...
72
2,395
gpt-researcher
gpt_researcher/retrievers/xquik/xquik.py
.py
# Xquik X/Twitter Retriever # # Searches X (Twitter) for real-time perspectives, dev discussions, # product feedback, breaking news, and expert opinions. # $0.00015 per tweet — 33x cheaper than the official X API. import json import os import urllib.parse import urllib.request class XquikSearch: """ Xquik X/...
100
3,394
gpt-researcher
gpt_researcher/retrievers/semantic_scholar/semantic_scholar.py
.py
from typing import Dict, List import requests class SemanticScholarSearch: """ Semantic Scholar API Retriever """ BASE_URL = "https://api.semanticscholar.org/graph/v1/paper/search" VALID_SORT_CRITERIA = ["relevance", "citationCount", "publicationDate"] def __init__(self, query: str, sort: s...
76
2,662
gpt-researcher
gpt_researcher/retrievers/mcp/__init__.py
.py
""" MCP Retriever Module This module contains only the MCP retriever implementation. The core MCP functionality has been moved to gpt_researcher.mcp module. """ import logging logger = logging.getLogger(__name__) try: # Check if langchain-mcp-adapters is available from langchain_mcp_adapters.client import Mu...
32
1,016
gpt-researcher
gpt_researcher/retrievers/mcp/retriever.py
.py
""" MCP-Based Research Retriever A retriever that uses Model Context Protocol (MCP) tools for intelligent research. This retriever implements a two-stage approach: 1. Tool Selection: LLM selects 2-3 most relevant tools from all available MCP tools 2. Research Execution: LLM uses the selected tools to conduct intellige...
324
14,578
gpt-researcher
gpt_researcher/retrievers/google/google.py
.py
# Tavily API Retriever # libraries import os import requests import json from urllib.parse import urlencode class GoogleSearch: """ Google API Retriever """ def __init__(self, query, headers=None, query_domains=None): """ Initializes the GoogleSearch object Args: q...
115
3,966
gpt-researcher
gpt_researcher/retrievers/tavily/tavily_search.py
.py
"""Tavily API search retriever for GPT Researcher. This module provides the TavilySearch class for performing web searches using the Tavily API. """ import json import os import re from typing import Literal, Optional, Sequence import requests # Google-style site:domain operators, which the Tavily API does not supp...
149
5,215
gpt-researcher
gpt_researcher/retrievers/crw/crw.py
.py
"""fastCRW API search retriever for GPT Researcher. This module provides the CRWRetriever class for performing web searches using fastCRW, a Firecrawl-compatible web data engine (single binary; self-host or managed cloud). """ import json import os import requests class CRWRetriever: """ fastCRW API Retrie...
127
4,279
gpt-researcher
gpt_researcher/retrievers/duckduckgo/duckduckgo.py
.py
from itertools import islice from ..utils import check_pkg class Duckduckgo: """ Duckduckgo API Retriever """ def __init__(self, query, query_domains=None): check_pkg('ddgs') from ddgs import DDGS self.ddg = DDGS() self.query = query self.query_domains = query_d...
62
2,037
gpt-researcher
gpt_researcher/retrievers/searchapi/searchapi.py
.py
# SearchApi Retriever # libraries import os import requests import urllib.parse class SearchApiSearch(): """ SearchApi Retriever """ def __init__(self, query, query_domains=None): """ Initializes the SearchApiSearch object Args: query: """ self.quer...
85
2,601
gpt-researcher
gpt_researcher/retrievers/bocha/bocha.py
.py
# BoCha Search Retriever # libraries import os import requests import json import logging class BoChaSearch(): """ BoCha Search Retriever """ def __init__(self, query, query_domains=None): """ Initializes the BoChaSearch object Args: query: """ sel...
71
2,152
gpt-researcher
gpt_researcher/config/config.py
.py
"""Configuration management for GPT Researcher. This module provides the Config class that manages all configuration settings for GPT Researcher including LLM providers, embeddings, retrievers, and various operational parameters. """ import json import os import warnings from typing import Any, Dict, List, Type, Unio...
316
13,373
gpt-researcher
gpt_researcher/config/variables/default.py
.py
from .base import BaseConfig DEFAULT_CONFIG: BaseConfig = { "RETRIEVER": "tavily", "EMBEDDING": "openai:text-embedding-3-small", "SIMILARITY_THRESHOLD": 0.42, "FAST_LLM": "openai:gpt-5.4-mini", "SMART_LLM": "openai:gpt-5.4", # Has support for long responses (2k+ words). "STRATEGIC_LLM": "opena...
59
2,774
gpt-researcher
gpt_researcher/config/variables/base.py
.py
from typing import Union, List, Dict, Any from typing_extensions import TypedDict class BaseConfig(TypedDict): RETRIEVER: str EMBEDDING: str SIMILARITY_THRESHOLD: float FAST_LLM: str SMART_LLM: str STRATEGIC_LLM: str FAST_TOKEN_LIMIT: int SMART_TOKEN_LIMIT: int STRATEGIC_TOKEN_LIMI...
52
1,468
gpt-researcher
gpt_researcher/scraper/utils.py
.py
"""Utility functions for web scraping. This module provides helper functions for extracting content, images, and processing HTML from web pages. """ import hashlib import logging import re from urllib.parse import parse_qs, urljoin, urlparse import bs4 from bs4 import BeautifulSoup def get_relevant_images(soup: Be...
144
5,114
gpt-researcher
gpt_researcher/scraper/__init__.py
.py
from .beautiful_soup.beautiful_soup import BeautifulSoupScraper from .web_base_loader.web_base_loader import WebBaseLoaderScraper from .arxiv.arxiv import ArxivScraper from .pymupdf.pymupdf import PyMuPDFScraper from .browser.browser import BrowserScraper from .browser.nodriver_scraper import NoDriverScraper from .tavi...
22
650
gpt-researcher
gpt_researcher/scraper/scraper.py
.py
"""Web scraper module for GPT Researcher. This module provides the Scraper class that extracts content from URLs using various scraping backends (BeautifulSoup, PyMuPDF, Browser, etc.). """ import asyncio import importlib import logging import subprocess import sys from urllib.parse import urlparse import requests f...
218
8,031
gpt-researcher
gpt_researcher/scraper/beautiful_soup/beautiful_soup.py
.py
import logging import time from bs4 import BeautifulSoup from ..utils import get_relevant_images, extract_title, get_text_from_soup, clean_soup logger = logging.getLogger(__name__) # Response codes worth one retry: rate limiting and transient server errors. RETRYABLE_STATUS_CODES = {429, 500, 502, 503, 504} MAX_CON...
94
3,342
gpt-researcher
gpt_researcher/scraper/web_base_loader/web_base_loader.py
.py
from bs4 import BeautifulSoup from urllib.parse import urljoin import requests from ..utils import get_relevant_images, extract_title class WebBaseLoaderScraper: def __init__(self, link, session=None): self.link = link self.session = session or requests.Session() def scrape(self) -> tuple: ...
44
1,562
gpt-researcher
gpt_researcher/scraper/tavily_extract/tavily_extract.py
.py
from bs4 import BeautifulSoup import os from ..utils import get_relevant_images, extract_title class TavilyExtract: def __init__(self, link, session=None): self.link = link self.session = session from tavily import TavilyClient self.tavily_client = TavilyClient(api_key=self.get_api...
62
2,360
gpt-researcher
gpt_researcher/scraper/arxiv/arxiv.py
.py
"""ArXiv paper scraper using the maintained `arxiv` Client API. Avoids langchain_community.ArxivRetriever, which still calls the removed `arxiv.Search.results()` method (broken for arxiv>=2.2). """ from __future__ import annotations import re from typing import Any _ID_RE = re.compile( r"(?:arxiv\.org/(?:abs|p...
61
1,790
gpt-researcher
gpt_researcher/scraper/pymupdf/pymupdf.py
.py
import os import requests import tempfile from urllib.parse import urlparse from langchain_community.document_loaders import PyMuPDFLoader class PyMuPDFScraper: def __init__(self, link, session=None): """ Initialize the scraper with a link and an optional session. Args: link (s...
87
3,410
gpt-researcher
gpt_researcher/scraper/firecrawl/firecrawl.py
.py
from bs4 import BeautifulSoup import os from ..utils import get_relevant_images class FireCrawl: def __init__(self, link, session=None): self.link = link self.session = session from firecrawl import FirecrawlApp self.firecrawl = FirecrawlApp(api_key=self.get_api_key(), api_url=self...
83
3,397
gpt-researcher
gpt_researcher/scraper/browser/nodriver_scraper.py
.py
from contextlib import asynccontextmanager import math from pathlib import Path import random import traceback from urllib.parse import urlparse from bs4 import BeautifulSoup from typing import Dict, Literal, cast, Tuple, List import requests import asyncio import logging from ..utils import get_relevant_images, extra...
261
9,642
gpt-researcher
gpt_researcher/scraper/browser/browser.py
.py
from __future__ import annotations import traceback import pickle from pathlib import Path from sys import platform import time import random import string import os from bs4 import BeautifulSoup from typing import Iterable, cast from .processing.scrape_skills import (scrape_pdf_with_pymupdf, ...
261
10,275
gpt-researcher
gpt_researcher/scraper/browser/processing/scrape_skills.py
.py
from langchain_community.document_loaders import PyMuPDFLoader from langchain_community.retrievers import ArxivRetriever def scrape_pdf_with_pymupdf(url) -> str: """Scrape a pdf with pymupdf Args: url (str): The url of the pdf to scrape Returns: str: The text scraped from the pdf """...
31
830
gpt-researcher
gpt_researcher/scraper/browser/processing/html.py
.py
"""HTML processing functions""" from __future__ import annotations from bs4 import BeautifulSoup from requests.compat import urljoin def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> list[tuple[str, str]]: """Extract hyperlinks from a BeautifulSoup object Args: soup (BeautifulSoup): The ...
34
929
gpt-researcher
gpt_researcher/vector_store/__init__.py
.py
from .vector_store import VectorStoreWrapper __all__ = ['VectorStoreWrapper']
3
78
gpt-researcher
gpt_researcher/vector_store/vector_store.py
.py
""" Wrapper for langchain vector store """ from typing import List, Dict from langchain_core.documents import Document from langchain_community.vectorstores import VectorStore from langchain_text_splitters import RecursiveCharacterTextSplitter class VectorStoreWrapper: """ A Wrapper for LangchainVectorStore t...
44
1,719
gpt-researcher
gpt_researcher/mcp/__init__.py
.py
""" MCP (Model Context Protocol) Integration for GPT Researcher This module provides comprehensive MCP integration including: - Client management for MCP servers - Tool selection and execution - Research execution with MCP tools - Streaming support for real-time updates """ import logging logger = logging.getLogger(...
43
1,220
gpt-researcher
gpt_researcher/mcp/research.py
.py
""" MCP Research Execution Skill Handles research execution using selected MCP tools as a skill component. """ import asyncio import logging from typing import List, Dict, Any logger = logging.getLogger(__name__) class MCPResearchSkill: """ Handles research execution using selected MCP tools. Respo...
271
12,853
gpt-researcher
gpt_researcher/mcp/client.py
.py
""" MCP Client Management Module Handles MCP client creation, configuration conversion, and connection management. """ import asyncio import logging from typing import List, Dict, Any, Optional try: from langchain_mcp_adapters.client import MultiServerMCPClient HAS_MCP_ADAPTERS = True except ImportError: ...
180
6,949
gpt-researcher
gpt_researcher/mcp/streaming.py
.py
""" MCP Streaming Utilities Module Handles websocket streaming and logging for MCP operations. """ import asyncio import logging from typing import Any, Optional logger = logging.getLogger(__name__) class MCPStreamer: """ Handles streaming output for MCP operations. Responsible for: - Streaming...
102
3,816
gpt-researcher
gpt_researcher/mcp/tool_selector.py
.py
""" MCP Tool Selection Module Handles intelligent tool selection using LLM analysis. """ import asyncio import json import logging from typing import List, Dict, Any, Optional logger = logging.getLogger(__name__) class MCPToolSelector: """ Handles intelligent selection of MCP tools using LLM analysis. ...
204
8,012
gpt-researcher
gpt_researcher/utils/costs.py
.py
"""Cost estimation utilities for LLM API usage.""" from __future__ import annotations import logging from collections.abc import Mapping from typing import Any import tiktoken # Per OpenAI Pricing Page: https://openai.com/api/pricing/ ENCODING_MODEL = "o200k_base" INPUT_COST_PER_TOKEN = 0.000005 OUTPUT_COST_PER_TOK...
265
8,919
gpt-researcher
gpt_researcher/utils/logger.py
.py
import logging import sys from copy import copy from typing import Literal import click TRACE_LOG_LEVEL = 5 def get_formatted_logger(): """Return a formatted logger.""" logger = logging.getLogger("scraper") # Set the logging level logger.setLevel(logging.INFO) # Check if the logger already has ...
97
3,287
gpt-researcher
gpt_researcher/utils/rate_limiter.py
.py
""" Global rate limiter for scraper requests. Ensures that SCRAPER_RATE_LIMIT_DELAY is enforced globally across ALL WorkerPools, not just per-pool. This prevents multiple concurrent researchers from overwhelming rate-limited APIs like Firecrawl. """ import asyncio import time from typing import ClassVar class Global...
93
2,867
gpt-researcher
gpt_researcher/utils/enum.py
.py
"""Enumeration types for GPT Researcher configuration.""" from enum import Enum class ReportType(Enum): """Enumeration of available report types for research output. Defines the different types of reports that can be generated by the GPT Researcher agent. Attributes: ResearchReport: Standar...
102
4,080
gpt-researcher
gpt_researcher/utils/llm.py
.py
"""LLM utilities for GPT Researcher. This module provides utility functions for interacting with various LLM providers through a unified interface. """ from __future__ import annotations import logging import os from typing import Any import asyncio from langchain_core.output_parsers import PydanticOutputParser from...
218
7,868
gpt-researcher
gpt_researcher/utils/logging_config.py
.py
import logging import json import os from datetime import datetime from pathlib import Path class JSONResearchHandler: def __init__(self, json_file): self.json_file = json_file self.research_data = { "timestamp": datetime.now().isoformat(), "events": [], "content...
83
2,626
gpt-researcher
gpt_researcher/utils/tools.py
.py
""" Tool-enabled LLM utilities for GPT Researcher This module provides provider-agnostic tool calling functionality using LangChain's unified interface. It allows any LLM provider that supports function calling to use tools seamlessly. """ import asyncio import logging from typing import Any, Dict, List, Tuple, Calla...
350
14,243
gpt-researcher
gpt_researcher/utils/validators.py
.py
"""Pydantic validation models for GPT Researcher.""" from typing import List from pydantic import BaseModel, Field class Subtopic(BaseModel): """Model representing a single research subtopic. Attributes: task: The name or description of the subtopic task. """ task: str = Field(description="...
27
646
gpt-researcher
gpt_researcher/utils/workers.py
.py
import asyncio import time from concurrent.futures import ThreadPoolExecutor from contextlib import asynccontextmanager from .rate_limiter import get_global_rate_limiter class WorkerPool: def __init__(self, max_workers: int, rate_limit_delay: float = 0.0): """ Initialize WorkerPool with concurrenc...
51
2,166
gpt-researcher
gpt_researcher/skills/researcher.py
.py
"""Research conductor skill for GPT Researcher. This module provides the ResearchConductor class that manages and coordinates the research process including query planning, web searching, and context gathering. """ import asyncio import logging import os import random from ..actions.agent_creator import choose_agent...
1,083
47,916
gpt-researcher
gpt_researcher/skills/curator.py
.py
"""Source curator skill for GPT Researcher. This module provides the SourceCurator class that evaluates and ranks research sources based on relevance, credibility, and reliability. """ import json from typing import Dict, List, Optional from ..actions import stream_output from ..config.config import Config from ..ut...
97
3,306
gpt-researcher
gpt_researcher/skills/writer.py
.py
"""Report generator skill for GPT Researcher. This module provides the ReportGenerator class that handles report writing, including introductions, conclusions, and subtopic management. """ import json from typing import Dict, Optional from ..actions import ( generate_draft_section_titles, generate_report, ...
266
9,864
gpt-researcher
gpt_researcher/skills/__init__.py
.py
from .context_manager import ContextManager from .researcher import ResearchConductor from .writer import ReportGenerator from .browser import BrowserManager from .curator import SourceCurator from .image_generator import ImageGenerator __all__ = [ 'ResearchConductor', 'ReportGenerator', 'ContextManager', ...
16
387
gpt-researcher
gpt_researcher/skills/image_generator.py
.py
"""Image generator skill for GPT Researcher. This module provides the ImageGenerator class that handles generating contextually relevant images for research reports using AI image generation. """ import asyncio import json import logging import re from typing import Any, Dict, List, Optional, Tuple from ..actions.ut...
772
29,930
gpt-researcher
gpt_researcher/skills/deep_research.py
.py
from typing import List, Dict, Any, Optional, Set import asyncio import logging import re import time from datetime import datetime, timedelta import json_repair from gpt_researcher.llm_provider.generic.base import ReasoningEfforts from ..utils.llm import create_chat_completion from ..utils.enum import ReportType, Re...
647
25,876
gpt-researcher
gpt_researcher/skills/context_manager.py
.py
"""Context manager skill for GPT Researcher. This module provides the ContextManager class that handles context retrieval, compression, and similarity matching for research queries. """ import asyncio from typing import Dict, List, Optional, Set from ..actions.utils import stream_output from ..context.compression im...
156
5,752
gpt-researcher
gpt_researcher/skills/browser.py
.py
"""Browser manager skill for GPT Researcher. This module provides the BrowserManager class that handles web scraping and content extraction from URLs. """ from gpt_researcher.utils.workers import WorkerPool from ..actions.utils import stream_output from ..actions.web_scraping import scrape_urls from ..scraper.utils ...
116
3,796
gpt-researcher
gpt_researcher/memory/embeddings.py
.py
"""Embedding provider management for GPT Researcher. This module provides the Memory class that handles embedding generation across multiple providers (OpenAI, Cohere, Google, Ollama, etc.). Supported providers: - openai: OpenAI embeddings - azure_openai: Azure OpenAI embeddings - cohere: Cohere embedding...
236
8,767
gpt-researcher
backend/utils.py
.py
import aiofiles import urllib import mistune import os async def write_to_file(filename: str, text: str) -> None: """Asynchronously write text to a file in UTF-8 encoding. Args: filename (str): The filename to write to. text (str): The text to write. """ # Ensure text is a string i...
148
4,957
gpt-researcher
backend/run_server.py
.py
#!/usr/bin/env python3 """ GPT-Researcher Backend Server Startup Script Run this to start the research API server. """ import uvicorn import os import sys # Add the backend directory to Python path backend_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, backend_dir) if __name__ == "__main__": ...
31
549
gpt-researcher
backend/server/websocket_manager.py
.py
import os import asyncio import datetime import json import logging import os import traceback from typing import Dict, List from fastapi import WebSocket from backend.report_type import BasicReport, DetailedReport from gpt_researcher.utils.enum import ReportType, Tone from gpt_researcher.actions import stream_outpu...
184
7,481
gpt-researcher
backend/server/report_store.py
.py
import asyncio import json from pathlib import Path from typing import Any, Dict, List class ReportStore: def __init__(self, path: Path): self._path = path self._lock = asyncio.Lock() async def _ensure_parent_dir(self) -> None: self._path.parent.mkdir(parents=True, exist_ok=True) ...
58
2,115
gpt-researcher
backend/server/app.py
.py
import json import os from typing import Dict, List, Any import time import logging import sys import warnings from pathlib import Path # Suppress Pydantic V2 migration warnings warnings.filterwarnings("ignore", message="Valid config keys have changed in V2") warnings.filterwarnings("ignore", category=UserWarning, mod...
468
16,647
gpt-researcher
backend/server/server_utils.py
.py
import asyncio import json import os import re import time import shutil import traceback from typing import Awaitable, Dict, List, Any from fastapi.responses import JSONResponse, FileResponse from gpt_researcher.document.document import DocumentLoader from gpt_researcher import GPTResearcher from utils import write_md...
413
15,582
gpt-researcher
backend/server/multi_agent_runner.py
.py
import os import sys from typing import Any, Awaitable, Callable RunResearchTask = Callable[..., Awaitable[Any]] def _ensure_repo_root_on_path() -> None: """Ensure top-level repo root is importable for multi-agent modules.""" repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) ...
34
1,065
gpt-researcher
backend/server/logging_config.py
.py
import logging import json import os from datetime import datetime from pathlib import Path class JSONResearchHandler: def __init__(self, json_file): self.json_file = json_file self.research_data = { "timestamp": datetime.now().isoformat(), "events": [], "content...
83
2,680
gpt-researcher
backend/server/agent_discovery.py
.py
from typing import Dict, List, Optional def _to_websocket_origin(origin: str) -> str: if origin.startswith("https://"): return "wss://" + origin[len("https://"):] if origin.startswith("http://"): return "ws://" + origin[len("http://"):] return origin def build_agent_discovery_document( ...
69
2,053
gpt-researcher
backend/report_type/__init__.py
.py
from .basic_report.basic_report import BasicReport from .detailed_report.detailed_report import DetailedReport __all__ = [ "BasicReport", "DetailedReport" ]
7
165
gpt-researcher
backend/report_type/deep_research/main.py
.py
from gpt_researcher import GPTResearcher from backend.utils import write_md_to_pdf import asyncio async def main(task: str): # Progress callback def on_progress(progress): print(f"Depth: {progress.current_depth}/{progress.total_depth}") print(f"Breadth: {progress.current_breadth}/{progress.tot...
33
1,221
gpt-researcher
backend/report_type/deep_research/example.py
.py
from typing import List, Dict, Any, Optional, Set from fastapi import WebSocket import asyncio import logging from gpt_researcher import GPTResearcher from gpt_researcher.llm_provider.generic.base import ReasoningEfforts from gpt_researcher.skills.deep_research import ( parse_follow_up_questions_response, parse...
328
12,514
gpt-researcher
backend/report_type/basic_report/basic_report.py
.py
import hashlib import time from fastapi import WebSocket from typing import Any from gpt_researcher import GPTResearcher class BasicReport: def __init__( self, query: str, query_domains: list, report_type: str, report_source: str, source_urls, document_urls...
76
2,499
gpt-researcher
backend/report_type/detailed_report/detailed_report.py
.py
import asyncio import hashlib import time from typing import List, Dict, Set, Optional, Any from fastapi import WebSocket from gpt_researcher import GPTResearcher class DetailedReport: def __init__( self, query: str, report_type: str, report_source: str, source_urls: List[...
206
8,615
gpt-researcher
backend/memory/draft.py
.py
from typing import TypedDict, List, Annotated import operator class DraftState(TypedDict): task: dict topic: str draft: dict review: str revision_notes: str
10
178
gpt-researcher
backend/memory/research.py
.py
from typing import TypedDict, List, Annotated import operator class ResearchState(TypedDict): task: dict initial_research: str sections: List[str] research_data: List[dict] # Report layout title: str headers: dict date: str table_of_contents: str introduction: str conclusio...
21
368
gpt-researcher
backend/chat/chat.py
.py
import logging import os import uuid import json from fastapi import WebSocket from typing import List, Dict, Any from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_community.vectorstores import InMemoryVectorStore from gpt_researcher.memory import Memory from gpt_researcher.config.conf...
259
10,344