Skip to content

Commit a32fbc7

Browse files
Copilotcomfuture
andcommitted
Separate examples from README and add OpenAI, Claude, MCP examples
Co-authored-by: comfuture <151300+comfuture@users.noreply.github.com>
1 parent 1a01fec commit a32fbc7

File tree

8 files changed

+944
-164
lines changed

8 files changed

+944
-164
lines changed

README.md

Lines changed: 32 additions & 164 deletions
Original file line numberDiff line numberDiff line change
@@ -18,186 +18,54 @@ pip install function-schema
1818

1919
## Usage
2020

21-
```python
22-
from typing import Annotated, Optional
23-
from function_schema import Doc
24-
import enum
25-
26-
def get_weather(
27-
city: Annotated[str, Doc("The city to get the weather for")],
28-
unit: Annotated[
29-
Optional[str],
30-
Doc("The unit to return the temperature in"),
31-
enum.Enum("Unit", "celcius fahrenheit")
32-
] = "celcius",
33-
) -> str:
34-
"""Returns the weather for the given city."""
35-
return f"Weather for {city} is 20°C"
36-
```
37-
38-
Function description is taken from the docstring.
39-
Type hinting with `typing.Annotated` for annotate additional information about the parameters and return type.
40-
41-
Then you can generate a schema for this function:
42-
```python
43-
import json
44-
from function_schema import get_function_schema
45-
46-
schema = get_function_schema(get_weather)
47-
print(json.dumps(schema, indent=2))
48-
```
49-
50-
Will output:
51-
52-
```json
53-
{
54-
"name": "get_weather",
55-
"description": "Returns the weather for the given city.",
56-
"parameters": {
57-
"type": "object",
58-
"properties": {
59-
"city": {
60-
"type": "string",
61-
"description": "The city to get the weather for"
62-
},
63-
"unit": {
64-
"type": "string",
65-
"description": "The unit to return the temperature in",
66-
"enum": [
67-
"celcius",
68-
"fahrenheit"
69-
],
70-
"default": "celcius"
71-
}
72-
},
73-
}
74-
"required": [
75-
"city"
76-
]
77-
}
78-
```
79-
80-
for claude, you should pass 2nd argument as SchemaFormat.claude or `claude`:
81-
82-
```python
83-
from function_schema import get_function_schema
84-
85-
schema = get_function_schema(get_weather, "claude")
86-
```
87-
88-
Please refer to the [Claude tool use](https://docs.anthropic.com/claude/docs/tool-use) documentation for more information.
21+
See the [examples directory](./examples/) for comprehensive usage examples with different AI platforms:
8922

90-
You can use any type hinting supported by python for the first argument of `Annotated`. including:
91-
`typing.Literal`, `typing.Optional`, `typing.Union`, and `T | None` for python 3.10+.
92-
`Doc` class or plain string in `Annotated` is used for describe the parameter.
93-
`Doc` metadata is the [PEP propose](https://peps.python.org/pep-0727/) for standardizing the metadata in type hints.
94-
currently, implemented in `typing-extensions` module. Also `function_schema.Doc` is provided for compatibility.
23+
- **[Basic Usage](./examples/basic_usage.py)** - Core features and function definition patterns
24+
- **[OpenAI Integration](./examples/openai_example.py)** - Assistant API and Chat Completion examples
25+
- **[Claude Integration](./examples/claude_example.py)** - Anthropic Claude tool calling examples
26+
- **[MCP Integration](./examples/mcp_example.py)** - Model Context Protocol examples
27+
- **[CLI Usage](./examples/cli_example.py)** - Command-line interface examples
9528

96-
Enumeratable candidates can be defined with `enum.Enum` in the argument of `Annotated`.
29+
### Quick Start
9730

9831
```python
99-
import enum
32+
from typing import Annotated
33+
from function_schema import Doc, get_function_schema
10034

101-
class AnimalType(enum.Enum):
102-
dog = enum.auto()
103-
cat = enum.auto()
104-
105-
def get_animal(
106-
animal: Annotated[str, Doc("The animal to get"), AnimalType],
107-
) -> str:
108-
"""Returns the animal."""
109-
return f"Animal is {animal.value}"
110-
```
111-
In this example, each name of `AnimalType` enums(`dog`, `cat`) is used as an enum schema.
112-
In shorthand, you can use `typing.Literal` as the type will do the same thing.
113-
114-
```python
115-
def get_animal(
116-
animal: Annotated[Literal["dog", "cat"], Doc("The animal to get")],
117-
) -> str:
118-
"""Returns the animal."""
119-
return f"Animal is {animal}"
120-
```
121-
122-
123-
### Plain String in Annotated
124-
125-
The string value of `Annotated` is used as a description for convenience.
126-
127-
```python
128-
def get_weather(
129-
city: Annotated[str, "The city to get the weather for"], # <- string value of Annotated is used as a description
130-
unit: Annotated[Optional[str], "The unit to return the temperature in"] = "celcius",
131-
) -> str:
35+
def get_weather(city: Annotated[str, Doc("The city to get the weather for")]) -> str:
13236
"""Returns the weather for the given city."""
13337
return f"Weather for {city} is 20°C"
38+
39+
# Generate schema
40+
schema = get_function_schema(get_weather)
13441
```
13542

136-
But this would create a predefined meaning for any plain string inside of `Annotated`,
137-
and any tool that was using plain strings in them for any other purpose, which is currently allowed, would now be invalid.
138-
Please refer to the [PEP 0727, Plain String in Annotated](https://peps.python.org/pep-0727/#plain-string-in-annotated) for more information.
43+
### Key Features
13944

140-
### Usage with OpenAI API
45+
- **Type Annotations**: Use `typing.Annotated` with `Doc` metadata for parameter descriptions
46+
- **Multiple Formats**: Support for OpenAI (`"openai"`) and Claude (`"claude"`) schema formats
47+
- **Enum Support**: Use `enum.Enum` or `typing.Literal` for parameter constraints
48+
- **CLI Tool**: Generate schemas from command line using `function_schema`
14149

142-
You can use this schema to make a function call in OpenAI API:
143-
```python
144-
import openai
145-
openai.api_key = "sk-..."
146-
147-
# Create an assistant with the function
148-
assistant = client.beta.assistants.create(
149-
instructions="You are a weather bot. Use the provided functions to answer questions.",
150-
model="gpt-4-turbo-preview",
151-
tools=[{
152-
"type": "function",
153-
"function": get_function_schema(get_weather),
154-
}]
155-
)
156-
157-
run = client.beta.messages.create(
158-
assistant_id=assistant.id,
159-
messages=[
160-
{"role": "user", "content": "What's the weather like in Seoul?"}
161-
]
162-
)
163-
164-
# or with chat completion
165-
166-
result = openai.chat.completion.create(
167-
model="gpt-3.5-turbo",
168-
messages=[
169-
{"role": "user", "content": "What's the weather like in Seoul?"}
170-
],
171-
tools=[{
172-
"type": "function",
173-
"function": get_function_schema(get_weather)
174-
}],
175-
tool_call="auto",
176-
)
177-
```
50+
For detailed examples and advanced usage patterns, see the [examples directory](./examples/).
17851

179-
### Usage with Anthropic Claude
52+
### Platform Integration
18053

181-
```python
182-
import anthropic
183-
184-
client = anthropic.Client()
185-
186-
response = client.beta.tools.messages.create(
187-
model="claude-3-opus-20240229",
188-
max_tokens=4096,
189-
tools=[get_function_schema(get_weather, "claude")],
190-
messages=[
191-
{"role": "user", "content": "What's the weather like in Seoul?"}
192-
]
193-
)
194-
```
54+
#### OpenAI API
55+
For detailed OpenAI integration examples including Assistant API and Chat Completion, see [examples/openai_example.py](./examples/openai_example.py).
19556

196-
### CLI usage
57+
#### Anthropic Claude
58+
For Claude tool calling examples and multi-turn conversations, see [examples/claude_example.py](./examples/claude_example.py).
19759

198-
```sh
199-
function_schema mymodule.py my_function | jq
60+
#### Model Context Protocol (MCP)
61+
For MCP server and tool integration examples, see [examples/mcp_example.py](./examples/mcp_example.py).
62+
63+
#### CLI Usage
64+
Generate schemas from command line:
65+
```bash
66+
function_schema examples/cli_example.py get_weather | jq
20067
```
68+
For more CLI examples, see [examples/cli_example.py](./examples/cli_example.py).
20169

20270
## License
20371
MIT License

examples/README.md

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# Function Schema Examples
2+
3+
This directory contains practical examples of how to use the `function-schema` library with various AI platforms and protocols.
4+
5+
## Examples
6+
7+
### 🔧 Basic Usage (`basic_usage.py`)
8+
Demonstrates the fundamental features of function-schema:
9+
- Creating functions with type annotations and Doc metadata
10+
- Generating JSON schemas
11+
- Using enums and Literal types for parameter constraints
12+
- Different annotation styles
13+
14+
**Run:** `python examples/basic_usage.py`
15+
16+
### 🤖 OpenAI Integration (`openai_example.py`)
17+
Shows how to integrate with OpenAI's APIs:
18+
- Assistant API with tool calling
19+
- Chat Completion API with function calling
20+
- Multiple tool definitions
21+
22+
**Run:** `python examples/openai_example.py`
23+
24+
### 🧠 Claude Integration (`claude_example.py`)
25+
Demonstrates Anthropic Claude tool calling:
26+
- Basic tool calling setup
27+
- Multi-turn conversations with tools
28+
- Claude-specific schema format
29+
30+
**Run:** `python examples/claude_example.py`
31+
32+
### 📟 CLI Usage (`cli_example.py`)
33+
Examples of using the command-line interface:
34+
- Generating schemas from Python files
35+
- Different output formats
36+
- Working with multiple functions
37+
38+
**Test the CLI:**
39+
```bash
40+
# Install the package first
41+
pip install -e .
42+
43+
# Generate schema for a function
44+
function_schema examples/cli_example.py get_weather
45+
46+
# Generate with pretty JSON formatting
47+
function_schema examples/cli_example.py get_weather | jq
48+
49+
# Generate for Claude format
50+
function_schema examples/cli_example.py get_weather claude
51+
```
52+
53+
### 🔌 MCP Integration (`mcp_example.py`)
54+
Shows integration with Model Context Protocol:
55+
- Creating MCP-compatible tool definitions
56+
- Server manifest generation
57+
- Tool calling examples
58+
- Resource access patterns
59+
60+
**Run:** `python examples/mcp_example.py`
61+
62+
## Running the Examples
63+
64+
1. **Install the package:**
65+
```bash
66+
pip install -e .
67+
```
68+
69+
2. **Run any example:**
70+
```bash
71+
python examples/basic_usage.py
72+
python examples/openai_example.py
73+
python examples/claude_example.py
74+
python examples/mcp_example.py
75+
```
76+
77+
3. **Test CLI functionality:**
78+
```bash
79+
function_schema examples/cli_example.py get_weather
80+
```
81+
82+
## Integration Notes
83+
84+
- **OpenAI**: Requires `openai` library and API key for actual usage
85+
- **Claude**: Requires `anthropic` library and API key for actual usage
86+
- **MCP**: Conceptual example showing schema compatibility
87+
- **CLI**: Works out of the box with the installed package
88+
89+
## Schema Formats
90+
91+
The library supports multiple output formats:
92+
- **OpenAI format** (default): Uses `parameters` key
93+
- **Claude format**: Uses `input_schema` key
94+
95+
Specify format with: `get_function_schema(func, "claude")`

0 commit comments

Comments
 (0)