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 | tests/test_searchapi_retriever_none.py | .py | """Regression: SearchAPIRetriever must tolerate raw_content=None.
The scraper sets ``raw_content`` to ``None`` for pages that failed to scrape.
Slicing ``None`` raises ``TypeError``, so the retriever must coerce a missing
or None ``raw_content`` to an empty string.
"""
from gpt_researcher.context.retriever import Sea... | 33 | 1,110 |
gpt-researcher | tests/test_google_search_url_encoding.py | .py | """Regression test: GoogleSearch must URL-encode the query.
The Custom Search request URL was built by f-string interpolating the raw
query: ``...&q={search_query}&start=1``. Any reserved character in the
query corrupted the request:
* ``&`` (e.g. "AT&T") injected a spurious query parameter,
* ``#`` truncated ever... | 64 | 2,207 |
gpt-researcher | tests/test_logging.py | .py | import pytest
from unittest.mock import AsyncMock
from fastapi import WebSocket
from backend.server.server_utils import CustomLogsHandler
import os
import json
@pytest.mark.asyncio
async def test_custom_logs_handler():
# Mock websocket
mock_websocket = AsyncMock()
mock_websocket.send_json = AsyncMock()
... | 61 | 1,839 |
gpt-researcher | tests/test_arxiv_scraper.py | .py | """Regression: ArxivScraper must use arxiv.Client, not Search.results()."""
from types import SimpleNamespace
from datetime import datetime, timezone
from unittest.mock import MagicMock, patch
import pytest
from gpt_researcher.scraper.arxiv.arxiv import ArxivScraper, _paper_id_from_link
def test_paper_id_from_abs_... | 45 | 1,686 |
gpt-researcher | tests/test_pymupdf_tempfile_cleanup.py | .py | """Regression test: PyMuPDFScraper must not leak its downloaded temp file.
When scraping a remote PDF, the scraper downloads it to a
``NamedTemporaryFile(delete=False, suffix=".pdf")`` and then loads it with
``PyMuPDFLoader``. The old code called ``os.remove(temp_filename)`` only on the
success path, so a parse failur... | 51 | 1,680 |
gpt-researcher | tests/test_researcher_logging.py | .py | import pytest
import asyncio
from pathlib import Path
import sys
import logging
# Add the project root to Python path
project_root = Path(__file__).parent.parent
sys.path.append(str(project_root))
# Configure basic logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@pytest.mark.asyn... | 71 | 2,491 |
gpt-researcher | tests/test_add_references_order.py | .py | """Regression tests for add_references deterministic ordering.
``visited_urls`` is a set, so iterating it directly makes the report's
References section order vary run-to-run. add_references must emit the URLs
in a stable (sorted) order.
"""
from gpt_researcher.actions.markdown_processing import add_references
def ... | 35 | 1,257 |
gpt-researcher | tests/test_pubmed_central_returns_list.py | .py | """Regression test: PubMedCentralSearch.search must return [] (never None).
Callers (actions.query_processing.get_search_results -> List[Dict]) and
skills.researcher (`len(search_results)`) crash on None.
"""
import sys
import types
from unittest.mock import patch
if "requests" not in sys.modules:
sys.modules["r... | 32 | 968 |
gpt-researcher | tests/test_multi_agents_draft_revisions.py | .py | import importlib.util
from pathlib import Path
import pytest
PATH = Path(__file__).resolve().parents[1] / "multi_agents" / "agents" / "draft_review.py"
spec = importlib.util.spec_from_file_location("draft_review", PATH)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
def test_accept_when_no... | 36 | 980 |
gpt-researcher | tests/test_quick_search.py | .py | import unittest
from unittest.mock import MagicMock, patch, AsyncMock
import asyncio
from gpt_researcher.agent import GPTResearcher
import os
class TestQuickSearch(unittest.TestCase):
@patch('gpt_researcher.agent.get_search_results', new_callable=AsyncMock)
@patch('gpt_researcher.agent.create_chat_completion'... | 111 | 4,717 |
gpt-researcher | tests/test_extract_json_with_regex.py | .py | """Regression tests for extract_json_with_regex (agent JSON recovery).
The helper used a non-greedy ``{.*?}`` pattern, which stopped at the FIRST
closing brace. That truncated any JSON object that had more than one key or
a ``}`` inside a string value (e.g. an agent_role_prompt mentioning
"{markets}"), producing an in... | 38 | 1,341 |
gpt-researcher | tests/test-your-retriever.py | .py | import asyncio
from dotenv import load_dotenv
from gpt_researcher.config.config import Config
from gpt_researcher.actions.retriever import get_retrievers
from gpt_researcher.skills.researcher import ResearchConductor
import pprint
# Load environment variables from .env file
load_dotenv()
async def test_scrape_data_by_... | 49 | 1,740 |
gpt-researcher | tests/test_browser_pdf_detection.py | .py | """Regression tests for PDF URL detection in the BrowserScraper.
The scrape path used ``self.url.endswith(".pdf")``, which:
* missed query strings / fragments (signed CDN/S3 links such as
``https://host/doc.pdf?sig=...`` are extremely common), and
* was case-sensitive, so ``.PDF`` was not recognized.
These te... | 42 | 1,350 |
gpt-researcher | tests/test_context_compressor_source_url.py | .py | """Regression: ContextCompressor fast path must map url -> metadata.source."""
import os
from unittest.mock import MagicMock
import pytest
from langchain_core.documents import Document
from gpt_researcher.context.compression import ContextCompressor
from gpt_researcher.prompts import PromptFamily
@pytest.mark.asyn... | 55 | 1,705 |
gpt-researcher | tests/test_serpapi_retriever_malformed.py | .py | """Regression tests for SerpApiSearch result normalization.
Without the fix, a response missing ``organic_results`` raises a KeyError, and
a single result missing ``title``/``link``/``snippet`` raises a KeyError that
aborts the whole ``search()`` call.
"""
import importlib.util
import os
import pathlib
from unittest.m... | 56 | 1,986 |
gpt-researcher | tests/documents-report-source.py | .py | import os
import asyncio
import pytest
# Ensure this path is correct
from gpt_researcher import GPTResearcher
from dotenv import load_dotenv
load_dotenv()
# Define the report types to test
report_types = [
"research_report",
"custom_report",
"subtopic_report",
"summary_report",
"detailed_report",
... | 55 | 1,638 |
gpt-researcher | tests/test_semantic_scholar_sort.py | .py | """Regression test for Semantic Scholar sort-criterion casing.
``VALID_SORT_CRITERIA`` holds the API's exact camelCase values
(``citationCount``, ``publicationDate``), and ``__init__`` asserts the
incoming value is one of them. It then stored ``sort.lower()``, corrupting
``citationCount`` -> ``citationcount`` before i... | 34 | 1,178 |
gpt-researcher | tests/test_scraper_get_scraper.py | .py | """Regression tests for PDF detection in Scraper.get_scraper.
PDF links were detected with ``link.endswith(".pdf")``, which:
* missed query strings / fragments (signed CDN/S3 links such as
``https://host/doc.pdf?sig=...`` are extremely common), and
* was case-sensitive, so ``.PDF`` was not recognized.
In both... | 59 | 2,101 |
gpt-researcher | tests/test_exa_null_attrs.py | .py | """ExaSearch must skip hits with missing url/id rather than raising."""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from gpt_researcher.retrievers.exa.exa import ExaSearch
def _searcher():
# bypass __init__ pkg/API setup
s = ExaSearch.__ne... | 54 | 1,616 |
gpt-researcher | tests/test_none_accept_sentinels.py | .py | """Strict None/no acceptance sentinels for multi_agents loops.
Regression for #1881 (reviewer/fact-checker false-accept on substring "None")
and shared helpers for the human plan-approval gate (#1882).
"""
import importlib.util
from pathlib import Path
import pytest
SENTINEL_PATH = (
Path(__file__).resolve().pa... | 63 | 2,201 |
gpt-researcher | tests/test_multi_agents_plan_revisions.py | .py | import importlib.util
from pathlib import Path
import pytest
PLAN_REVIEW_PATH = (
Path(__file__).resolve().parents[1] /
"multi_agents" / "agents" / "plan_review.py"
)
spec = importlib.util.spec_from_file_location(
"plan_review",
PLAN_REVIEW_PATH,
)
plan_review = importlib.util.module_from_spec(spec)
... | 43 | 1,217 |
gpt-researcher | tests/gptr-logs-handler.py | .py | import logging
from typing import List, Dict, Any
import asyncio
from gpt_researcher import GPTResearcher
from backend.server.server_utils import CustomLogsHandler # Update import
async def run() -> None:
"""Run the research process and generate a report."""
query = "What happened in the latest burning man fl... | 35 | 1,073 |
gpt-researcher | tests/test_serper_retriever.py | .py | """Serper organic items must not KeyError on partial payloads."""
from unittest.mock import MagicMock, patch
from gpt_researcher.retrievers.serper.serper import SerperSearch
def test_skip_items_missing_link(monkeypatch):
monkeypatch.setenv("SERPER_API_KEY", "k")
resp = MagicMock()
resp.text = '{"organic... | 25 | 869 |
gpt-researcher | tests/test-openai-llm.py | .py | import asyncio
from gpt_researcher.utils.llm import get_llm
from gpt_researcher import GPTResearcher
from dotenv import load_dotenv
load_dotenv()
async def main():
# Example usage of get_llm function
llm_provider = "openai"
model = "gpt-3.5-turbo"
temperature = 0.7
max_tokens = 1000
llm = ge... | 31 | 913 |
gpt-researcher | tests/test_costs.py | .py | import unittest
from gpt_researcher.utils.costs import (
EMBEDDING_COST,
calculate_llm_cost,
estimate_embedding_cost,
estimate_llm_cost,
)
class TestCosts(unittest.TestCase):
def test_calculate_llm_cost_uses_anthropic_api_usage(self):
cost = calculate_llm_cost(
llm_provider="a... | 104 | 3,202 |
gpt-researcher | tests/test-your-llm.py | .py | from gpt_researcher.config.config import Config
from gpt_researcher.utils.llm import create_chat_completion
import asyncio
from dotenv import load_dotenv
load_dotenv()
async def main():
cfg = Config()
try:
report = await create_chat_completion(
model=cfg.smart_llm_model,
messag... | 24 | 678 |
gpt-researcher | tests/test_construct_subtopics_error_log.py | .py | """Tests for construct_subtopics error handling.
On failure, construct_subtopics returns the original `subtopics` fallback and
logs the error. The log call previously used a non-f-string
("...\\n {e}"), so it recorded the literal text "{e}" instead of the actual
exception, and also printed to stdout. This test pins th... | 51 | 1,466 |
gpt-researcher | tests/report-types.py | .py | import os
import asyncio
import pytest
from unittest.mock import AsyncMock
from gpt_researcher.agent import GPTResearcher
from backend.server.server_utils import CustomLogsHandler
from typing import List, Dict, Any
# Define the report types to test
report_types = ["research_report", "subtopic_report"]
# Define a comm... | 48 | 1,380 |
gpt-researcher | tests/test_duckduckgo_normalize.py | .py | import importlib.util
import sys
import types
import unittest
from pathlib import Path
from unittest.mock import MagicMock
ROOT = Path(__file__).resolve().parents[1]
MODULE_PATH = ROOT / "gpt_researcher" / "retrievers" / "duckduckgo" / "duckduckgo.py"
def _load_duckduckgo_module():
# Load the module file direct... | 74 | 2,733 |
gpt-researcher | tests/test_llm_max_tokens.py | .py | from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from gpt_researcher.utils.llm import create_chat_completion
@pytest.mark.asyncio
async def test_create_chat_completion_accepts_max_tokens_above_old_32k_cap():
provider = MagicMock()
provider.get_chat_response = AsyncMock(side_effect=["ok-64... | 44 | 1,516 |
gpt-researcher | tests/test_groundroute_malformed_results.py | .py | import importlib.util
import os
import sys
import types
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
ROOT = Path(__file__).resolve().parents[1]
MODULE_PATH = ROOT / "gpt_researcher" / "retrievers" / "groundroute" / "groundroute.py"
def _load():
requests_mod = types.ModuleT... | 64 | 2,055 |
gpt-researcher | tests/test_crw_retriever_malformed.py | .py | """Regression tests for CRWRetriever (fastCRW) result normalization.
Without the fix, a source missing the ``url`` key raises a KeyError that is
swallowed by the broad ``except`` in ``search()`` — discarding every other
(valid) source in the same response and returning an empty list.
"""
import importlib.util
import o... | 51 | 1,606 |
gpt-researcher | tests/test_get_retrievers_whitespace.py | .py | """Regression tests for whitespace handling in get_retrievers.
Comma-separated retriever lists supplied via request headers
(e.g. ``"tavily, exa"``) previously kept the surrounding whitespace,
so every name after the first failed the exact ``match`` in
``get_retriever`` and silently fell back to the default retriever.... | 62 | 2,339 |
gpt-researcher | tests/test_online_document_extension.py | .py | """Regression test for OnlineDocumentLoader._get_extension case handling."""
from gpt_researcher.document.online_document import OnlineDocumentLoader
def test_get_extension_lowercases_uppercase_suffix():
# Loader dict keys are lower-case ("pdf", "docx"); an upper-case URL
# extension must be normalised so th... | 25 | 1,022 |
gpt-researcher | tests/test_logging_output.py | .py | import pytest
import asyncio
from pathlib import Path
import json
import logging
from fastapi import WebSocket
from datetime import datetime
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class TestWebSocket(WebSocket):
def __init__(self):
self.events = []
self.scope ... | 63 | 2,003 |
gpt-researcher | tests/test_crw_retriever.py | .py | import unittest
from unittest.mock import MagicMock, patch
from gpt_researcher.retrievers.crw.crw import CRWRetriever
def make_response(json_data, status_code=200):
"""Build a fake requests.Response-like object."""
response = MagicMock()
response.status_code = status_code
response.json.return_value =... | 109 | 3,805 |
gpt-researcher | tests/test_new_agents.py | .py | import sys
import os
import asyncio
from dotenv import load_dotenv
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from multi_agents.agents.fact_checker import FactCheckerAgent
from multi_agents.agents.visualizer import VisualizerAgent
import multi_agents.agents.fact_checker
import m... | 59 | 2,194 |
gpt-researcher | tests/test-loaders.py | .py | from langchain_community.document_loaders import PyMuPDFLoader, UnstructuredCSVLoader
# # Test PyMuPDFLoader
pdf_loader = PyMuPDFLoader("my-docs/Elisha - Coding Career.pdf")
try:
pdf_data = pdf_loader.load()
print("PDF Data:", pdf_data)
except Exception as e:
print("Failed to load PDF:", e)
# Test Unstruc... | 17 | 562 |
gpt-researcher | tests/test_tavily_malformed.py | .py | """TavilySearch must skip malformed sources instead of raising KeyError."""
from __future__ import annotations
from unittest.mock import patch
from gpt_researcher.retrievers.tavily.tavily_search import TavilySearch
def test_tavily_skips_sources_missing_url_or_non_dict():
sources = [
{"url": "https://a.... | 40 | 1,177 |
gpt-researcher | tests/test_scraper_extract_title.py | .py | """Tests for scraper title extraction.
`extract_title` is annotated `-> str` and its result flows into image alt-text
and document metadata across every scraper backend. A `<title></title>` with no
text node made `soup.title.string` return `None`, breaking the string contract
and propagating `None` downstream.
"""
im... | 42 | 1,288 |
gpt-researcher | tests/test_parse_dimension.py | .py | """Tests for image dimension parsing.
`parse_dimension` is called for every `<img>` width/height attribute during
scraping. Non-numeric values like '100%', 'auto', and '50em' are common and
valid HTML, but used to print an error line to stdout for each one, polluting
application output. It should parse numeric/px valu... | 49 | 1,582 |
gpt-researcher | tests/test_xquik_null_fields.py | .py | """Regression tests for XquikSearch null-field handling.
The Xquik API can return an explicit JSON ``null`` for ``tweets`` (no
results) or for a tweet's ``author`` / ``text`` fields. ``dict.get(key,
default)`` only substitutes the default when the key is *absent*, not when
its value is ``None`` — so ``tweet.get("autho... | 63 | 2,086 |
gpt-researcher | tests/test_convert_env_value_optional.py | .py | """Regression tests for Optional[str] env coercion (issue #1899)."""
from typing import Optional, Union
import pytest
from gpt_researcher.config.config import Config
@pytest.mark.parametrize(
"raw",
["none", "null", "", "NONE", "Null"],
)
def test_optional_str_coerces_none_sentinels(raw):
assert Config.... | 26 | 883 |
gpt-researcher | tests/test_bing_retriever_malformed.py | .py | """Regression tests for BingSearch result normalization.
Without the fix, a single result missing an expected key (``url``/``name``/
``snippet``) raises a KeyError that aborts the whole ``search()`` call, and a
response without a ``webPages`` block raises a KeyError instead of returning [].
"""
import importlib.util
i... | 54 | 1,884 |
gpt-researcher | tests/test_llm_usage_tracking.py | .py | import asyncio
import unittest
from gpt_researcher.llm_provider.generic.base import GenericLLMProvider
class _Chunk:
def __init__(self, content, usage_metadata=None, response_metadata=None):
self.content = content
self.usage_metadata = usage_metadata
self.response_metadata = response_meta... | 43 | 1,307 |
gpt-researcher | tests/test_deep_research_parsing.py | .py | from types import SimpleNamespace
import pytest
import gpt_researcher.skills.deep_research as deep_research_module
from gpt_researcher.skills.deep_research import (
DeepResearchSkill,
MAX_CONTEXT_WORDS,
parse_follow_up_questions_response,
parse_research_results_response,
parse_search_queries_respo... | 317 | 11,192 |
gpt-researcher | tests/test_agent_discovery.py | .py | import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
for path in (ROOT, ROOT / "backend"):
path_str = str(path)
if path_str not in sys.path:
sys.path.insert(0, path_str)
from backend.server.agent_discovery import build_agent_discovery_document
def test_build_agent_discover... | 52 | 1,848 |
gpt-researcher | tests/test_mcp.py | .py | #!/usr/bin/env python3
"""
Test script for MCP integration in GPT Researcher
This script tests two MCP integration scenarios:
1. Web Search MCP (Tavily) - News and general web search queries
2. GitHub MCP - Code repository and technical documentation queries
Both tests verify:
- MCP server connection and tool usage
-... | 269 | 9,360 |
gpt-researcher | tests/test-your-embeddings.py | .py | from gpt_researcher.config.config import Config
from gpt_researcher.memory.embeddings import Memory
import asyncio
import os
from dotenv import load_dotenv
load_dotenv()
async def main():
cfg = Config()
print("Current embedding configuration:")
print(f"EMBEDDING env var: {os.getenv('EMBEDDING', 'Not s... | 56 | 2,318 |
gpt-researcher | tests/test_quick_search_summary_context.py | .py | """Regression test: quick_search aggregated summary must include real result data.
All GPT-Researcher search retrievers return records keyed by ``href`` (URL)
and ``body`` (content) — never ``title``/``content``/``url``. The aggregated
summary path in ``quick_search`` built its context with
``result.get('content')`` /... | 60 | 2,360 |
gpt-researcher | tests/test_mcp_client_config.py | .py | #!/usr/bin/env python3
"""
Unit tests for MCPClientManager.convert_configs_to_langchain_format.
Regression coverage for the dead-branch bug where connection_headers were
silently dropped for HTTP/websocket transports because the guard checked
server_config["connection_type"] (never set) instead of the transport.
"""
... | 50 | 1,850 |
gpt-researcher | tests/test_websocket_manager.py | .py | import importlib
import os
import sys
import types
import unittest
from enum import Enum
from pathlib import Path
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
def _load_websocket_manager_module():
for path in (ROOT, ROOT / "backend"):
path_str = str(path)
if path_st... | 115 | 3,756 |
gpt-researcher | tests/test_bocha_error_handling.py | .py | """Regression tests for BoChaSearch robustness.
Unlike every sibling retriever (which returns ``[]`` and uses ``.get()`` on a
bad/empty payload), BoChaSearch indexed ``json_response["data"]["webPages"]
["value"]`` directly and had no error handling. A non-200 response, a body
that doesn't decode as JSON, or a payload ... | 70 | 2,076 |
gpt-researcher | tests/test_sub_query_normalization.py | .py | """Tests for sub-query response normalization.
`generate_sub_queries` returns the raw output of `json_repair.loads`, which can
be a list, a dict, a bare string, or None depending on what the LLM emits.
Downstream callers (researcher.plan_research) treat the result as a `list[str]`
and call `.append(...)` / iterate ove... | 68 | 2,093 |
gpt-researcher | tests/test_custom_retriever_guard.py | .py | """CustomRetriever.search must always return a list, never None."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from gpt_researcher.retrievers.custom.custom import CustomRetriever
def _make(endpoint="https://example.test/search"):
with patch.dict("os.environ", {"RETRIEVER_ENDP... | 59 | 1,926 |
gpt-researcher | tests/test_research_conductor_retrieval.py | .py | import unittest
from types import SimpleNamespace
from gpt_researcher.skills.researcher import ResearchConductor
class FakeSnippetRetriever:
def __init__(self, query, query_domains=None):
self.query = query
self.query_domains = query_domains or []
def search(self, max_results=10):
re... | 83 | 2,511 |
gpt-researcher | tests/test_security_fix.py | .py | """
Security tests for path traversal vulnerability fix.
This module tests the security improvements made to file upload and deletion
operations to prevent path traversal attacks.
"""
import pytest
import tempfile
import os
import shutil
from unittest.mock import Mock, MagicMock
from fastapi import HTTPException
from... | 352 | 13,188 |
gpt-researcher | tests/test_google_malformed.py | .py | """GoogleSearch must tolerate malformed CSE items / response shapes."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from gpt_researcher.retrievers.google.google import GoogleSearch
def _searcher():
g = GoogleSearch.__new__(GoogleSearch)
g.query = "q"
g.headers = {}
... | 54 | 1,613 |
gpt-researcher | tests/test_logs.py | .py | import os
from pathlib import Path
import sys
# Add the project root to Python path
project_root = Path(__file__).parent.parent
sys.path.append(str(project_root))
from backend.server.server_utils import CustomLogsHandler
def test_logs_creation():
# Print current working directory
print(f"Current working dire... | 48 | 1,455 |
gpt-researcher | tests/test_nebius_provider.py | .py | """Unit tests for the Nebius Token Factory provider (LLM + embeddings).
These tests construct the provider objects with a dummy key and assert they
point at the Token Factory endpoint; no network calls are made.
"""
import os
import unittest
from gpt_researcher.llm_provider.generic.base import (
GenericLLMProvide... | 67 | 2,328 |
gpt-researcher | tests/test_searx_malformed_results.py | .py | import importlib.util
import os
import sys
import types
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
ROOT = Path(__file__).resolve().parents[1]
MODULE_PATH = ROOT / "gpt_researcher" / "retrievers" / "searx" / "searx.py"
def _load():
requests_mod = types.ModuleType("request... | 75 | 2,409 |
gpt-researcher | tests/skills/test_deep_research_empty_results.py | .py | """Deep research terminates when a level yields no results (#1579)."""
import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
import pytest
from gpt_researcher.skills.deep_research import DeepResearchSkill
@pytest.mark.asyncio
async def test_stops_when_all_query_processors_retu... | 56 | 1,751 |
gpt-researcher | tests/skills/test_tavily_mcp_dedupe.py | .py | """Skip redundant Tavily MCP when direct Tavily retriever is active (#1875)."""
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from gpt_researcher.skills.researcher import ResearchConductor
class TavilySearch:
pass
class MCPRetriever: # name contains mcpretrie... | 68 | 2,419 |
gpt-researcher | tests/backend/test_write_md_to_pdf_filename.py | .py | """Filename/directory hygiene for report PDF export (#1718)."""
import asyncio
import os
from pathlib import Path
from unittest.mock import patch
import pytest
from backend import utils as backend_utils
@pytest.mark.asyncio
async def test_empty_filename_does_not_write_dot_pdf(tmp_path, monkeypatch):
monkeypatc... | 61 | 2,050 |
gpt-researcher | multi_agents/main.py | .py | from dotenv import load_dotenv
import sys
import os
import uuid
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from multi_agents.agents import ChiefEditorAgent
import asyncio
import json
from gpt_researcher.utils.enum import Tone
# Run with LangSmith if API key is set
if os.environ... | 62 | 1,988 |
gpt-researcher | multi_agents/__init__.py | .py | # multi_agents/__init__.py
from .agents import (
ResearchAgent,
WriterAgent,
PublisherAgent,
ReviserAgent,
ReviewerAgent,
EditorAgent,
ChiefEditorAgent
)
from .memory import (
DraftState,
ResearchState
)
__all__ = [
"ResearchAgent",
"WriterAgent",
"PublisherAgent",
... | 27 | 439 |
gpt-researcher | multi_agents/agent.py | .py | from multi_agents.agents import ChiefEditorAgent
chief_editor = ChiefEditorAgent({
"query": "Is AI in a hype cycle?",
"max_sections": 3,
"max_plan_revisions": 3,
"follow_guidelines": False,
"model": "gpt-4o",
"guidelines": [
"The report MUST be written in APA format",
"Each sub section MUST include... | 18 | 621 |
gpt-researcher | multi_agents/ag2/main.py | .py | import asyncio
from dotenv import load_dotenv
import os
import sys
import uuid
import json
from multi_agents.ag2.agents import ChiefEditorAgent
from gpt_researcher.utils.enum import Tone
load_dotenv()
def open_task() -> dict:
current_dir = os.path.dirname(os.path.abspath(__file__))
task_json_path = os.path... | 61 | 1,552 |
gpt-researcher | multi_agents/ag2/agents/editor.py | .py | from datetime import datetime
from typing import Dict, Optional, List
from multi_agents.agents.utils.views import print_agent_output
from multi_agents.agents.utils.llms import call_model
class EditorAgent:
"""Agent responsible for planning the research outline."""
def __init__(self, websocket=None, stream_o... | 90 | 3,641 |
gpt-researcher | multi_agents/ag2/agents/__init__.py | .py | from .editor import EditorAgent
from .orchestrator import ChiefEditorAgent
from multi_agents.agents.human import HumanAgent
from multi_agents.agents.publisher import PublisherAgent
from multi_agents.agents.researcher import ResearchAgent
from multi_agents.agents.reviewer import ReviewerAgent
from multi_agents.agents.r... | 21 | 577 |
gpt-researcher | multi_agents/ag2/agents/orchestrator.py | .py | import asyncio
import datetime
import os
import time
from typing import Any, Dict, List, Optional
from autogen import ConversableAgent, GroupChat, GroupChatManager, UserProxyAgent
from multi_agents.agents.utils.views import print_agent_output
from multi_agents.agents.utils.utils import sanitize_filename
from .editor ... | 216 | 8,667 |
gpt-researcher | multi_agents/memory/__init__.py | .py | from .draft import DraftState
from .research import ResearchState
__all__ = [
"DraftState",
"ResearchState"
] | 7 | 118 |
gpt-researcher | multi_agents/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
draft_revision_count: int
| 12 | 209 |
gpt-researcher | multi_agents/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]
human_feedback: str
plan_revision_count: int
# Report layout
title: str
headers: dict
date: str
table... | 24 | 504 |
gpt-researcher | multi_agents/agents/researcher.py | .py | from gpt_researcher import GPTResearcher
from colorama import Fore, Style
from .utils.views import print_agent_output
class ResearchAgent:
def __init__(self, websocket=None, stream_output=None, tone=None, headers=None):
self.websocket = websocket
self.stream_output = stream_output
self.hea... | 58 | 3,145 |
gpt-researcher | multi_agents/agents/human.py | .py | import json
class HumanAgent:
def __init__(self, websocket=None, stream_output=None, headers=None):
self.websocket = websocket
self.stream_output = stream_output
self.headers = headers or {}
async def review_plan(self, research_state: dict):
print(f"HumanAgent websocket: {self... | 60 | 2,483 |
gpt-researcher | multi_agents/agents/writer.py | .py | from datetime import datetime
import json5 as json
from .utils.views import print_agent_output
from .utils.llms import call_model
sample_json = """
{
"table_of_contents": A table of contents in markdown syntax (using '-') based on the research headers and subheaders,
"introduction": An indepth introduction to the ... | 147 | 6,032 |
gpt-researcher | multi_agents/agents/editor.py | .py | from datetime import datetime
import asyncio
from typing import Dict, List, Optional
from langgraph.graph import StateGraph, END
from .utils.views import print_agent_output
from .utils.llms import call_model
from ..memory.draft import DraftState
from . import ResearchAgent, ReviewerAgent, ReviserAgent
class EditorA... | 169 | 7,158 |
gpt-researcher | multi_agents/agents/plan_review.py | .py | DEFAULT_MAX_PLAN_REVISIONS = 3
class MaxPlanRevisionsExceededError(RuntimeError):
"""Raised when human feedback requests exceed the configured planning limit."""
def route_human_feedback(review, max_plan_revisions=DEFAULT_MAX_PLAN_REVISIONS):
if review.get("human_feedback") is None:
return "accept"
... | 24 | 739 |
gpt-researcher | multi_agents/agents/fact_checker.py | .py | from .utils.views import print_agent_output
from .utils.llms import call_model
class FactCheckerAgent:
def __init__(self, websocket=None, stream_output=None, headers=None):
self.websocket = websocket
self.stream_output = stream_output
self.headers = headers or {}
async def check_facts(... | 67 | 3,005 |
gpt-researcher | multi_agents/agents/__init__.py | .py | from .researcher import ResearchAgent
from .writer import WriterAgent
from .publisher import PublisherAgent
from .reviser import ReviserAgent
from .reviewer import ReviewerAgent
from .editor import EditorAgent
from .human import HumanAgent
from .fact_checker import FactCheckerAgent
from .visualizer import VisualizerAge... | 26 | 660 |
gpt-researcher | multi_agents/agents/visualizer.py | .py | from .utils.views import print_agent_output
from .utils.llms import call_model
class VisualizerAgent:
def __init__(self, websocket=None, stream_output=None, headers=None):
self.websocket = websocket
self.stream_output = stream_output
self.headers = headers or {}
async def generate_visu... | 55 | 2,530 |
gpt-researcher | multi_agents/agents/reviewer.py | .py | from .utils.views import print_agent_output
from .utils.llms import call_model
TEMPLATE = """You are an expert research article reviewer. \
Your goal is to review research drafts and provide feedback to the reviser only based on specific guidelines. \
"""
class ReviewerAgent:
def __init__(self, websocket=None, s... | 85 | 3,356 |
gpt-researcher | multi_agents/agents/fact_review.py | .py | DEFAULT_MAX_FACT_CHECK_REVISIONS = 3
class MaxFactCheckRevisionsExceededError(RuntimeError):
"""Raised when writer/fact-checker rounds exceed the configured limit."""
def route_fact_check(state, max_fact_check_revisions=DEFAULT_MAX_FACT_CHECK_REVISIONS):
if state.get("fact_check_notes") is None:
ret... | 24 | 748 |
gpt-researcher | multi_agents/agents/reviser.py | .py | from .utils.views import print_agent_output
from .utils.llms import call_model
import json
sample_revision_notes = """
{
"draft": {
draft title: The revised draft that you are submitting for review
},
"revision_notes": Your message to the reviewer about the changes you made to the draft based on their feed... | 75 | 2,541 |
gpt-researcher | multi_agents/agents/draft_review.py | .py | DEFAULT_MAX_DRAFT_REVISIONS = 3
class MaxDraftRevisionsExceededError(RuntimeError):
"""Raised when reviewer/reviser rounds exceed the configured draft limit."""
def route_draft_review(draft, max_draft_revisions=DEFAULT_MAX_DRAFT_REVISIONS):
"""Return accept | revise for the editor review loop.
* ``revi... | 32 | 1,096 |
gpt-researcher | multi_agents/agents/orchestrator.py | .py | import os
import time
import datetime
from langgraph.graph import StateGraph, END
# from langgraph.checkpoint.memory import MemorySaver
from .utils.views import print_agent_output
from ..memory.research import ResearchState
from .utils.utils import sanitize_filename
from .plan_review import (
DEFAULT_MAX_PLAN_REVIS... | 147 | 5,362 |
gpt-researcher | multi_agents/agents/publisher.py | .py | from .utils.file_formats import \
write_md_to_pdf, \
write_md_to_word, \
write_text_to_md
from .utils.views import print_agent_output
class PublisherAgent:
def __init__(self, output_dir: str, websocket=None, stream_output=None, headers=None):
self.websocket = websocket
self.stream_out... | 78 | 2,921 |
gpt-researcher | multi_agents/agents/utils/utils.py | .py | import re
def sanitize_filename(filename: str) -> str:
"""
Sanitize a given filename by replacing characters that are invalid
in Windows file paths with an underscore ('_').
This function ensures that the filename is compatible with all
operating systems by removing or replacing characters that ... | 27 | 865 |
gpt-researcher | multi_agents/agents/utils/llms.py | .py | import json_repair
from langchain_community.adapters.openai import convert_openai_messages
from langchain_core.utils.json import parse_json_markdown
from loguru import logger
from gpt_researcher.config.config import Config
from gpt_researcher.utils.llm import create_chat_completion
async def call_model(
prompt: ... | 37 | 1,008 |
gpt-researcher | multi_agents/agents/utils/file_formats.py | .py | import aiofiles
import urllib
import uuid
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 ... | 105 | 3,091 |
gpt-researcher | multi_agents/agents/utils/views.py | .py | from colorama import Fore, Style
from enum import Enum
class AgentColor(Enum):
RESEARCHER = Fore.LIGHTBLUE_EX
EDITOR = Fore.YELLOW
WRITER = Fore.LIGHTGREEN_EX
PUBLISHER = Fore.MAGENTA
REVIEWER = Fore.CYAN
REVISOR = Fore.LIGHTWHITE_EX
MASTER = Fore.LIGHTYELLOW_EX
FACT_CHECKER = Fore.LIG... | 18 | 504 |
gpt-researcher | multi_agents/agents/utils/none_sentinels.py | .py | """Strict parsers for LLM / human "none" / "no" acceptance sentinels.
Substring checks (``"None" in response``, ``"no" in feedback``) false-accept
review notes like "None of the criteria are met" or human plan feedback like
"not enough cost data". Keep the sentinels exact (optional surrounding
quotes / whitespace) so ... | 43 | 1,718 |
gpt-researcher | gpt_researcher/__init__.py | .py | from .agent import GPTResearcher
__all__ = ['GPTResearcher'] | 3 | 61 |
gpt-researcher | gpt_researcher/prompts.py | .py | import warnings
from datetime import date, datetime, timezone
from langchain_core.documents import Document
from .config import Config
from .utils.enum import ReportSource, ReportType, Tone
from .utils.enum import PromptFamily as PromptFamilyEnum
from typing import Callable, List, Dict, Any
## Prompt Families #####... | 904 | 40,851 |
gpt-researcher | gpt_researcher/agent.py | .py | """GPT Researcher agent module.
This module provides the main GPTResearcher class that orchestrates
autonomous research and report generation using LLMs and web search.
"""
import asyncio
import json
import os
from typing import Any, Optional
from .actions import (
add_references,
choose_agent,
extract_h... | 795 | 31,311 |
gpt-researcher | gpt_researcher/llm_provider/__init__.py | .py | from .generic import GenericLLMProvider
from .image import ImageGeneratorProvider
__all__ = [
"GenericLLMProvider",
"ImageGeneratorProvider",
]
| 8 | 153 |
gpt-researcher | gpt_researcher/llm_provider/image/modelslab_image_generator.py | .py | """ModelsLab image generation provider for GPT Researcher.
This module provides image generation via ModelsLab's API, supporting
Flux, SDXL, Stable Diffusion, and 50k+ community models.
API docs: https://docs.modelslab.com
"""
import asyncio
import hashlib
import logging
import os
from pathlib import Path
from typin... | 243 | 9,030 |
gpt-researcher | gpt_researcher/llm_provider/image/__init__.py | .py | """Image generation provider module for GPT Researcher."""
from .image_generator import ImageGeneratorProvider
from .modelslab_image_generator import ModelsLabImageGeneratorProvider
__all__ = ["ImageGeneratorProvider", "ModelsLabImageGeneratorProvider"]
| 7 | 256 |
gpt-researcher | gpt_researcher/llm_provider/image/image_generator.py | .py | """Image generation provider for GPT Researcher.
This module provides image generation capabilities using Google's Gemini/Imagen
models via the google.genai SDK.
Supported models:
- Gemini image models (free tier): models/gemini-2.5-flash-image
- Imagen models (requires billing): imagen-4.0-generate-001
"""
import a... | 441 | 18,134 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.