準備
本案例使用deepseek,登錄deepseek官網,登錄賬號,充值幾塊錢,然后創建Api key
????????可以創建虛擬環境,python版本最好是3.12,以下是文件目錄。test文件夾中,放一些txt文件做測試,main.py就是充當agent,tools.py是自定義工具(函數),大模型就是通過調用這些工具幫你完成需求。
????????大致流程就是,我寫好工具,創建一個agent(一段程序),在agent中注冊好我創建的工具,同時調用deepseek(作為我的私人程序員)。之后,我向agent發出需求,agent將需求傳遞給deepseek,deepseek分析出完成這個需求,需要使用哪些工具,返回給agent,agent根據指示再去調用工具,工具執行完,將結果返回給agent,agent再將結果返回給deepseek,然后deepseek給出最終答案,返回給agent,agent返回給用戶。
工具
????????這里,我們就指定了只對 test文件夾進行操作,有 列出文件夾中所有文件名稱、讀取文件內容、重命名文件、創建文件的四個工具。
import ostest_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'test')print(test_path)
def list_files() -> list[str]:"""列出 test 文件夾中所有文件名稱,返回列表(相對路徑)"""file_list = []for root, dirs, files in os.walk(test_path):for file in files:# 獲取相對路徑rel_path = os.path.relpath(os.path.join(root, file), test_path)file_list.append(rel_path)return file_listprint(list_files())def read_file(name: str) -> str:"""讀取test文件夾下,某一文件內容"""print(f"(read_file {name})")try:with open(os.path.join(test_path,name), "r") as f:content = f.read()return contentexcept Exception as e:return f"An error occurred: {e}"def rename_file(name: str, new_name: str) -> str:"""重命名 test 文件夾下的文件"""print(f"(rename_file {name} -> {new_name})")try:old_path = os.path.join(test_path, name)new_path = os.path.join(test_path, new_name)# 檢查 new_path 是否在 test_path 內if not os.path.abspath(new_path).startswith(os.path.abspath(test_path)):return "Error: new_name is outside test_path."# 創建父目錄os.makedirs(os.path.dirname(new_path), exist_ok=True)# 執行重命名os.rename(old_path, new_path)return f"File '{name}' successfully renamed to '{new_name}'."except Exception as e:return f"An error occurred: {e}"def create_file(name: str, content: str = "") -> str:"""在 test 文件夾下創建文件,并寫入內容"""print(f"(create_file {name})")try:file_path = os.path.join(test_path, name)# 檢查文件是否在 test_path 內if not os.path.abspath(file_path).startswith(os.path.abspath(test_path)):return "Error: file path is outside test_path."# 創建父目錄(如果有子目錄的話)os.makedirs(os.path.dirname(file_path), exist_ok=True)# 寫入內容with open(file_path, "w", encoding="utf-8") as f:f.write(content)return f"File '{name}' successfully created."except Exception as e:return f"An error occurred: {e}"
agent
pip install pydantic-ai如果安裝完成后,出現 pydantic-core 不存在 的錯誤
pip install --force-reinstall --no-cache-dir --only-binary=:all: pydantic-core -i https://pypi.org/simple
創建一個.env文件,里面寫入DEEPSEEK_API_KEY=你的deepseek api key 等號兩邊不要有空格,不要有引號
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider
import tools
from dotenv import load_dotenv
import os
load_dotenv()#讀取env文件中的變量到環境變量中#使用deepseek模型
model = OpenAIModel("deepseek-chat",provider=OpenAIProvider(api_key=os.getenv('DEEPSEEK_API_KEY'), # 從環境變量加載API密鑰base_url="https://api.deepseek.com"))
agent = Agent(model,system_prompt='你是我的windows系統管理大師' ,#設定大模型其角色tools=[ #給agent注冊工具tools.list_files,tools.rename_file,tools.read_file,tools.create_file,] )def main():history = []while True:user_input = input("Input: ")resp = agent.run_sync(user_input,message_history=history)#記住上下文history = list(resp.all_messages())print(resp.output)if __name__ == "__main__":main()
執行結果,此時的agent就像一個你自己雇傭的程序員一樣,可以對test文件夾執行你指定工具的所有功能