-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbasic_usage.py
More file actions
88 lines (66 loc) · 2.56 KB
/
basic_usage.py
File metadata and controls
88 lines (66 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""
Basic usage example for function-schema library.
This example demonstrates how to:
1. Define a function with type annotations and Doc metadata
2. Generate a JSON schema from the function
3. Use enum for parameter constraints
"""
from typing import Annotated, Optional, Literal
from function_schema import Doc, get_function_schema
import enum
import json
def get_weather(
city: Annotated[str, Doc("The city to get the weather for")],
unit: Annotated[
Optional[str],
Doc("The unit to return the temperature in"),
enum.Enum("Unit", "celcius fahrenheit")
] = "celcius",
) -> str:
"""Returns the weather for the given city."""
return f"Weather for {city} is 20°C"
def get_animal_with_enum(
animal: Annotated[str, Doc("The animal to get"),
enum.Enum("AnimalType", "dog cat")],
) -> str:
"""Returns the animal using enum."""
return f"Animal is {animal}"
class AnimalType(enum.Enum):
dog = enum.auto()
cat = enum.auto()
def get_animal_with_class_enum(
animal: Annotated[str, Doc("The animal to get"), AnimalType],
) -> str:
"""Returns the animal using class-based enum."""
return f"Animal is {animal.value}"
def get_animal_with_literal(
animal: Annotated[Literal["dog", "cat"], Doc("The animal to get")],
) -> str:
"""Returns the animal using Literal type."""
return f"Animal is {animal}"
def get_weather_with_string_annotation(
city: Annotated[str, "The city to get the weather for"],
unit: Annotated[Optional[str], "The unit to return the temperature in"] = "celcius",
) -> str:
"""Returns the weather for the given city using plain string annotations."""
return f"Weather for {city} is 20°C"
if __name__ == "__main__":
# Generate schema for the main weather function
schema = get_function_schema(get_weather)
print("Basic weather function schema:")
print(json.dumps(schema, indent=2))
print("\n" + "="*50 + "\n")
# Generate schema for Claude format
claude_schema = get_function_schema(get_weather, "claude")
print("Schema for Claude:")
print(json.dumps(claude_schema, indent=2))
print("\n" + "="*50 + "\n")
# Generate schema for enum example
enum_schema = get_function_schema(get_animal_with_enum)
print("Animal enum schema:")
print(json.dumps(enum_schema, indent=2))
print("\n" + "="*50 + "\n")
# Generate schema for Literal example
literal_schema = get_function_schema(get_animal_with_literal)
print("Animal literal schema:")
print(json.dumps(literal_schema, indent=2))