import os
from typing import Anyfrom langchain. agents import AgentType, initialize_agent, Tool
from langchain_openai import ChatOpenAI
from langchain. tools import BaseTool
from langchain_experimental. tools. python. tool import PythonREPLTool
from langchain. memory import ConversationBufferMemory
from langchain_community. utilities import WikipediaAPIWrapper
from langgraph. prebuilt import create_react_agent
os. environ[ "OPENAI_API_KEY" ] = "sk-cRMC2m0GsE18vYaWdAMj"
os. environ[ "OPENAI_BASE_URL" ] = "https://aigptx.top/v1/"
def create_init_tool_agent ( ) : """創建基本的ReAct智能體""" wikipedia = WikipediaAPIWrapper( ) python_repl = PythonREPLTool( ) tools = [ Tool( name= "維基百科" , func= wikipedia. run, description= "用于查詢維基百科文章的工具" ) , Tool( name= "Python解釋器" , func= python_repl. run, description= "用于執行Python代碼的工具,可以進行計算或數據分析" ) ] llm = ChatOpenAI( temperature= 1 , max_tokens= 2000 , model= 'gpt-3.5-turbo-0125' ) memory = ConversationBufferMemory( memory_key= "chat_history" , return_messages= True ) langgraph_agent_executor = initialize_agent( tools, llm, agent= AgentType. CHAT_CONVERSATIONAL_REACT_DESCRIPTION, verbose= True , memory= memory, handle_parsing_errors= True ) return langgraph_agent_executor
def create_openai_functions_agent ( ) : """創建基于OpenAI函數調用的智能體""" wikipedia = WikipediaAPIWrapper( ) python_repl = PythonREPLTool( ) tools = [ Tool( name= "Python執行器" , func= python_repl. run, description= "執行Python代碼的工具,適合進行計算、數據處理" ) , Tool( name= "維基百科" , func= wikipedia. run, description= "搜索維基百科文章的工具,適合查詢事實性信息" ) ] llm = ChatOpenAI( temperature= 0 ) agent = initialize_agent( tools, llm, agent= AgentType. OPENAI_FUNCTIONS, verbose= True ) return agent
class WeatherTool ( BaseTool) : name: str = "天氣查詢" description: str = "查詢指定城市的天氣情況" def _run ( self, city: str ) - > str : return f" { city} 的天氣: 晴朗, 25°C, 濕度50%" async def _arun ( self, city: str ) - > str : return self. _run( city) class CalculatorTool ( BaseTool) : name: str = "計算器" description: str = "進行數學計算,輸入應為數學表達式" def _run ( self, expression: str ) - > str : try : result = eval ( expression) return f"計算結果: { result} " except Exception as e: return f"計算錯誤: { str ( e) } " async def _arun ( self, expression: str ) - > str : return self. _run( expression) def create_custom_tool_agent ( ) : """創建帶有自定義工具的智能體""" tools = [ WeatherTool( ) , CalculatorTool( ) , PythonREPLTool( ) ] llm = ChatOpenAI( temperature= 0 ) agents = initialize_agent( tools, llm, agent= AgentType. CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose= True ) return agents
if __name__ == "__main__" : print ( "=== LangChain 單智能體模式示例 ===" ) agent_type = "openai_functions" response: Any = '' if agent_type == "react" : agent = create_init_tool_agent( ) response = agent. invoke( { 'input' : '誰是阿爾伯特·愛因斯坦? 他出生于哪一年? 計算從他出生到現在過了多少年。回答的時候請使用中文輸出' , 'chat_history' : [ ] } ) elif agent_type == "openai_functions" : agent = create_openai_functions_agent( ) response = agent. invoke( { 'input' : '計算 2345 + 5678 的結果,并解釋這兩個數字的數學特性。' , 'chat_history' : [ ] } ) elif agent_type == "custom" : agent = create_custom_tool_agent( ) response = agent. invoke( { 'input' : '北京今天的時間和今天的天氣如何?然后計算25乘以4的結果。' , 'chat_history' : [ ] } ) print ( f"\n最終回答: { response} " )