LocalGPTResearcher 및 WebGPTResearcher 도구는 특정 주제 또는 쿼리에 대한 철저한 연구를 수행하도록 설계되었습니다. 이 도구는 GPT 모델의 힘을 활용하여 자세한 보고서를 생성하여 다양한 연구 관련 작업에 이상적입니다. LocalGPTResearcher 도구는 로컬 데이터 파일에 액세스하는 반면 WebGPTResearcher 웹에서 정보를 검색합니다.
LocalGPTResearcher PDF, Word Documents, CSV 등과 같은 다양한 로컬 파일 형식으로 작업 할 수 있습니다.WebGPTResearcher 인터넷에서 직접 데이터를 가져 오므로 최신 정보 수집에 적합합니다.시스템에 Python 3이 설치되어 있는지 확인하십시오.
PIP를 사용하여 필요한 패키지를 설치하십시오.
pip install gpt-researcher LocalGPTResearcher 의 경우 다음 환경 변수를 설정해야합니다.
export DOC_PATH=/path/to/your/documents
export OPENAI_API_KEY=your-openai-api-key
export TAVILY_API_KEY=your-tavily-api-key WebGPTResearcher 의 경우 OPENAI_API_KEY 및 TAVILY_API_KEY 만 필요합니다.
export OPENAI_API_KEY=your-openai-api-key
export TAVILY_API_KEY=your-tavily-api-key 이 예는 LocalGPTResearcher 사용하여 로컬 문서를 기반으로 보고서를 생성하는 방법을 보여줍니다.
from libs . community . langchain_community . tools . gpt_researcher . tool import LocalGPTResearcher # This will be changed after successful PR
# Initialize the tool
researcher_local = LocalGPTResearcher ( report_type = "research_report" )
# You can also define it as `researcher_local = LocalGPTResearcher()` - default report_type is research_report.
# Run a query
query = "What is the demographics of Apple inc look like?"
report = researcher_local . invoke ({ "query" : query })
print ( "Generated Report:" , report ) 이 예는 WebGPTResearcher 사용하여 웹 데이터를 기반으로 보고서를 생성하는 방법을 보여줍니다.
from libs . community . langchain_community . tools . gpt_researcher . tool import WebGPTResearcher # This will be changed after successful PR
# Initialize the tool
researcher_web = WebGPTResearcher ( report_type = "research_report" ) # report_type="research_report" is optional as the default value is `research_report`
# Run a query
query = "What are the latest advancements in AI?"
report = researcher_web . invoke ({ "query" : query })
print ( "Generated Report:" , report )WebGPTResearcher 와 함께 AgentExecutor 사용합니다LLM과 도구를 사용하여 에세이를 작성하고 보고서 끝에 인용/서명을 제공하는 AgentExecutor 래퍼를 구축하는 방법을 살펴 보겠습니다.
from libs . community . langchain_community . tools . gpt_researcher . tool import WebGPTResearcher # This will be changed after successful PR
from langchain import hub
from langchain_core . tools import Tool
from langchain . agents import AgentExecutor , create_react_agent
from langchain . tools import tool
from langchain_openai import ChatOpenAI
# Let us see how to use the WebGPTResearcher tool along with AgentExecutor to perform a grand task with decision making.
# 1. Let us build a Reactive Agent who takes decisions based on reasoning.
# 2. Let us give our agent 2 tools - WebGPTResearcher and a dummy tool that provides a signature at the end of the text
# 3. We can then wrap our agent and tools inside an AgentExecutor object and ask our question!
# The expectation is the response must be signed at the end after a long report on a research topic.
# Create a new tool called citation_provider.
@ tool
def citation_provider ( text : str ) -> str :
"""Provides a citation or signature"""
return " n - Written by GPT-Makesh n Thanks for reading! n "
# Create the WebGPTResearcher tool
researcher_web = WebGPTResearcher ( "research_report" )
# Initialize tools and components
tools = [
researcher_web ,
Tool (
name = "citation_tool" ,
func = citation_provider ,
description = "Useful for when you need to add citation or signature at the end of text" ,
),
]
# Create an LLM
llm = ChatOpenAI ( model = "gpt-4o" )
prompt = hub . pull ( "hwchase17/react" )
# Create the ReAct agent using the create_react_agent function
agent = create_react_agent (
llm = llm ,
tools = tools ,
prompt = prompt ,
stop_sequence = True ,
)
# Wrap the components inside an AgentExecutor
agent_executor = AgentExecutor . from_agent_and_tools ( agent = agent , tools = tools , verbose = True )
# Run the agent
question = "What are the recent advancements in AI? Provide a citation for your report too."
response = agent_executor . invoke ({ "input" : question })
print ( "Agent Response:" , response )WebGPTResearcher 의 간단한 순차적 체인보고서를 작성하는 연구원과 그 다음에 등급을 매기고 점수를 매기는 연구원이있는 일련의 런 가능성 체인을 구축합시다.
from libs . community . langchain_community . tools . gpt_researcher . tool import WebGPTResearcher
from langchain . prompts import ChatPromptTemplate
from langchain . schema . output_parser import StrOutputParser
from langchain . schema . runnable import RunnableLambda
from langchain_openai import ChatOpenAI
# Let us use WebGPTResearcher to grade the essay using LECL langchain Chaining tricks
# 1. Use the researcher to write an essay
# 2. Pass it as a chat_prompt_template (a runnable) to a grader to score the essay
# 3. Parse the output as a string
# Create a ChatOpenAI model
grader = ChatOpenAI ( model = "gpt-4o" )
researcher_tool = WebGPTResearcher ()
prompt_template = ChatPromptTemplate . from_messages (
[
( "system" , "You are a essay grader. Give score out of 10 in brief" ),
( "human" , "The essay: {essay}" ),
]
)
# Define our WebGPTResearcher tool as a RunnableLambda
researcher = RunnableLambda ( lambda x : researcher_tool . invoke ( x ))
# Create the combined chain using LangChain Expression Language (LCEL)
chain = researcher | prompt_template | grader | StrOutputParser ()
# Run the chain
result = chain . invoke ({ "query" : "What are the recent advancements in AI?" })
# Output
print ( result )BaseGPTResearcher 확장 BaseGPTResearcher 클래스를 확장하여 사용자 정의 도구를 만들 수 있습니다. 예는 다음과 같습니다.
from libs . community . langchain_community . tools . gpt_researcher . tool import WebGPTResearcher
class CustomGPTResearcher ( BaseGPTResearcher ):
name = ""
description = ""
def __init__ ( self , report_type : ReportType = ReportType . RESEARCH ):
super (). __init__ ( report_type = report_type , report_source = "web" )
# Override or extend methods as needed (You need to implement `_run()` method, `_arun()` is optional)API 참조 : (GPT 연구원 도구) [링크]
다음과 같이 사용자 정의 GPTR 도구를 정의 할 수 있습니다.
import asyncio
from typing import Optional , Type
from langchain_core . callbacks import CallbackManagerForToolRun
from langchain_core . pydantic_v1 import BaseModel , Field
from langchain_core . tools import BaseTool
from gpt_researcher import GPTResearcher
class GPTRInput ( BaseModel ):
"""Input schema for the GPT-Researcher tool."""
query : str = Field ( description = "The search query for the research" )
class MyGPTResearcher ( BaseTool ):
name : str = "custom_gpt_researcher"
description : str = "Base tool for researching and producing detailed information about a topic or query using the internet."
args_schema : Type [ BaseModel ] = GPTRInput
async def get_report ( self , query : str ) -> str :
try :
researcher = GPTResearcher (
query = query ,
report_type = "research_report" ,
report_source = "web" ,
verbose = False
)
await researcher . conduct_research ()
report = await researcher . write_report ()
return report
except Exception as e :
raise ValueError ( f"Error generating report: { str ( e ) } " )
def _run (
self ,
query : str ,
run_manager : Optional [ CallbackManagerForToolRun ] = None
) -> str :
answer = asyncio . run ( self . get_report ( query = query ))
answer += " n n - By GPT-Makesh. n Thanks for reading!"
return answer
my_researcher = MyGPTResearcher ()
report = my_researcher . invoke ({ "query" : "What are the recent advancements in AI?" })
print ( report )또는 기성품을 수정하지 않고 제공된 도구를 직접 사용할 수 있습니다.
from libs . community . langchain_community . tools . gpt_researcher . tool import WebGPTResearcher , LocalGPTResearcher
# Use LocalGPTResearcher
researcher_local = LocalGPTResearcher ( report_type = "research_report" )
report = researcher_local . invoke ({ 'query' : "What can you tell about the company?" })
# Use WebGPTResearcher
researcher_web = WebGPTResearcher ( report_type = "research_report" )
report = researcher_web . invoke ({ 'query' : "What are the latest advancements in AI?" })gpt-4o-mini 및 gpt-4o (128K 컨텍스트)와 같은 모델을 사용하여 성능 및 비용에 최적화됩니다. 평균 연구 작업은 약 3 분이 걸리며 약 $ 0.005가 소요됩니다.우리는 GPT-Researcher 도구를 개선하고 확장하기위한 기여를 환영합니다. 기여를 시작하려면 Github 저장소를 방문하십시오.