AightBits

Simple LLM Function Calling Example

Mar 24th, 2025
648
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.25 KB | Source Code | 0 0
  1. import requests
  2. import json
  3. from duckduckgo_search import DDGS
  4.  
  5. # === Config ===
  6. API_URL = "http://localhost:5000/v1/chat/completions"
  7. API_KEY = ""
  8. MODEL_NAME = ""
  9. SYSTEM_PROMPT = (
  10.     "You are an assistant that can perform function calls using search_duckduckgo({ \"query\": \"...\" }). "
  11.     "Only use the function when the user asks for recent, location-specific, or online information. "
  12.     "After the function is called, and relevant information is returned, continue the conversation using it.\n\n"
  13.     "Examples:\n"
  14.     "User: Who won the Oscar for Best Picture this year?\n"
  15.     "Assistant: search_duckduckgo({ \"query\": \"2025 Best Picture Oscar winner\" })\n"
  16.     "Assistant: The winner of Best Picture at the 2025 Oscars was The Midnight Star.\n\n"
  17.     "User: What's the weather like in New York City?\n"
  18.     "Assistant: search_duckduckgo({ \"query\": \"current weather in New York City\" })\n"
  19.     "Assistant: It's currently 52°F and mostly cloudy in NYC, with winds around 10 mph.\n\n"
  20.     "User: How do I reverse a string in Python?\n"
  21.     "Assistant: You can reverse a string by using slicing: my_string[::-1]\n\n"
  22.     "Begin."
  23. )
  24.  
  25. # === Search Function ===
  26. def duckduckgo_search(query, num_results=3):
  27.     try:
  28.         ddgs = DDGS()
  29.         results = ddgs.text(query, max_results=num_results)
  30.         return [
  31.             {
  32.                 "title": r.get("title", "No title"),
  33.                 "link": r.get("href", "No link"),
  34.                 "snippet": r.get("body", "No snippet")
  35.             }
  36.             for r in results
  37.         ]
  38.     except Exception:
  39.         return []
  40.  
  41. # === LLM Call ===
  42. def call_llm(messages):
  43.     headers = {"Content-Type": "application/json"}
  44.     if API_KEY:
  45.         headers["Authorization"] = f"Bearer {API_KEY}"  # Optional for local models
  46.  
  47.     payload = {
  48.         "model": MODEL_NAME,
  49.         "messages": messages,
  50.         "temperature": 0.7,
  51.         "max_tokens": 1000
  52.     }
  53.  
  54.     response = requests.post(API_URL, headers=headers, json=payload)
  55.     return response.json() if response.status_code == 200 else None
  56.  
  57. # === Extract Function Call ===
  58. def extract_function_call(content):
  59.     if "search_duckduckgo" in content:
  60.         try:
  61.             start = content.find('{')
  62.             end = content.find('}', start)
  63.             if start != -1 and end != -1:
  64.                 return json.loads(content[start:end+1])
  65.         except Exception:
  66.             pass
  67.     return None
  68.  
  69. # === Main Loop ===
  70. def main():
  71.     history = [{"role": "system", "content": SYSTEM_PROMPT}]
  72.  
  73.     while True:
  74.         user_input = input("\nUser: ")
  75.         if user_input.lower() in {"exit", "quit"}:
  76.             break
  77.  
  78.         history.append({"role": "user", "content": user_input})
  79.         response = call_llm(history)
  80.         if not response:
  81.             continue
  82.  
  83.         message = response["choices"][0]["message"]
  84.         content = message.get("content", "")
  85.         function_args = extract_function_call(content)
  86.  
  87.         if function_args:
  88.             query = function_args.get("query", "")
  89.             results = duckduckgo_search(query)
  90.  
  91.             # Format result text for assistant use
  92.             result_text = "\n\n".join(
  93.                 f"{r['snippet']} ({r['title']}, {r['link']})" for r in results
  94.             )
  95.  
  96.             # Prepare list of sources for final output
  97.             source_links = [f"{r['title']}: {r['link']}" for r in results]
  98.  
  99.             # Inject function call and results as assistant content
  100.             history.append({"role": "assistant", "content": content})
  101.             history.append({"role": "assistant", "content": result_text})
  102.  
  103.             # Request continuation with new knowledge
  104.             followup = call_llm(history)
  105.             if followup:
  106.                 final_message = followup["choices"][0]["message"]["content"]
  107.  
  108.                 # Append sources at the end
  109.                 if source_links:
  110.                     final_message += "\n\nSources:\n" + "\n".join(source_links)
  111.  
  112.                 print(f"\n{final_message}\n")
  113.                 history.append({"role": "assistant", "content": final_message})
  114.         else:
  115.             print(f"\n{content}\n")
  116.             history.append({"role": "assistant", "content": content})
  117.  
  118. if __name__ == "__main__":
  119.     main()
Tags: ai llm
Advertisement
Add Comment
Please, Sign In to add comment