# [LangChain] 範例-用自然語言管理檔案 日期:2023/09/18 ## 敘述 - 主題:initialize_agent()、Command-Line Interface - 使用情境:透過自然語言直接對檔案進行操作。使用者不需要記得各種指令,只需要用自然語言提出要求,接著交由model判斷對應的指令,提供給CLI(Command-Line Interface)執行。 - 輸入:列出檔案、刪除xxx檔案等等 - 輸出:電腦根據輸入的自然語言指令進行動作 ## 目錄 - [1. 程式碼](#1-程式碼) - [2. 執行](#2-執行) - [參考資料](#參考資料) ____ ## 1. 程式碼 需將以下程式碼以.py檔儲存,並在CLI中執行此檔案。 將透過agent自動尋找符合輸入的工具,透過此工具完成對應的動作。 以下為程式使用到的tool種類: copy_file file_delete file_search move_file read_file write_file list_directory ```python= import click from langchain.agents.agent_toolkits import FileManagementToolkit from langchain.chat_models import ChatOpenAI from langchain.agents import AgentType, initialize_agent from dotenv import load_dotenv load_dotenv() #@click.command()為裝飾器,在此處裝飾了名為interact的函式,此函式變成為了可在命令列中執行的命令 @click.command() def interact(): """ 與OpenAI Functions進行互動。 透過Agent自動選擇提供的工具(函式)。 """ model = ChatOpenAI(model="gpt-3.5-turbo-0613") tools = FileManagementToolkit().get_tools() #agent,定義agent,提供需要用到的tool作為參數。 open_ai_agent = initialize_agent(tools, model, agent=AgentType.OPENAI_FUNCTIONS, verbose=False) #若沒有關閉,執行時會出現執行的資訊,使畫面顯得凌亂。 #透過while持續執行定義好的agent。 while True: try: #click.prompt()用於讓使用者可以提供輸入, question = click.prompt('Question: ') tool_result = open_ai_agent.run(question) #echo command,顯示回覆內容。 click.echo(f'Answer: {tool_result}') except KeyboardInterrupt: break if __name__ == '__main__': interact() ``` ## 2. 執行 透過cmd執行上述程式碼。需先執行存好的.py檔。 ``python filemanagement.py``。這條命令告訴系統去執行 filemanagement.py 這個 Python 腳本,並使用全域的 Python 解譯器來執行。只要確保你已經在電腦上安裝了 Python,就可以在命令提示字元 (cmd) 中輸入這個指令。如果這個程式需要特定的套件,請確保這些套件已經在全域的 Python 環境中安裝好。 ```python python C:\Users\Admin\anaconda\LangChain\書籍\實戰\filemanagement.py ``` 本人使用anaconda,並且將使用了虛擬環境,因此需先使用以下程式碼啟動對應的環境。 ``` activate testenv1 ``` 執行結果: :::info Question: : 列出檔案 Answer: 這是目前資料夾中的檔案: 1\. 1.txt 2\. 11.txt 3\. 33.txt Question: : 創建檔案22.txt Answer: 已成功創建檔案22.txt。 Question: : 刪除檔案22.txt Answer: 檔案22.txt已成功刪除。 Question: : 寫一首詩並寫入44.txt Answer: 已經成功將詩寫入到44.txt檔案中。以下是詩的內容: 寒風吹過林間 紛飛的落葉如舞者 大地漸漸被覆蓋 寂靜的冬季降臨 Question: : 列出檔案 Answer: 這是目前資料夾中的檔案清單: 1\. 1.txt 2\. 11.txt 3\. 33.txt 4\. 44.txt ::: 觀察: 透過此程式,確實能執行檔案相關的操作。 ____ ## 參考資料 上述程式碼源自於以下網址: https://github.com/kkdai/langchain_tools/tree/master/func_filemgr https://www.evanlin.com/langchain-function-agent/
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up