4_agent_with_tools.py
1 """ 2 Agent with Tools Example. 3 This demonstrates how to create an AI agent that can use tools to accomplish tasks. 4 """ 5 6 from langchain_community.llms import Ollama 7 from langchain.agents import Tool, AgentExecutor, create_react_agent 8 from langchain.prompts import PromptTemplate 9 import math 10 11 # Initialize Ollama 12 llm = Ollama( 13 model="gpt-oss:120b", 14 base_url="http://192.222.50.154:11434", 15 temperature=0 # More deterministic for tool use 16 ) 17 18 # Define custom tools 19 def calculator(expression: str) -> str: 20 """ 21 A calculator tool that evaluates mathematical expressions. 22 """ 23 try: 24 # Safe evaluation of math expressions 25 result = eval(expression, {"__builtins__": {}}, { 26 "sin": math.sin, 27 "cos": math.cos, 28 "tan": math.tan, 29 "sqrt": math.sqrt, 30 "pi": math.pi, 31 "e": math.e, 32 "pow": pow, 33 "abs": abs, 34 }) 35 return str(result) 36 except Exception as e: 37 return f"Error: {str(e)}" 38 39 def string_length(text: str) -> str: 40 """ 41 Returns the length of a string. 42 """ 43 return str(len(text)) 44 45 def reverse_string(text: str) -> str: 46 """ 47 Reverses a string. 48 """ 49 return text[::-1] 50 51 # Create tool objects 52 tools = [ 53 Tool( 54 name="Calculator", 55 func=calculator, 56 description="Useful for mathematical calculations. Input should be a valid Python expression like '2 + 2' or 'sqrt(16)'. Available functions: sin, cos, tan, sqrt, pi, e, pow, abs." 57 ), 58 Tool( 59 name="StringLength", 60 func=string_length, 61 description="Returns the length of a string. Input should be the string." 62 ), 63 Tool( 64 name="ReverseString", 65 func=reverse_string, 66 description="Reverses a string. Input should be the string to reverse." 67 ) 68 ] 69 70 # Create ReAct prompt template 71 template = """Answer the following questions as best you can. You have access to the following tools: 72 73 {tools} 74 75 Use the following format: 76 77 Question: the input question you must answer 78 Thought: you should always think about what to do 79 Action: the action to take, should be one of [{tool_names}] 80 Action Input: the input to the action 81 Observation: the result of the action 82 ... (this Thought/Action/Action Input/Observation can repeat N times) 83 Thought: I now know the final answer 84 Final Answer: the final answer to the original input question 85 86 Begin! 87 88 Question: {input} 89 Thought: {agent_scratchpad} 90 """ 91 92 prompt = PromptTemplate.from_template(template) 93 94 # Create agent 95 agent = create_react_agent(llm, tools, prompt) 96 97 # Create agent executor 98 agent_executor = AgentExecutor( 99 agent=agent, 100 tools=tools, 101 verbose=True, 102 handle_parsing_errors=True, 103 max_iterations=5 104 ) 105 106 if __name__ == "__main__": 107 # Example queries that require tool use 108 queries = [ 109 "What is the square root of 144 plus 10?", 110 "How long is the string 'LangChain is awesome!'?", 111 "Reverse the string 'Hello World' and tell me its length", 112 "Calculate 2 to the power of 8, then divide by 4" 113 ] 114 115 for query in queries: 116 print("\n" + "=" * 60) 117 print(f"Query: {query}") 118 print("=" * 60) 119 try: 120 response = agent_executor.invoke({"input": query}) 121 print(f"\nFinal Answer: {response['output']}\n") 122 except Exception as e: 123 print(f"Error: {str(e)}\n")