이 노트북에서는 Reddit search tool이 어떻게 작동하는지 알아봅니다. 먼저 아래 명령어로 praw를 설치했는지 확인하세요:
pip install -qU  praw
그런 다음 적절한 API key와 environment variable을 설정해야 합니다. Reddit 사용자 계정을 만들고 credential을 받아야 합니다. www.reddit.com에 가서 가입하여 Reddit 사용자 계정을 만드세요. 그런 다음 www.reddit.com/prefs/apps에 가서 앱을 만들어 credential을 받으세요. 앱을 만들면 client_id와 secret을 받게 됩니다. 이제 이 문자열들을 client_id와 client_secret 변수에 붙여넣으면 됩니다. 참고: user_agent에는 아무 문자열이나 넣어도 됩니다
client_id = ""
client_secret = ""
user_agent = ""
from langchain_community.tools.reddit_search.tool import RedditSearchRun
from langchain_community.utilities.reddit_search import RedditSearchAPIWrapper

search = RedditSearchRun(
    api_wrapper=RedditSearchAPIWrapper(
        reddit_client_id=client_id,
        reddit_client_secret=client_secret,
        reddit_user_agent=user_agent,
    )
)
그런 다음 쿼리를 설정할 수 있습니다. 예를 들어, 어떤 subreddit을 쿼리할지, 몇 개의 게시물을 반환받을지, 결과를 어떻게 정렬할지 등을 설정합니다.
from langchain_community.tools.reddit_search.tool import RedditSearchSchema

search_params = RedditSearchSchema(
    query="beginner", sort="new", time_filter="week", subreddit="python", limit="2"
)
마지막으로 검색을 실행하고 결과를 받습니다
result = search.run(tool_input=search_params.dict())
print(result)
다음은 결과를 출력하는 예시입니다. 참고: subreddit의 최신 게시물에 따라 다른 출력을 받을 수 있지만 형식은 비슷해야 합니다.
Searching r/python found 2 posts: Post Title: ‘Setup Github Copilot in Visual Studio Code’ User: Feisty-Recording-715 Subreddit: r/Python: Text body: 🛠️ This tutorial is perfect for beginners looking to strengthen their understanding of version control or for experienced developers seeking a quick reference for GitHub setup in Visual Studio Code. 🎓 By the end of this video, you’ll be equipped with the skills to confidently manage your codebase, collaborate with others, and contribute to open-source projects on GitHub. Video link: youtu.be/IdT1BhrSfdo?si=mV7xVpiyuhlD8Zrw Your feedback is welcome Post URL: www.reddit.com/r/Python/comments/1823wr7/setup_github_copilot_in_visual_studio_code/ Post Category: N/A. Score: 0 Post Title: ‘A Chinese Checkers game made with pygame and PySide6, with custom bots support’ User: HenryChess Subreddit: r/Python: Text body: GitHub link: github.com/henrychess/pygame-chinese-checkers I’m not sure if this counts as beginner or intermediate. I think I’m still in the beginner zone, so I flair it as beginner. This is a Chinese Checkers (aka Sternhalma) game for 2 to 3 players. The bots I wrote are easy to beat, as they’re mainly for debugging the game logic part of the code. However, you can write up your own custom bots. There is a guide at the github page. Post URL: www.reddit.com/r/Python/comments/181xq0u/a_chinese_checkers_game_made_with_pygame_and/ Post Category: N/A. Score: 1

agent chain과 함께 tool 사용하기

Reddit search 기능은 multi-input tool로도 제공됩니다. 이 예시에서는 문서의 기존 코드를 수정하고, ChatOpenAI를 사용하여 memory가 있는 agent chain을 만듭니다. 이 agent chain은 Reddit에서 정보를 가져와 이러한 게시물을 사용하여 후속 입력에 응답할 수 있습니다. 예시를 실행하려면 Reddit API 접근 정보를 추가하고 OpenAI API에서 OpenAI key를 받으세요.
# Adapted code from /docs/modules/agents/how_to/sharedmemory_for_tools

from langchain.agents import AgentExecutor, StructuredChatAgent
from langchain.chains import LLMChain
from langchain.memory import ConversationBufferMemory, ReadOnlySharedMemory
from langchain_community.tools.reddit_search.tool import RedditSearchRun
from langchain_community.utilities.reddit_search import RedditSearchAPIWrapper
from langchain_core.prompts import PromptTemplate
from langchain.tools import Tool
from langchain_openai import ChatOpenAI

# Provide keys for Reddit
client_id = ""
client_secret = ""
user_agent = ""
# Provide key for OpenAI
openai_api_key = ""

template = """This is a conversation between a human and a bot:

{chat_history}

Write a summary of the conversation for {input}:
"""

prompt = PromptTemplate(input_variables=["input", "chat_history"], template=template)
memory = ConversationBufferMemory(memory_key="chat_history")

prefix = """Have a conversation with a human, answering the following questions as best you can. You have access to the following tools:"""
suffix = """Begin!"

{chat_history}
Question: {input}
{agent_scratchpad}"""

tools = [
    RedditSearchRun(
        api_wrapper=RedditSearchAPIWrapper(
            reddit_client_id=client_id,
            reddit_client_secret=client_secret,
            reddit_user_agent=user_agent,
        )
    )
]

prompt = StructuredChatAgent.create_prompt(
    prefix=prefix,
    tools=tools,
    suffix=suffix,
    input_variables=["input", "chat_history", "agent_scratchpad"],
)

llm = ChatOpenAI(temperature=0, openai_api_key=openai_api_key)

llm_chain = LLMChain(llm=llm, prompt=prompt)
agent = StructuredChatAgent(llm_chain=llm_chain, verbose=True, tools=tools)
agent_chain = AgentExecutor.from_agent_and_tools(
    agent=agent, verbose=True, memory=memory, tools=tools
)

# Answering the first prompt requires usage of the Reddit search tool.
agent_chain.run(input="What is the newest post on r/langchain for the week?")
# Answering the subsequent prompt uses memory.
agent_chain.run(input="Who is the author of the post?")

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I