页面简介
Turns natural-language trading requests into calls to ordinary typed functions by mapping function names and closed-set arguments to confidence-aware System One questions.
正文摘录
When you order a “large iced oat latte, no sweetener,” the barista does not write your sentence down. They mark four options on a cup. This cookbook does the same thing for a trading API: a sentence goes in, and out comes a function name and its arguments as evaluated enums, each with a confidence. "plot rolling correlation between nvda and spy for the past month" rolling_correlation(symbol='NVDA', benchmark='SPY', window='1mo') confidence 0.93 "compare nvda amd and msft over the past three months" compare_returns(symbols=['NVDA', 'AMD', 'MSFT'], window='3mo') confidence 0.93 "show me apple daily with volume" plot_price(symbol='AAPL', resolution='1d', include_volume=True) confidence 0.69 "what tickers do you have" list_symbols() confidence 1.00 Those calls go to ten ordinary functions in a trading assistant. Their arguments take values from fixed lists, so they are Literals already: Sketchdef plot_price( symbol: Literal["SPY", "NVDA", "AMD", "AAPL", "MSFT", "TSLA"], style: Literal["line", "candles"] = "line", resolution: Literal["1m", "5m", "15m", "1h", "1d"] = "15m", window: Literal["1d", "1w", "1mo", "3mo"] = "1w", include_volume: bool = False, moving_average: Literal["9", "20", "50"] | None = None, log_scale: bool = False, ): ... An argument whose values come from a fixed list is a closed set. When it takes one value out of that list, it gets a Choice question over exactly those values, so whatever reaches the function is a value the function accepts. You leave the functions alone. What you add is a spec that says in plain words what each argument means. By the end you have a Dispatcher you can point at your own functions. Setup Run in ColabRuns as published without an API key.Python fileThis page as one .py file, to run locally.Open in playgroundEdit one request and run it live. Needs a TypeSafe account. To run it on your own machine instead: pip install ipython polars matplotlib numpy 'cooksafe>=0.3.0,<0.4.0' With uv, uv run function_calling.py installs the dependencies for you. The code replays saved answers, so it runs as published without an API key. To change a request, set TYPESAFE_API_KEY; in Colab, add it in the Secrets panel. The code below downloads trader.py, which holds the ten functions, with spec.json and the price bars, from typesafe-public-examples unless they are already on disk. The code that reads a signature and a spec and makes the call is all on this page. The prices are simulated from a fixed random seed, not real market data. The tickers are real, but every price, return and chart below is generated. import json import os import urllib.request from dataclasses import dataclass, field from math import prod from pathlib import Path from types import UnionType from typing import Any, Callable, Literal, Mapping, Union, get_args, get_origin, get_type_hints import matplotlib.pyplot as plt from cooksafe import JsonCache, make_playground_link from IPython.display import Markdown, display from typesafe_sdk import SystemOneResponse, TypeSafeClient EXAMPLES = ( "https://raw.githubusercontent.com/typesafe-ai/typesafe-public-examples/pub-20261126-cfe720/" "cookbooks/function_calling" ) for name in ["trader.py", "spec.json", "bars.parquet"]: if not Path(name).exists(): urllib.request.urlretrieve(f"{EXAMPLES}/{name}", name) from trader import TOOLS, chart_theme, load # noqa: E402 (downloaded above) def show(draw) -> None: """Display the chart ``draw()`` makes. The docs build sets COOKSAFE_RENDER and also gets a dark copy.""" for theme in ("light", "dark") if os.environ.get("COOKSAFE_RENDER") else ("light",): with chart_theme(theme): figure = draw() display(figure, metadata={"theme": theme}) plt.close(figure) print(f"{len(TOOLS)} functions over {load().height:,} one-minute bars") See all 36 lines 10 functions over 156,780 one-minute bars TYPESAFE_MODEL = "jev-1.14.0" # the page's model; "jev-latest" runs the newest, live # The keys this cookbook uses. In Colab, keys saved in the Secrets panel are copied in here. KEYS = ["TYPESAFE_API_KEY"] try: from google.colab import userdata except ImportError: # not in Colab userdata = None for key in KEYS: if userdata is not None and key not in os.environ: try: os.environ[key] = userdata.get(key) except (userdata.SecretNotFoundError, userdata.NotebookAccessError): pass # not saved, or this notebook may not read it typesafe = TypeSafeClient( api_key=os.environ.get("TYPESAFE_API_KEY", "cache-only"), # keyless runs replay the cache base_url=os.environ.get("TYPESAFE_ENDPOINT"), timeout=120.0, ) CACHE = Path("function_calling_cache.json") # True fills CACHE with the published answers, so the run makes no requests. To run # live, set it to False and delete CACHE; a CACHE already on disk is never overwritten. DOWNLOAD_CACHE = True if DOWNLOAD_CACHE and not CACHE.exists(): urllib.request.urlretrieve(f"{EXAMPLES}/{CACHE.name}", CACHE) json_cache = JsonCache(CACHE) @json_cache def _system_one(state: str, questions: str, model: str) -> dict: response = typesafe.system_one(state=state, questions=json.loads(questions), model=model) return { "answers": {k: a.model_dump(mode="json") for k, a in response.answers.items()}, "usage": response.usage.model_dump(mode="json"), } class Client: """The `system_one` the dispatcher calls, with every answer cached in CACHE.""" def system_one(self, state, questions: dict, model: str) -> SystemOneResponse: raw = _system_one(str(state), json.dumps(questions, sort_keys=True), model=model) return SystemOneResponse.model_validate({**raw, "model": model}) client = Client() See all 47 lines Find the closed sets in the signatures The type hints already say which arguments come from a fixed list, and what is in each list. closed_sets reads a signature and sorts those arguments into three shapes: a choice (a Literal, so one value out of the list), a set (a list[Literal[...]], so any number of them), or a flag (a bool, so on or off). All ten functions are defined in trader.py. def _bare(hint: Any) -> Any: """Strip ``Annotated[...]`` and ``| None`` down to the underlying type.""" if hasattr(hint, "__metadata__"): hint = get_args(hint)[0] if get_origin(hint) in (Union, UnionType): named = [a for a in get_args(hint) if a is not type(None)] if len(named) == 1: return named[0] return hint def _members(hint: Any) -> tuple[str, ...] | None: hint = _bare(hint) return get_args(hint) if get_origin(hint) is Literal else None def closed_sets(fn: Callable) -> dict[str, tuple[str, tuple[str, ...] | None]]: """Every argument that can be filled from a fixed set: ``name -> (shape, members)``.""" found = {} for name, hint in get_type_hints(fn).items(): if name == "return": continue members, bare = _members(hint), _bare(hint) if members is not None: found[name] = ("choice", members) elif get_origin(bare) is list and _members(get_args(bare)[0]) is not None: found[name] = ("set", _members(get_args(bare)[0])) elif bare is bool: found[name] = ("flag", None) return found for name, fn in TOOLS.items(): shapes = closed_sets(fn) print( f" {name:<20}{len(shapes)} " + ", ".join(f"{a}:{s}" for a, (s, _) in shapes.items()) ) print( f"\n{sum(len(closed_sets(fn)) for fn in TOOLS.values())} fillable arguments in total" ) See all 41 lines list_symbols 0 market_summary 1 window:choice plot_price 7 symbol:choice, style:choice, resolution:choice, window:choice, include_volume:flag, moving_average:choice, log_scale:flag intraday_pattern 3 symbol:choice, window:choice, metric:choice compare_returns 3 symbols:set, window:choice, normalize:flag rolling_correlation 4 symbol:choice, benchmark:choice, window:choice, resolution:choice summary_stats 2 symbol:choice, window:choice volatility 3 symbol:choice, window:choice, annualized:flag top_movers 2 window:choice, direction:choice drawdown 3 symbol:choice, window:choice, plot:flag 28 fillable arguments in total top_movers shows what gets left out. Of its three arguments, two are closed sets. The third, limit, is an int, so it never gets a question and keeps its default of 3. Free text, numbers and dates work the same way: no question, and the function’s default stands. Write the spec The Literal gives you the strings "1mo" and "3mo". It does not say that a user typing “this quarter” means the second one. The spec says that. It holds a question per argument, a line per option, a description per function, and one more question that picks between the functions. It lives in spec.json, and an LLM can write it for you from the signatures. SPEC = json.loads(Path("spec.json").read_text()) for argument in ("style", "moving_average"): print( json.dumps( {argument: SPEC["functions"]["plot_price"]["arguments"][argument]}, indent=2 ) ) { "style": { "question": "Does the user want a plain line or candles?", "stated": "Does the user say how the chart should be drawn, such as a line, candles, or OHLC bars?", "options": { "line": "a simple line through the closing prices", "candles": "a candlestick or OHLC chart, showing each bar's open, high, low and close" } } } { "moving_average": { "question": "How many bars should the moving average cover - nine, twenty, or fifty?", "stated": "Does the user ask for a moving average or a smoothed line over the candles?", "options": { "9": "a nine-bar moving average, a fast one", "20": "a twenty-bar moving average", "50": "a fifty-bar moving average, a slow one" } } } The option keys are the strings the function takes, so nothing has to map a label back to an argument afterwards. stated makes an argument optional. It is a second yes/no question asking whether the command says anything about that argument at all. When the answer is no, the call leaves that argument out and the function’s own default applies. A set argument gets its question once per member, with {} standing in for the member name. "Does the user want {} in the comparison?" becomes one question per ticker. Write each question about the idea rather than the words a user might pick, because the match is on meaning: “is amd tracking nvidia lately” reaches rolling