|
| 1 | +""" |
| 2 | +Demo: OpenAI-Compatible Tool Calling |
| 3 | +
|
| 4 | +Description: |
| 5 | +This demo shows the standard OpenAI function-calling flow against a |
| 6 | +Llama Stack server: define tools, let the model request a call, execute |
| 7 | +locally, and send results back. |
| 8 | +
|
| 9 | +Learning Objectives: |
| 10 | +- Define OpenAI-style function tools |
| 11 | +- Parse tool_calls from the model response |
| 12 | +- Execute a local function and return the result |
| 13 | +- Complete the full 3-step tool-calling loop |
| 14 | +""" |
| 15 | + |
| 16 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 17 | +# All rights reserved. |
| 18 | +# |
| 19 | +# This source code is licensed under the terms described in the LICENSE file in |
| 20 | +# the root directory of this source tree. |
| 21 | + |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | +import json |
| 25 | +import os |
| 26 | +import sys |
| 27 | + |
| 28 | +import fire |
| 29 | +from openai import OpenAI |
| 30 | +from termcolor import colored |
| 31 | + |
| 32 | +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) |
| 33 | +from shared.utils import resolve_openai_model |
| 34 | + |
| 35 | +try: |
| 36 | + from dotenv import load_dotenv |
| 37 | +except ImportError: # pragma: no cover - optional dependency |
| 38 | + load_dotenv = None |
| 39 | + |
| 40 | + |
| 41 | +def _maybe_load_dotenv() -> None: |
| 42 | + if load_dotenv is not None: |
| 43 | + load_dotenv() |
| 44 | + |
| 45 | + |
| 46 | +# -- Simulated local tool -------------------------------------------------- |
| 47 | + |
| 48 | +WEATHER_DATA = { |
| 49 | + "san francisco": {"temperature": "62°F", "condition": "Foggy"}, |
| 50 | + "new york": {"temperature": "45°F", "condition": "Cloudy"}, |
| 51 | + "london": {"temperature": "50°F", "condition": "Rainy"}, |
| 52 | +} |
| 53 | + |
| 54 | + |
| 55 | +def get_weather(location: str) -> str: |
| 56 | + """Return simulated weather for a given location.""" |
| 57 | + data = WEATHER_DATA.get(location.lower()) |
| 58 | + if data is None: |
| 59 | + return json.dumps({"error": f"No weather data for {location}"}) |
| 60 | + return json.dumps(data) |
| 61 | + |
| 62 | + |
| 63 | +TOOLS = [ |
| 64 | + { |
| 65 | + "type": "function", |
| 66 | + "function": { |
| 67 | + "name": "get_weather", |
| 68 | + "description": "Get the current weather for a location.", |
| 69 | + "parameters": { |
| 70 | + "type": "object", |
| 71 | + "properties": { |
| 72 | + "location": { |
| 73 | + "type": "string", |
| 74 | + "description": "City name, e.g. 'San Francisco'", |
| 75 | + }, |
| 76 | + }, |
| 77 | + "required": ["location"], |
| 78 | + }, |
| 79 | + }, |
| 80 | + }, |
| 81 | +] |
| 82 | + |
| 83 | +TOOL_MAP = { |
| 84 | + "get_weather": get_weather, |
| 85 | +} |
| 86 | + |
| 87 | + |
| 88 | +def main( |
| 89 | + host: str, |
| 90 | + port: int, |
| 91 | + model_id: str | None = None, |
| 92 | + prompt: str = "What is the weather like in San Francisco?", |
| 93 | + scheme: str = "http", |
| 94 | +) -> None: |
| 95 | + _maybe_load_dotenv() |
| 96 | + |
| 97 | + if scheme not in {"http", "https"}: |
| 98 | + raise ValueError("scheme must be 'http' or 'https'") |
| 99 | + if host not in {"localhost", "127.0.0.1", "::1"} and scheme != "https": |
| 100 | + print(colored("Warning: using HTTP for a non-local host. Consider --scheme https.", "yellow")) |
| 101 | + |
| 102 | + client = OpenAI( |
| 103 | + base_url=f"{scheme}://{host}:{port}/v1", |
| 104 | + api_key=os.getenv("LLAMA_STACK_API_KEY", "fake"), |
| 105 | + ) |
| 106 | + |
| 107 | + resolved_model = resolve_openai_model(client, model_id) |
| 108 | + if resolved_model is None: |
| 109 | + return |
| 110 | + print(f"Using model: {resolved_model}") |
| 111 | + |
| 112 | + # Step 1 — send the user message with tool definitions |
| 113 | + messages = [{"role": "user", "content": prompt}] |
| 114 | + print(colored(f"User> {prompt}", "blue")) |
| 115 | + |
| 116 | + response = client.chat.completions.create( |
| 117 | + model=resolved_model, |
| 118 | + messages=messages, |
| 119 | + tools=TOOLS, |
| 120 | + tool_choice="auto", |
| 121 | + ) |
| 122 | + |
| 123 | + assistant_message = response.choices[0].message |
| 124 | + |
| 125 | + # If the model replies directly without calling a tool, print and exit. |
| 126 | + if not assistant_message.tool_calls: |
| 127 | + print(colored(f"Assistant> {assistant_message.content}", "green")) |
| 128 | + return |
| 129 | + |
| 130 | + # Step 2 — execute each requested tool call locally |
| 131 | + messages.append(assistant_message) |
| 132 | + for tool_call in assistant_message.tool_calls: |
| 133 | + fn_name = tool_call.function.name |
| 134 | + try: |
| 135 | + fn_args = json.loads(tool_call.function.arguments or "{}") |
| 136 | + if not isinstance(fn_args, dict): |
| 137 | + raise ValueError("arguments must be a JSON object") |
| 138 | + except (json.JSONDecodeError, ValueError) as exc: |
| 139 | + result = json.dumps({"error": f"Invalid arguments for {fn_name}: {exc}"}) |
| 140 | + print(colored(f"Tool result: {result}", "yellow")) |
| 141 | + messages.append( |
| 142 | + {"role": "tool", "tool_call_id": tool_call.id, "content": result} |
| 143 | + ) |
| 144 | + continue |
| 145 | + print(colored(f"Tool call: {fn_name}({fn_args})", "yellow")) |
| 146 | + |
| 147 | + fn = TOOL_MAP.get(fn_name) |
| 148 | + if fn is None: |
| 149 | + result = json.dumps({"error": f"Unknown function: {fn_name}"}) |
| 150 | + else: |
| 151 | + try: |
| 152 | + result = fn(**fn_args) |
| 153 | + except TypeError as exc: |
| 154 | + result = json.dumps({"error": f"Invalid parameters for {fn_name}: {exc}"}) |
| 155 | + print(colored(f"Tool result: {result}", "yellow")) |
| 156 | + |
| 157 | + messages.append( |
| 158 | + { |
| 159 | + "role": "tool", |
| 160 | + "tool_call_id": tool_call.id, |
| 161 | + "content": result, |
| 162 | + } |
| 163 | + ) |
| 164 | + |
| 165 | + # Step 3 — send tool results back and get the final answer |
| 166 | + final = client.chat.completions.create( |
| 167 | + model=resolved_model, |
| 168 | + messages=messages, |
| 169 | + tools=TOOLS, |
| 170 | + ) |
| 171 | + print(colored(f"Assistant> {final.choices[0].message.content}", "green")) |
| 172 | + |
| 173 | + |
| 174 | +if __name__ == "__main__": |
| 175 | + fire.Fire(main) |
0 commit comments