# Configuration file for managing API keys as environment variables
from dotenv import load_dotenv
# Load API key information
load_dotenv()
Copy
True
Copy
# LangSmith set up tracking. https://smith.langchain.com
# !pip install -qU langchain-teddynote
from langchain_teddynote import logging
# Enter a project name.
logging.langsmith("CH15-Agent-Toolkits")
Copy
First, temporary folder tmp Generate.
Copy
FileManagementToolkit
FileManagementToolkit Is a collection of tools for local file management.
Main components
File management tools
CopyFileTool : Copy file
DeleteFileTool : Delete file
FileSearchTool : File Search
MoveFileTool : Move file
ReadFileTool : Read file
WriteFileTool : Write file
ListDirectoryTool : Directory list lookup
Settings
root_dir : Root directory setting of file operations possible
selected_tools : Only certain tools are available selectively
Dynamic tool creation
get_tools Create instances of selected tools with methods
this FileManagementToolkit Can be useful when automating local file management tasks or giving AI agents the ability to manipulate files. However, a careful approach is needed in terms of security.
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
tmp Check inside the folder to see that the file was created as shown below.
Copy
tmp Check inside the folder to see that the file name has changed as shown below.
import os
if not os.path.exists("tmp"):
os.mkdir("tmp")
# FileManagementToolkit bring it. This tool is used to perform file management tasks.
from langchain_community.agent_toolkits import FileManagementToolkit
# Set the directory named 'tmp' as the working directory.
working_directory = "tmp"
# FileManagementToolkit creates an object
# root_dir Specify a working directory in the parameter so that all file operations are performed within this directory.
toolkit = FileManagementToolkit(root_dir=str(working_directory))
# Get all available file management tools by calling the toolkit.get_tools() method.
# These tools provide functions for copying, deleting, searching, moving, reading, writing, and listing files.
available_tools = toolkit.get_tools()
# Prints the names of available tools.
print("[Available file management tools]")
for tool in available_tools:
print(f"- {tool.name}: {tool.description}")
[Available file management tools]
-copy_file: Create a copy of a file in a specific location
-file_delete: Delete a file
-file_search: Recursively search for files in a subdirectory that match the regex pattern
-move_file: Move or rename a file from one location to another
-read_file: Read file from disk
-write_file: Write file to disk
-list_directory: List files and directories in a specific folder
# It is also possible to select only some of the tools.
tools = FileManagementToolkit(
root_dir=str(working_directory),
selected_tools=["read_file", "file_delete", "write_file", "list_directory"],
).get_tools()
tools
# Import the required modules and classes.
from langchain.tools import tool
from typing import List, Dict
from langchain_teddynote.tools import GoogleNews
# Defines the latest news search tool.
@tool
def latest_news(k: int = 5) -> List[Dict[str, str]]:
"""Look up latest news"""
# Create an googleNews object.
news_tool = GoogleNews()
# Searches for the latest news and returns the results. k is the number of news items to return.
return news_tool.search_latest(k=k)
# Get file management tools using FileManagementToolkit.
tools = FileManagementToolkit(
root_dir=str(working_directory),
).get_tools()
# Add the latest news search tool to your tools list.
tools.append(latest_news)
# Prints a list of tools containing all tools.
tools
Copyfrom langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_teddynote.messages import AgentStreamParser
# Create a dictionary to store session_id
store = {}
# Generate prompt
# Prompts provide text that describes to the agent what the model should do (enter the name of the tool and its role).
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful assistant. "
"Make sure to use the `latest_news` tool to find latest news. "
"Make sure to use the `file_management` tool to manage files. ",
),
("placeholder", "{chat_history}"),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
]
)
# create an LLM
llm = ChatOpenAI(model="gpt-4o-mini")
# Agent creation
agent = create_tool_calling_agent(llm, tools, prompt)
# AgentExecutor generation
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=False,
handle_parsing_errors=True,
)
# Function to retrieve session records based on session_id
def get_session_history(session_ids):
if session_ids not in store: # If session_id is not in the store
# Create a new ChatMessageHistory object and save it to the store.
store[session_ids] = ChatMessageHistory()
return store[session_ids] # Returns the session record for the given session ID.
# Create an agent with added chat message history.
agent_with_chat_history = RunnableWithMessageHistory(
agent_executor,
# λν session_id
get_session_history,
# Key: "input" where the question in the prompt is entered
input_messages_key="input",
# The message in the prompt is entered key: "chat_history"
history_messages_key="chat_history",
)
agent_stream_parser = AgentStreamParser()
result = agent_with_chat_history.stream(
{
"input": "Search for the 5 latest news, create a file with the title of each news as the file name (.txt), and add the contents of the news and url to the " " file."
},
config={"configurable": {"session_id": "abc123"}},
)
print("Agent execution results:")
for step in result:
agent_stream_parser.process_agent_steps(step)
Agent run results:
[Tool call]
Tool: latest_news
k: 5
Log:
Invoking: `latest_news` with `{'k': 5}`
[Observation content]
Observation: [{'url':'https://news.google.com/rss/articles/CBMiZkFVX3lxTE55OWlTNnNaWi03N2FoQThLRHM4aktxNmZNenA5czJPMmhmWFZ0WFUxUXZXQ09EUnZCREdULVlGOGYxVElUanJoRFR6aHdCNWQxNk1GQ2x2Y2stX1YxTXN0S2d2WFI2Zw?oc=5','content':'Reducing 5 years of medical practice βNo prior consultation with the Ministry of Education β -Korean'}, {'url':'https://news.google.com/rss/articles/CBMiZkFVX3lxTFBTTTVXZjRhUzZ0SFRCdWhLRE9VcnFwQVRCNkZ0ZlFjMzNBMjB5Yk5sMmhqRzBEMElVZ2tteXdCZmVRRFFNLXZRY0luVnFKM1VmdUtjaWF1WW4tYzNPOHNkeWFVNHFLZw?oc=5','content ':'Han-Philippines Summit. com/rss/articles/CBMieEFVX3lxTE9GTHhYbkNwbC1pYW9UbnlDMExQVkhKRWFnSHFaUUR0S0hyX05oRGZMbkp4YkZaRHNwYU92VDFMNVNpQV81dElxdGJaTEdwWDhtNWRsb3lQN21HS1Z6ZFl2TTlCU2FsZ1k3dHNxY2lSampMdUlKLXg5d9IBeEFVX3lxTE91MmdsUUhRRnV1MnFFb1VfNWVGTkpyeHlka0dXblVZWnpXRk1XNkMtRU9vVVJUNGQ4NWVobXRuSkRJZE5Tc0NjdnN1amJtMElJaWFIRVZraFppYUFOS05JOGlKUi04RGVNeE5OQ1hhUm4yenFWbzd2RQ?oc=5','content':'Start of the National Assembly.. It's all over the top. -MBC News'}, {'url':'https://news.google.com/rss/articles/CBMiYEFVX3lxTE5aRmIzTzdqT1FaQmVrZUY2SlhMRzNKbUNOM05EbGk0SXhUTkk1bGgxNzRTSmN2RWdRSFh4QlVWODI0RUk5WUhZZkJWWkEwQWpEMkU1OFhuY0ExOEhjT2pnUA?oc=5','content': "[Breaking News','Prosecution of Public Election Law' '<Gl , com/rss/articles/CBMieEFVX3lxTE5fbk5wQl9TdEg4UnlRb2xUZHdBQ0hIV21uaktJbE9zSC14UU5jaktKOGhDODdmWWtKMHliOUpkNTU2NnY0UHN4Z3VJUjFpdGs4S0k0R1M1OE92b0pKNUVXbzBqQVc1d1c5MVhfZ1R6OFpYa1J6NVI2QdIBeEFVX3lxTE1uaVNNMGtwcUxPUWRYZllLXzVSaDFtZEQ4WW9Pb05fZGg1dl96SWRMMHk3Tms0MkZtWmRUMXNoanlQRTA5bGFnUjhGM185YnJBcWJfTmotaDl4SGhxY1ZGTnJxTFpYQ0plVVFhTF9zQVJCRE5Sa2pQUw?oc=5','content':'Judges, trial of Lee Jae-myeong and workshop.. ruling party "Hurry to judge"-opposition "Muritist" -MBC News'}]
[Tool call]
Tool: write_file
file_path: George W. Welfare Officer β5 years of medical school shortened, no prior consultation with the Ministry of Education β.txt
text: George W. Welfare Officer β5 years of medical school shortened, no prior consultation with the Ministry of Education β
URL: https://news.google.com/rss/articles/CBMiZkFVX3lxTE55OWlTNnNaWi03N2FoQThLRHM4aktxNmZNenA5czJPMmhmWFZ0WFUxUXZXQ09EUnZCREdULVlGOGYxVElUanJoRFR6aHdCNWQxNk1GQ2x2Y2stX1YxTXN0S2d2WFI2Zw?oc=5
append: False
Log:
Invoking: `write_file` with `{'file_path':'Geosygulf Welfare Officer β5 years shortened, no prior consultation with the Ministry of Education β.txt','text':'George Welfare Officer β5 years of medical school Shortened, no prior consultation with the Ministry of Education<
[Tool call]
Tool: write_file
file_path: Han-Philippines Summit... ββ Strategic Companion β Established β.txt
text: Han-Philippines Summit... ββ Strategic Companion β Established β
URL: https://news.google.com/rss/articles/CBMiZkFVX3lxTFBTTTVXZjRhUzZ0SFRCdWhLRE9VcnFwQVRCNkZ0ZlFjMzNBMjB5Yk5sMmhqRzBEMElVZ2tteXdCZmVRRFFNLXZRY0luVnFKM1VmdUtjaWF1WW4tYzNPOHNkeWFVNHFLZw?oc=5
append: False
Log:
Invoking: `write_file` with `{'file_path':'Han-Philippines Summit...ββ Strategic Companion Relations β Established β.txt','text':'Han-Philippines Summit...ββ< Strategic Companion
[Tool call]
Tool: write_file
file_path: Beginning of the National Assembly... It's all over the top.
text: The National Assembly begins... It must be around the top.
URL: https://news.google.com/rss/articles/CBMieEFVX3lxTE9GTHhYbkNwbC1pYW9UbnlDMExQVkhKRWFnSHFaUUR0S0hyX05oRGZMbkp4YkZaRHNwYU92VDFMNVNpQV81dElxdGJaTEdwWDhtNWRsb3lQN21HS1Z6ZFl2TTlCU2FsZ1k3dHNxY2lSampMdUlKLXg5d9IBeEFVX3lxTE91MmdsUUhRRnV1MnFFb1VfNWVGTkpyeHlka0dXblVZWnpXRk1XNkMtRU9vVVJUNGQ4NWVobXRuSkRJZE5Tc0NjdnN1amJtMElJaWFIRVZraFppYUFOS05JOGlKUi04RGVNeE5OQ1hhUm4yenFWbzd2RQ?oc=5
append: False
Log:
Invoking: `write_file` with `{'file_path':'Start of the National Assembly.. It's time to come.... Clash.txt','text':'State of the National Assembly.. It's all over the ranks. Collision\n\nURL: https://news.google.com/rss/articles/CBMieEFVX3lxTE9GTHhYbkNwbC1pYW9UbnlDMExQVkhKRWFnSHFaUUR0S0hyX05oRGZMbkp4YkZaRHNwYU92VDFMNVNpQV81dElxdGJaTEdwWDhtNWRsb3lQN21HS1Z6ZFl2TTlCU2FsZ1k3dHNxY2lSampMdUlKLXg5d9IBeEFVX3lxTE91MmdsUUhRRnV1MnFFb1VfNWVGTkpyeHlka0dXblVZWnpXRk1XNkMtRU9vVVJUNGQ4NWVobXRuSkRJZE5Tc0NjdnN1amJtMElJaWFIRVZraFppYUFOS05JOGlKUi04RGVNeE5OQ1hhUm4yenFWbzd2RQ?oc=5','append': False<
[Tool call]
Tool: write_file
file_path: [Breaking News] Police,'Proposed Violation of the Public Election Act' .txt
text: [Breaking News] Police,'Proposed Violation of Public Election Law' President γ
URL: https://news.google.com/rss/articles/CBMiYEFVX3lxTE5aRmIzTzdqT1FaQmVrZUY2SlhMRzNKbUNOM05EbGk0SXhUTkk1bGgxNzRTSmN2RWdRSFh4QlVWODI0RUk5WUhZZkJWWkEwQWpEMkU1OFhuY0ExOEhjT2pnUA?oc=5
append: False
Log:
Invoking: `write_file` with `{'file_path': "[Breaking News] Police,'Public Election Law Violation' α President Bullying .txt",'text': "[Breaking News] Police,'Public Election Law Violation' ,'Exp As likely to send \n\nURL:
[Tool call]
Tool: write_file
file_path: Lawyer, Lee Jae-myeong trial and workshop.. Yeosun "Hurry to judge"-Yardan "Murderer".txt
text: Lawyer, trial of the present and workshop... "Hurry to judge"-Night "Murderer"
URL: https://news.google.com/rss/articles/CBMieEFVX3lxTE5fbk5wQl9TdEg4UnlRb2xUZHdBQ0hIV21uaktJbE9zSC14UU5jaktKOGhDODdmWWtKMHliOUpkNTU2NnY0UHN4Z3VJUjFpdGs4S0k0R1M1OE92b0pKNUVXbzBqQVc1d1c5MVhfZ1R6OFpYa1J6NVI2QdIBeEFVX3lxTE1uaVNNMGtwcUxPUWRYZllLXzVSaDFtZEQ4WW9Pb05fZGg1dl96SWRMMHk3Tms0MkZtWmRUMXNoanlQRTA5bGFnUjhGM185YnJBcWJfTmotaDl4SGhxY1ZGTnJxTFpYQ0plVVFhTF9zQVJCRE5Sa2pQUw?oc=5
append: False
Log:
Invoking: `write_file` with `{'file_path':'Judge, Lee Jae-myeong Jae-myeong, Joo Jae-myeong... Yoo "Judges".txt','text':'Judges, Jae-myeong Jae-joo's "Jaejeong, "
[Observation content]
Observation: File written successfully to Zoosyong Welfare Officer β5 years of medical school shortening, no prior consultation with the Ministry of Education β.txt.
[Observation content]
Observation: File written successfully to Han-Philippines Summit... ββ Strategic Companion Relations β Established β.txt.
[Observation content]
Observation: File written successfully to National Assembly Deputy Director begins.. It's all over the top.
[Observation content]
Observation: File written successfully to [Breaking News] Police,'Proposed violation of the public election law' γ President seems to be in transit.txt.
[Observation content]
Observation: File written successfully to Lawyer, Lee Jae-myeong Jae-myeong, Jae-myeong Ji-myeong... Yeo-dang "Hurry to judge"-Night "Wizard".txt.
[Final answer]
I created a file with the title of the latest 5 news as the file name. Each file contains the content and URL of the news. The list of files created is as follows:
One. ** George Hong Welfare Officer β5 years of medical school shortened, no prior consultation with the Ministry of Education β.txt**
2. ** Han-Philippines Summit... ββ Strategic Companion β Established β.txt**
3. ** Beginning of the National Assembly of the National Assembly.. It's all over the top.
4. **[Breaking News] Police,'Proposed Violation of Public Election Law' President .txt**
5. **Judges, Lee Jae-myeong Trial and Vacancy.. Yeosang "Hurry to judge"-Yardan "Murderer".txt**
These files were created on request, and the content contains the core and URL of each news. Please tell me if you need any additional work!
result = agent_with_chat_history.stream(
{
"input": "Change the file name by adding an emoji that matches the title to the beginning of the previously created file title."
"Please also change the file name neatly. "
},
config={"configurable": {"session_id": "abc123"}},
)
print("Agent μ€ν κ²°κ³Ό:")
for step in result:
agent_stream_parser.process_agent_steps(step)
result = agent_with_chat_history.stream(
{
"input": "Create a `news` folder with all the files you created previously, and copy all the files into that folder. " " Copy the contents as well. "
},
config={"configurable": {"session_id": "abc123"}},
)
print("Agent execution results:")
for step in result:
agent_stream_parser.process_agent_steps(step)