repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
ai-agent-book
chapter2/local_llm_serving/test_vllm_structured_streaming.py
.py
"""Focused tests for fragmented structured tool calls in VLLMToolAgent.chat_stream.""" from types import SimpleNamespace from unittest.mock import MagicMock from agent import VLLMToolAgent def _chunk(content=None, tool_calls=None): delta = SimpleNamespace(content=content, tool_calls=tool_calls or []) return...
103
3,714
ai-agent-book
chapter2/local_llm_serving/test_ollama_thinking.py
.py
#!/usr/bin/env python3 """Regression tests for Ollama thinking stream handling.""" import sys import types fake_ollama_module = types.ModuleType("ollama") setattr(fake_ollama_module, "Client", lambda: None) sys.modules.setdefault("ollama", fake_ollama_module) from ollama_native import OllamaNativeAgent class Fake...
48
1,456
ai-agent-book
chapter2/local_llm_serving/test_run_experiment.py
.py
import json from run_experiment import normalize_tool_call, parse_tool_calls, sha256_text def test_parse_multiple_raw_tool_calls(): raw = ( '<tool_call>\n{"name":"get_current_time","arguments":{"city":"Vancouver"}}\n</tool_call>' '<tool_call>\n{"name":"get_weather","arguments":{"city":"Vancouver"...
43
1,459
ai-agent-book
chapter2/local_llm_serving/ollama_native.py
.py
""" Ollama Native Tool Calling Implementation Uses Ollama's standard tool calling API (requires compatible models) """ import json import logging from concurrent.futures import ThreadPoolExecutor from typing import List, Dict, Any, Optional import ollama from tools import ToolRegistry logging.basicConfig(level=loggin...
629
25,790
ai-agent-book
chapter2/local_llm_serving/demo_streaming.py
.py
#!/usr/bin/env python3 """ Simple demo showing how to use streaming with the chat template agents """ import sys import time def print_with_typing_effect(text, delay=0.03): """Print text with a typing effect""" for char in text: print(char, end="", flush=True) time.sleep(delay) print() ...
215
6,986
ai-agent-book
chapter2/local_llm_serving/test_code_interpreter_full.py
.py
""" Test the full Python environment code interpreter with error handling """ import json from tools import ToolRegistry def test_successful_execution(): """Test that code executes successfully with full Python environment""" print("=" * 60) print("Test 1: Successful execution with full Python environment"...
185
6,352
ai-agent-book
chapter2/local_llm_serving/config.py
.py
""" Configuration for vLLM Tool Calling Demo """ import os from pathlib import Path from dotenv import load_dotenv # Load environment variables load_dotenv() # Model Configuration MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen3-0.6B") # Can use ModelScope path or HuggingFace MODEL_PATH = os.getenv("MODEL_PATH", Non...
42
1,170
ai-agent-book
chapter2/local_llm_serving/test_benchmark.py
.py
#!/usr/bin/env python3 """Regression tests for the local LLM serving benchmark.""" from types import SimpleNamespace from unittest.mock import patch from benchmark import stream_once class FakeCompletions: def __init__(self, chunks): self.chunks = chunks def create(self, **kwargs): return i...
54
1,486
ai-agent-book
chapter2/local_llm_serving/tools.py
.py
""" Sample tools for demonstrating vLLM tool calling functionality """ import json import math import random import io import contextlib from typing import Dict, Any, List from datetime import datetime import requests from io import BytesIO import PyPDF2 class ToolRegistry: """Registry for managing available tool...
503
19,571
ai-agent-book
chapter2/local_llm_serving/run_experiment.py
.py
#!/usr/bin/env python3 """Run the complete, real local-server campaign for Chapter 2 Experiment 2-1. Unlike an OpenAI-compatible client, this runner deliberately uses Ollama's ``/api/generate`` endpoint with ``raw=true``. The exact string emitted by the Qwen chat template is therefore visible in the evidence, includi...
448
16,801
ai-agent-book
chapter2/local_llm_serving/test_platform_detection.py
.py
"""Regression tests for platform-specific backend selection.""" import contextlib import io import sys import unittest from types import SimpleNamespace from unittest import mock from check_compatibility import provide_recommendations from main import ToolCallingAgent class BackendDetectionTests(unittest.TestCase):...
61
2,158
ai-agent-book
chapter2/local_llm_serving/agent.py
.py
""" vLLM Tool Calling Agent Implementation Demonstrates how to use vLLM with Qwen3 for tool calling """ import json import uuid import logging from concurrent.futures import ThreadPoolExecutor from typing import List, Dict, Any, Optional, Tuple from openai import OpenAI from tools import ToolRegistry from config impor...
592
24,906
ai-agent-book
chapter2/prompt-engineering/test_tau_bench_empty_results.py
.py
""" display_metrics must handle empty results list without raising ZeroDivisionError. """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent / "tau_bench")) from run import display_metrics def test_display_metrics_empty_results(): """Ensure display_metrics gracefully hand...
15
371
ai-agent-book
chapter2/prompt-engineering/test_ablation.py
.py
#!/usr/bin/env python3 """ Test script to demonstrate all ablation modes Runs a small subset of tasks with different ablation settings """ import subprocess import json import time from pathlib import Path from typing import Dict, List, Tuple import sys try: from dotenv import load_dotenv load_dotenv() except...
297
9,096
ai-agent-book
chapter2/prompt-engineering/ablation_utils.py
.py
""" Ablation utilities for prompt engineering experiments """ import random import re from enum import Enum from typing import List, Dict, Any, Optional import copy class ToneStyle(Enum): """Different tone styles for the agent""" DEFAULT = "default" TRUMP = "trump" CASUAL = "casual" # Tone style in...
164
5,399
ai-agent-book
chapter2/prompt-engineering/setup.py
.py
# Copyright Sierra from setuptools import find_packages, setup setup( name="tau_bench", version="0.1.0", description="The Tau-Bench package", long_description=open("README.md").read(), packages=find_packages(), include_package_data=True, install_requires=[ "openai>=1.13.3", ...
23
524
ai-agent-book
chapter2/prompt-engineering/run_ablation.py
.py
#!/usr/bin/env python3 """ Ablation Study Runner for Tau-Bench Framework Demonstrates the importance of prompt engineering by testing different variations: 1. Tone variations (Trump style, Casual style, Default style) 2. Wiki rule randomization 3. Tool description removal """ import argparse import copy import hashlib...
777
31,769
ai-agent-book
chapter2/prompt-engineering/run.py
.py
# Copyright Sierra import argparse try: from dotenv import load_dotenv load_dotenv() except ImportError: pass from tau_bench.types import RunConfig from tau_bench.run import run from litellm import provider_list from tau_bench.envs.user import UserStrategy def parse_args() -> RunConfig: parser = ar...
110
3,340
ai-agent-book
chapter2/prompt-engineering/test_user_empty_response.py
.py
from types import SimpleNamespace from tau_bench.envs import user as user_module from tau_bench.envs.user import LLMUserSimulationEnv from ablation_agent import completion_token_limit class Message: def __init__(self, content): self.content = content def model_dump(self): return {"role": "as...
57
2,021
ai-agent-book
chapter2/prompt-engineering/test_openrouter_direct.py
.py
#!/usr/bin/env python3 """ Direct test of OpenRouter API connection with openai/gpt-5 This helps isolate API connection issues from tau-bench logic """ import os import sys try: from dotenv import load_dotenv load_dotenv() except ImportError: pass from litellm import completion def test_openrouter(): ...
90
3,012
ai-agent-book
chapter2/prompt-engineering/analyze_results.py
.py
#!/usr/bin/env python3 """ Analyze and visualize ablation study results """ import argparse import json import glob import re from pathlib import Path from collections import defaultdict from typing import Dict, List, Tuple import sys def _extract_experiment_name(filename: str) -> str: """ Recover the ablati...
394
13,852
ai-agent-book
chapter2/prompt-engineering/test_hash_item_dict_collision.py
.py
import pytest from tau_bench.model_utils.api.cache import ( cache, cache_call_w_dedup, conditions, hash_item, ) class SameReprKey: """Hashable key whose representation intentionally carries no identity.""" def __init__(self, value): self.value = value def __hash__(self): ...
144
3,998
ai-agent-book
chapter2/prompt-engineering/ablation_agent.py
.py
""" Custom Agent for Ablation Study Extends ToolCallingAgent to support tone modifications """ import json import os import time import copy import traceback from datetime import datetime, timezone from litellm import completion from typing import List, Optional, Dict, Any from tau_bench.agents.base import Agent from...
396
17,318
ai-agent-book
chapter2/prompt-engineering/tau_bench/types.py
.py
# Copyright Sierra from pydantic import BaseModel from typing import List, Dict, Any, Optional, Union RESPOND_ACTION_NAME = "respond" RESPOND_ACTION_FIELD_NAME = "content" class Action(BaseModel): name: str kwargs: Dict[str, Any] class Task(BaseModel): user_id: str actions: List[Action] instru...
91
1,823
ai-agent-book
chapter2/prompt-engineering/tau_bench/run.py
.py
# Copyright Sierra import os import json import random import traceback from math import comb import multiprocessing from typing import List, Dict, Any from datetime import datetime from concurrent.futures import ThreadPoolExecutor from tau_bench.envs import get_env from tau_bench.agents.base import Agent from tau_be...
208
7,728
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/user.py
.py
# Copyright Sierra import abc import copy import enum import time from datetime import datetime, timezone from litellm import completion from typing import Optional, List, Dict, Any, Union class BaseUserSimulationEnv(abc.ABC): metadata = {} @abc.abstractmethod def reset(self, instruction: Optional[str]...
435
17,466
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/__init__.py
.py
# Copyright Sierra from typing import Optional, Union from tau_bench.envs.base import Env from tau_bench.envs.user import UserStrategy def get_env( env_name: str, user_strategy: Union[str, UserStrategy], user_model: str, task_split: str, user_provider: Optional[str] = None, task_index: Option...
41
1,176
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/tool.py
.py
import abc from typing import Any class Tool(abc.ABC): @staticmethod def invoke(*args, **kwargs): raise NotImplementedError @staticmethod def get_info() -> dict[str, Any]: raise NotImplementedError
13
233
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/base.py
.py
# Copyright Sierra import random from hashlib import sha256 from tau_bench.envs.tool import Tool from typing import Any, Callable, Dict, List, Type, Optional, Set, Union, Tuple from tau_bench.envs.user import load_user, UserStrategy from tau_bench.types import ( Action, Task, EnvInfo, EnvResetResponse...
167
5,756
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/wiki.py
.py
# Copyright Sierra import os FOLDER_PATH = os.path.dirname(__file__) with open(os.path.join(FOLDER_PATH, "wiki.md"), "r") as f: WIKI = f.read()
9
151
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tasks_test.py
.py
from tau_bench.types import Action, Task TASKS = [ Task( annotator="0", user_id="mia_li_3668", instruction="Your user id is mia_li_3668. You want to fly from New York to Seattle on May 20 (one way). You do not want to fly before 11am est. You want to fly in economy. You prefer direct flight...
1,211
67,250
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/rules.py
.py
# Copyright Sierra RULES = []
4
31
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/env.py
.py
# Copyright Sierra from tau_bench.envs.airline.data import load_data from tau_bench.envs.airline.rules import RULES from tau_bench.envs.airline.tools import ALL_TOOLS from tau_bench.envs.airline.wiki import WIKI from tau_bench.envs.base import Env from typing import Optional, Union from tau_bench.envs.user import User...
40
1,308
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tasks.py
.py
# Copyright Sierra tasks = [ { "annotator": 0, "user_id": "mia_li_3668", "instruction": "Your user id is mia_li_3668. You want to fly from New York to Seattle on May 20 (one way). You do not want to fly before 11am est. You want to fly in economy. You prefer direct flights but one stopover ...
1,457
72,697
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/search_onestop_flight.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class SearchOnestopFlight(Tool): @staticmethod def invoke(data: Dict[str, Any], origin: str, destination: str, date: str) -> str: flights = data["flights"] results = [] for flight1 in flig...
75
3,240
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/think.py
.py
# Copyright Sierra from typing import Any, Dict from tau_bench.envs.tool import Tool class Think(Tool): @staticmethod def invoke(data: Dict[str, Any], thought: str) -> str: return "" @staticmethod def get_info() -> Dict[str, Any]: return { "type": "function", ...
31
980
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/search_direct_flight.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class SearchDirectFlight(Tool): @staticmethod def invoke(data: Dict[str, Any], origin: str, destination: str, date: str) -> str: flights = data["flights"] results = [] for flight in flight...
51
2,014
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/send_certificate.py
.py
# Copyright Sierra from typing import Any, Dict from tau_bench.envs.tool import Tool class SendCertificate(Tool): @staticmethod def invoke( data: Dict[str, Any], user_id: str, amount: int, ) -> str: users = data["users"] if user_id not in users: return ...
53
1,765
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/update_reservation_flights.py
.py
# Copyright Sierra import json from copy import deepcopy from typing import Any, Dict, List from tau_bench.envs.tool import Tool class UpdateReservationFlights(Tool): @staticmethod def invoke( data: Dict[str, Any], reservation_id: str, cabin: str, flights: List[Dict[str, Any]]...
139
6,070
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/transfer_to_human_agents.py
.py
# Copyright Sierra from typing import Any, Dict from tau_bench.envs.tool import Tool class TransferToHumanAgents(Tool): @staticmethod def invoke( data: Dict[str, Any], summary: str, ) -> str: return "Transfer successful" @staticmethod def get_info() -> Dict[str, Any]: ...
36
1,144
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/__init__.py
.py
# Copyright Sierra from .book_reservation import BookReservation from .calculate import Calculate from .cancel_reservation import CancelReservation from .get_reservation_details import GetReservationDetails from .get_user_details import GetUserDetails from .list_all_airports import ListAllAirports from .search_direct_...
34
1,088
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/list_all_airports.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class ListAllAirports(Tool): @staticmethod def invoke(data: Dict[str, Any]) -> str: airports = [ "SFO", "JFK", "LAX", "ORD", "DFW", ...
71
1,633
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/calculate.py
.py
# Copyright Sierra from typing import Any, Dict from tau_bench.envs.tool import Tool class Calculate(Tool): @staticmethod def invoke(data: Dict[str, Any], expression: str) -> str: if not all(char in "0123456789+-*/(). " for char in expression): return "Error: invalid characters in express...
36
1,266
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/get_reservation_details.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class GetReservationDetails(Tool): @staticmethod def invoke(data: Dict[str, Any], reservation_id: str) -> str: reservations = data["reservations"] if reservation_id in reservations: re...
35
1,082
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/cancel_reservation.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class CancelReservation(Tool): @staticmethod def invoke( data: Dict[str, Any], reservation_id: str, ) -> str: reservations = data["reservations"] if reservation_id not in reser...
51
1,528
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/get_user_details.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class GetUserDetails(Tool): @staticmethod def invoke(data: Dict[str, Any], user_id: str) -> str: users = data["users"] if user_id in users: return json.dumps(users[user_id]) re...
35
1,028
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/update_reservation_baggages.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class UpdateReservationBaggages(Tool): @staticmethod def invoke( data: Dict[str, Any], reservation_id: str, total_baggages: int, nonfree_baggages: int, payment_id: str, ...
85
3,268
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/book_reservation.py
.py
# Copyright Sierra import json from copy import deepcopy from typing import Any, Dict, List from tau_bench.envs.tool import Tool class BookReservation(Tool): @staticmethod def invoke( data: Dict[str, Any], user_id: str, origin: str, destination: str, flight_type: str, ...
227
10,282
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/tools/update_reservation_passengers.py
.py
# Copyright Sierra import json from typing import Any, Dict, List from tau_bench.envs.tool import Tool class UpdateReservationPassengers(Tool): @staticmethod def invoke( data: Dict[str, Any], reservation_id: str, passengers: List[Dict[str, Any]], ) -> str: reservations = d...
65
2,712
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/airline/data/__init__.py
.py
# Copyright Sierra import json import os from typing import Any FOLDER_PATH = os.path.dirname(__file__) def load_data() -> dict[str, Any]: with open(os.path.join(FOLDER_PATH, "flights.json")) as f: flight_data = json.load(f) with open(os.path.join(FOLDER_PATH, "reservations.json")) as f: res...
22
564
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tasks_test.py
.py
from tau_bench.types import Task, Action TASKS_TEST = [ Task( annotator="0", user_id="yusuf_rossi_9620", instruction="You are Yusuf Rossi in 19122. You received your order #W2378156 and wish to exchange the mechanical keyboard for a similar one but with clicky switches and the smart thermos...
3,359
169,476
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/rules.py
.py
# Copyright Sierra RULES = [ "You are a customer service representative for an online retail company. You are chatting with a customer, and you can call tools or respond to the user.", "The agent should always first confirm the user id by email or name+zip before proceeding with any task.", "The agent shou...
12
970
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tasks_train.py
.py
from tau_bench.types import Task, Action TASKS_TRAIN = [ Task( annotator="synthetic", user_id="omar_anderson_3203", instruction="Your name is Omar Anderson and your zip code is 19031. You are logical, independent, relaxing, polite. Return #W6067464 via credit_card_4190576: Electric Kettle; ...
10,019
471,974
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tasks_dev.py
.py
from tau_bench.types import Task, Action TASKS_DEV = [ Task( annotator="", user_id="olivia_ito_3591", instruction="Your name is Olivia Ito and your zip code is 80218. You are outgoing, flexible, pessimistic, organized, logical. You've ordered an item (#W5442520) from this shop. You've reali...
354
19,326
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/env.py
.py
# Copyright Sierra from tau_bench.envs.base import Env from tau_bench.envs.retail.data import load_data from tau_bench.envs.retail.rules import RULES from tau_bench.envs.retail.tools import ALL_TOOLS from tau_bench.envs.retail.wiki import WIKI from typing import Optional, Union from tau_bench.envs.user import UserStra...
44
1,519
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tasks.py
.py
# Copyright Sierra tasks = [ { "annotator": 0, "user_id": "yusuf_rossi_9620", "instruction": "You are Yusuf Rossi in 19122. You received your order #W2378156 and wish to exchange the mechanical keyboard for a similar one but with clicky switches and the smart thermostat for one compatible w...
3,077
178,995
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/exchange_delivered_order_items.py
.py
# Copyright Sierra import json from typing import Any, Dict, List from tau_bench.envs.tool import Tool class ExchangeDeliveredOrderItems(Tool): @staticmethod def invoke( data: Dict[str, Any], order_id: str, item_ids: List[str], new_item_ids: List[str], payment_method_...
127
5,370
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/modify_pending_order_payment.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class ModifyPendingOrderPayment(Tool): @staticmethod def invoke( data: Dict[str, Any], order_id: str, payment_method_id: str, ) -> str: orders = data["orders"] # Check...
112
4,364
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/think.py
.py
# Copyright Sierra from typing import Any, Dict from tau_bench.envs.tool import Tool class Think(Tool): @staticmethod def invoke(data: Dict[str, Any], thought: str) -> str: # This method does not change the state of the data; it simply returns an empty string. return "" @staticmethod ...
35
1,160
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/return_delivered_order_items.py
.py
# Copyright Sierra import json from typing import Any, Dict, List from tau_bench.envs.tool import Tool class ReturnDeliveredOrderItems(Tool): @staticmethod def invoke( data: Dict[str, Any], order_id: str, item_ids: List[str], payment_method_id: str ) -> str: orders = data["orders"] ...
83
3,632
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/modify_pending_order_items.py
.py
# Copyright Sierra import json from typing import Any, Dict, List from tau_bench.envs.tool import Tool class ModifyPendingOrderItems(Tool): @staticmethod def invoke( data: Dict[str, Any], order_id: str, item_ids: List[str], new_item_ids: List[str], payment_method_id: s...
130
5,707
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/transfer_to_human_agents.py
.py
# Copyright Sierra from typing import Any, Dict from tau_bench.envs.tool import Tool class TransferToHumanAgents(Tool): @staticmethod def invoke(data: Dict[str, Any], summary: str) -> str: # This method simulates the transfer to a human agent. return "Transfer successful" @staticmethod ...
35
1,200
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/__init__.py
.py
# Copyright Sierra from .calculate import Calculate from .cancel_pending_order import CancelPendingOrder from .exchange_delivered_order_items import ExchangeDeliveredOrderItems from .find_user_id_by_email import FindUserIdByEmail from .find_user_id_by_name_zip import FindUserIdByNameZip from .get_order_details import ...
39
1,302
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/modify_pending_order_address.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class ModifyPendingOrderAddress(Tool): @staticmethod def invoke( data: Dict[str, Any], order_id: str, address1: str, address2: str, city: str, state: str, c...
90
3,212
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/list_all_product_types.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class ListAllProductTypes(Tool): @staticmethod def invoke(data: Dict[str, Any]) -> str: products = data["products"] product_dict = { product["name"]: product["product_id"] for product ...
32
1,035
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/get_product_details.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class GetProductDetails(Tool): @staticmethod def invoke(data: Dict[str, Any], product_id: str) -> str: products = data["products"] if product_id in products: return json.dumps(products...
35
1,104
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/find_user_id_by_email.py
.py
# Copyright Sierra from typing import Any, Dict from tau_bench.envs.tool import Tool class FindUserIdByEmail(Tool): @staticmethod def invoke(data: Dict[str, Any], email: str) -> str: users = data["users"] for user_id, profile in users.items(): if profile["email"].lower() == email....
35
1,132
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/calculate.py
.py
# Copyright Sierra from typing import Any, Dict from tau_bench.envs.tool import Tool class Calculate(Tool): @staticmethod def invoke(data: Dict[str, Any], expression: str) -> str: if not all(char in "0123456789+-*/(). " for char in expression): return "Error: invalid characters in express...
37
1,324
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/get_user_details.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class GetUserDetails(Tool): @staticmethod def invoke(data: Dict[str, Any], user_id: str) -> str: users = data["users"] if user_id in users: return json.dumps(users[user_id]) re...
35
1,021
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/get_order_details.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class GetOrderDetails(Tool): @staticmethod def invoke(data: Dict[str, Any], order_id: str) -> str: orders = data["orders"] if order_id in orders: return json.dumps(orders[order_id]) ...
35
1,087
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/modify_user_address.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class ModifyUserAddress(Tool): @staticmethod def invoke( data: Dict[str, Any], user_id: str, address1: str, address2: str, city: str, state: str, country: s...
85
2,920
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/find_user_id_by_name_zip.py
.py
# Copyright Sierra from typing import Any, Dict from tau_bench.envs.tool import Tool class FindUserIdByNameZip(Tool): @staticmethod def invoke(data: Dict[str, Any], first_name: str, last_name: str, zip: str) -> str: users = data["users"] for user_id, profile in users.items(): if (...
51
2,013
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/tools/cancel_pending_order.py
.py
# Copyright Sierra import json from typing import Any, Dict from tau_bench.envs.tool import Tool class CancelPendingOrder(Tool): @staticmethod def invoke(data: Dict[str, Any], order_id: str, reason: str) -> str: # check order exists and is pending orders = data["orders"] if order_id n...
79
3,320
ai-agent-book
chapter2/prompt-engineering/tau_bench/envs/retail/data/__init__.py
.py
# Copyright Sierra import json import os from typing import Any FOLDER_PATH = os.path.dirname(__file__) def load_data() -> dict[str, Any]: with open(os.path.join(FOLDER_PATH, "orders.json")) as f: order_data = json.load(f) with open(os.path.join(FOLDER_PATH, "products.json")) as f: product_d...
22
544
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/args.py
.py
import argparse from tau_bench.model_utils.model.model import Platform def api_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser() parser.add_argument("--model", type=str) parser.add_argument("--base-url", type=str) parser.add_argument("--platform", type=str, required=True, choice...
12
369
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/func_tools/filter.py
.py
from typing import Callable, Iterable, TypeVar from tau_bench.model_utils.func_tools.map import map T = TypeVar("T") builtin_filter = filter def filter( func: Callable[[T], bool], iterable: Iterable[T], max_concurrency: int | None = None, ) -> Iterable[T]: assert max_concurrency is None or max_conc...
18
457
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/func_tools/map.py
.py
from concurrent.futures import ThreadPoolExecutor from typing import Callable, Iterable, TypeVar T = TypeVar("T") U = TypeVar("U") def map( func: Callable[[T], U], iterable: Iterable[T], max_concurrency: int | None = None, use_tqdm: bool = False, ) -> Iterable[U]: assert max_concurrency is None o...
21
593
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/openai.py
.py
import os from tau_bench.model_utils.api.datapoint import Datapoint from tau_bench.model_utils.model.chat import ChatModel, Message from tau_bench.model_utils.model.completion import approx_cost_for_datapoint, approx_prompt_str from tau_bench.model_utils.model.general_model import wrap_temperature from tau_bench.model...
124
4,133
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/utils.py
.py
import enum import json import re from typing import Any, Optional, TypeVar from pydantic import BaseModel, Field from tau_bench.model_utils.api.types import PartialObj T = TypeVar("T", bound=BaseModel) class InputType(enum.Enum): CHAT = "chat" COMPLETION = "completion" def display_choices(choices: list[...
151
4,250
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/vllm_completion.py
.py
import os from typing import Any from pydantic import BaseModel from tau_bench.model_utils.api.datapoint import Datapoint from tau_bench.model_utils.model.completion import ( CompletionModel, approx_cost_for_datapoint, approx_prompt_str, ) from tau_bench.model_utils.model.utils import approx_num_tokens fr...
122
4,467
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/vllm_utils.py
.py
from typing import Any import requests from tau_bench.model_utils.model.general_model import wrap_temperature def generate_request( url: str, prompt: str, temperature: float = 0.0, force_json: bool = False, **req_body_kwargs: Any, ) -> str: args = { "prompt": prompt, "tempera...
37
980
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/vllm_chat.py
.py
from tau_bench.model_utils.api.datapoint import Datapoint from tau_bench.model_utils.model.chat import ChatModel, Message from tau_bench.model_utils.model.completion import approx_cost_for_datapoint, approx_prompt_str from tau_bench.model_utils.model.general_model import wrap_temperature from tau_bench.model_utils.mode...
130
4,759
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/outlines_completion.py
.py
from typing import Any from pydantic import BaseModel from tau_bench.model_utils.api.datapoint import Datapoint from tau_bench.model_utils.model.vllm_completion import VLLMCompletionModel from tau_bench.model_utils.model.vllm_utils import generate_request class OutlinesCompletionModel(VLLMCompletionModel): def ...
37
1,186
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/model.py
.py
import abc import enum from typing import Any, TypeVar from pydantic import BaseModel from tau_bench.model_utils.api.datapoint import ( BinaryClassifyDatapoint, ClassifyDatapoint, Datapoint, GenerateDatapoint, ParseDatapoint, ParseForceDatapoint, ScoreDatapoint, ) from tau_bench.model_util...
131
3,154
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/completion.py
.py
import abc import json from typing import Any, TypeVar from pydantic import BaseModel from tau_bench.model_utils.api.datapoint import ( BinaryClassifyDatapoint, ClassifyDatapoint, Datapoint, GenerateDatapoint, ParseDatapoint, ParseForceDatapoint, ScoreDatapoint, ) from tau_bench.model_util...
539
18,672
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/chat.py
.py
import abc import enum import json from typing import Any, TypeVar from pydantic import BaseModel from tau_bench.model_utils.api.datapoint import ( BinaryClassifyDatapoint, ClassifyDatapoint, Datapoint, GenerateDatapoint, ParseDatapoint, ParseForceDatapoint, ScoreDatapoint, ) from tau_benc...
609
21,999
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/exception.py
.py
from dataclasses import dataclass from typing import Generic, TypeVar T = TypeVar("T") class ModelError(Exception): def __init__( self, short_message: str, prompt: str | list[dict[str, str]] | None = None, response: str | None = None, ) -> None: super().__init__(short_...
24
522
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/mistral.py
.py
import os from tau_bench.model_utils.api.datapoint import Datapoint from tau_bench.model_utils.model.chat import ChatModel, Message from tau_bench.model_utils.model.completion import approx_cost_for_datapoint, approx_prompt_str from tau_bench.model_utils.model.general_model import wrap_temperature from tau_bench.model...
90
3,170
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/anyscale.py
.py
import os from tau_bench.model_utils.api.datapoint import Datapoint from tau_bench.model_utils.model.chat import ChatModel, Message from tau_bench.model_utils.model.completion import approx_cost_for_datapoint, approx_prompt_str from tau_bench.model_utils.model.general_model import wrap_temperature from tau_bench.model...
90
3,229
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/claude.py
.py
import json import os from tau_bench.model_utils.api.datapoint import Datapoint from tau_bench.model_utils.model.chat import ChatModel, Message from tau_bench.model_utils.model.completion import approx_cost_for_datapoint, approx_prompt_str from tau_bench.model_utils.model.general_model import wrap_temperature from tau...
139
5,102
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/model/general_model.py
.py
import abc from typing import Any, TypeVar from pydantic import BaseModel from tau_bench.model_utils.api.datapoint import ( BinaryClassifyDatapoint, ClassifyDatapoint, GenerateDatapoint, ParseDatapoint, ParseForceDatapoint, ScoreDatapoint, ) from tau_bench.model_utils.api.types import PartialO...
188
5,529
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/api/types.py
.py
from typing import Any PartialObj = dict[str, Any]
4
52
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/api/logging.py
.py
import functools import inspect import json from multiprocessing import Lock from typing import Any from pydantic import BaseModel from tau_bench.model_utils.api.sample import SamplingStrategy from tau_bench.model_utils.model.utils import optionalize_type log_files = {} def prep_for_json_serialization(obj: Any, fr...
75
2,692
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/api/_model_methods.py
.py
MODEL_METHODS = [ "classify", "binary_classify", "parse", "generate", "parse_force", "score", ]
9
120
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/api/exception.py
.py
import json import os import time from concurrent.futures import ThreadPoolExecutor from typing import Any, Callable, TypeVar from tau_bench.model_utils.model.exception import ModelError, Result T = TypeVar("T") _REPORT_DIR = os.path.expanduser("~/.llm-primitives/log") def set_report_dir(path: str) -> None: gl...
70
2,042
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/api/router.py
.py
import abc from pydantic import BaseModel from tau_bench.model_utils.api.datapoint import Datapoint, ScoreDatapoint from tau_bench.model_utils.model.model import Model class RequestRouter(abc.ABC): @abc.abstractmethod def route(self, dp: Datapoint, available_models: list[Model]) -> Model: raise NotI...
93
3,536
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/api/sample.py
.py
import abc import functools from multiprocessing import Lock from typing import Any, Callable, TypeVar from pydantic import BaseModel from tau_bench.model_utils.api.exception import APIError, execute_and_filter_model_errors from tau_bench.model_utils.model.exception import ModelError from tau_bench.model_utils import...
234
8,204
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/api/datapoint.py
.py
from __future__ import annotations import abc import json from typing import Any, Callable, TypeVar from pydantic import BaseModel import tau_bench.model_utils from tau_bench.model_utils.api._model_methods import MODEL_METHODS from tau_bench.model_utils.api.exception import APIError from tau_bench.model_utils.api.ty...
300
9,514
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/api/api.py
.py
from __future__ import annotations import argparse from typing import Any, TypeVar from pydantic import BaseModel from tau_bench.model_utils.api._model_methods import MODEL_METHODS from tau_bench.model_utils.api.cache import cache_call_w_dedup from tau_bench.model_utils.api.datapoint import ( BinaryClassifyDatap...
433
15,432
ai-agent-book
chapter2/prompt-engineering/tau_bench/model_utils/api/cache.py
.py
import functools import inspect import threading from collections import defaultdict from multiprocessing import Lock from typing import Any, Callable, TypeVar from pydantic import BaseModel T = TypeVar("T") class _CallableIdentity: __slots__ = ("func",) def __init__(self, func: Callable[..., Any]): ...
116
3,225