datadabllp

LLM agent that can use external tools

Aug 20th, 2024
655
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. import requests
  2. import wolframalpha
  3.  
  4. def weather_lookup(location):
  5.     api_key = "your_weather_api_key"
  6.     url = f"http://api.weatherapi.com/v1/current.json?key={api_key}&q={location}"
  7.     response = requests.get(url)
  8.     data = response.json()
  9.     return f"The current temperature in {location} is {data['current']['temp_c']}°C"
  10.  
  11. def wolfram_query(query):
  12.     client = wolframalpha.Client("your_wolfram_alpha_app_id")
  13.     res = client.query(query)
  14.     return next(res.results).text
  15.  
  16. tools = {
  17.     "weather_lookup": weather_lookup,
  18.     "wolfram_query": wolfram_query
  19. }
  20.  
  21. def tool_using_agent(user_input):
  22.     tool_selection_prompt = f"""
  23.    Based on the user's input, determine if a tool should be used to answer the question.
  24.    Available tools: {', '.join(tools.keys())}
  25.    
  26.    User input: {user_input}
  27.    
  28.    If a tool should be used, respond with the tool name and the parameter to pass to the tool.
  29.    If no tool is needed, respond with "No tool needed."
  30.    
  31.    Response:
  32.    """
  33.    
  34.     tool_decision = llm.generate(tool_selection_prompt)
  35.    
  36.     if tool_decision.startswith("No tool needed"):
  37.         return llm.generate(f"User: {user_input}\nAssistant:")
  38.     else:
  39.         tool_name, parameter = tool_decision.split(', ')
  40.         tool_result = tools[tool_name](parameter)
  41.        
  42.         final_response_prompt = f"""
  43.        User asked: {user_input}
  44.        Tool used: {tool_name}
  45.        Tool result: {tool_result}
  46.        
  47.        Please provide a natural language response to the user based on this information:
  48.        """
  49.        
  50.         return llm.generate(final_response_prompt)
  51.  
  52. # Usage
  53. print(tool_using_agent("What's the weather like in New York?"))
  54. print(tool_using_agent("What's the square root of 256?"))
  55.  
Advertisement
Add Comment
Please, Sign In to add comment