OpenAI Toolchain
A Python library for working with OpenAI's function calling API, making it easier to create and manage tools that can be used with OpenAI's chat models.
Features
- 🛠️ Simple function registration with
@tooldecorator - 🤖 Automatic tool schema generation
- 🔄 Seamless integration with OpenAI's API
- ⚡ Support for both sync and async operations
- 📚 Clean and intuitive API
Installation
pip install openai-toolchain
Quick Start
- Define your tools using the
@tooldecorator:
from openai_toolchain import tool, OpenAIClient
@tool
def get_weather(location: str, unit: str = "celsius") -> str:
"""Get the current weather in a given location.
Args:
location: The city to get the weather for
unit: The unit of temperature (celsius or fahrenheit)
"""
return f"The weather in {location} is 22 {unit}"
@tool("get_forecast")
def get_forecast_function(location: str, days: int = 1) -> str:
"""Get a weather forecast for a location.
Args:
location: The city to get the forecast for
days: Number of days to forecast (1-5)
"""
return f"{days}-day forecast for {location}: Sunny"
- Use the tools with OpenAI:
# Initialize the client with your API key
client = OpenAIClient(api_key="your-api-key")
# Use the client
response = client.chat_with_tools(
messages=[{"role": "user", "content": "What's the weather in Toronto?"}]
)
print(response)
Documentation
For detailed documentation, including API reference and examples, please visit:
Or run the documentation locally:
pip install -e ".[docs]"
mkdocs serve
Contributing
Contributions are welcome! Please see our Contributing Guide for details.
Pre-commit Hooks
This project uses pre-commit to ensure code quality and style consistency. To set it up:
-
Install pre-commit:
pip install pre-commit
-
Install the git hook scripts:
pre-commit install -
(Optional) Run against all files:
pre-commit run --all-files
The hooks will now run automatically on every commit. To skip the pre-commit checks, use:
git commit --no-verify -m "Your commit message"
License
This project is licensed under the MIT License - see the LICENSE file for details.
Initialize the client with your API key
client = OpenAIClient(api_key="your-api-key")
Chat with automatic tool calling
response = client.chat_with_tools( messages=[{"role": "user", "content": "What's the weather in Toronto?"}], tools=["get_weather"] # Optional: specify which tools to use )
print(response)
## Features
### 1. Tool Registration
Use the `@tool` decorator to register functions as tools:
```python
from openai_toolchain import tool
@tool
def search_web(query: str) -> str:
"""Search the web for information."""
return f"Search results for: {query}"
2. Chat with Automatic Tool Calling
The chat_with_tools method handles tool calls automatically:
client = OpenAIClient(api_key="your-api-key")
response = client.chat_with_tools(
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Search for the latest Python news"}
],
tools=["search_web"],
model="gpt-4" # Optional: specify a different model
)
3. Accessing Registered Tools
You can access registered tools directly:
from openai_toolchain import tool_registry
# Get all registered tools
tools = tool_registry.get_openai_tools()
# Call a tool directly
result = tool_registry.call_tool("get_weather", {"location": "Paris", "unit": "fahrenheit"})
API Reference
@tool decorator
Register a function as a tool:
from openai_toolchain import tool
# Basic usage
@tool
def my_function(param: str) -> str:
"""Function documentation."""
return f"Result for {param}"
# With non-AI parameters
@tool(non_ai_params=["db_connection"])
def get_data(query: str, db_connection: Database) -> str:
"""Get data from the database.
Args:
query: The search query
db_connection: Database connection (handled by the system, not AI)
"""
return db_connection.execute(query)
Non-AI Parameters
You can mark certain parameters as non-AI parameters, which means they will be provided by the system rather than the AI. This is useful for passing in dependencies like database connections, configuration, or other runtime objects.
- Specify non-AI parameters using the
non_ai_paramsargument in the@tooldecorator - These parameters will be excluded from the AI's schema
- You must provide these parameters when calling
chat_with_toolsusing thetool_paramsargument
Example usage with chat_with_tools:
# Initialize client and dependencies
client = OpenAIClient(api_key="your-api-key")
db = DatabaseConnection()
# Call with non-AI parameters
response = client.chat_with_tools(
messages=[{"role": "user", "content": "Get me user data for John"}],
tools=["get_data"],
tool_params={
"get_data": {
"db_connection": db
}
}
)
tool_registry
The global registry instance with these methods:
register(func, **kwargs): Register a function as a toolget_tool(name): Get a registered tool by namecall_tool(name, arguments): Call a registered tool by name with argumentsget_openai_tools(): Get all tools in OpenAI format
Development
# Install in development mode
pip install -e ".[dev]"
# Run tests
pytest
License
MIT
Metadata
Release files for openai-toolchain 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| openai_toolchain-0.3.0.tar.gz | 30.8 kB | Without provenance | Details for openai_toolchain-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| openai_toolchain-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for openai_toolchain-0.3.0-py3-none-any.whl |
Total release size: 46.2 kB
Release files / openai_toolchain-0.3.0.tar.gz
| Download URL | openai_toolchain-0.3.0.tar.gz |
|---|---|
| Size | 30.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d8a06f867fe0764c531b9dfd0e01b0d12cf2064096e0e3c9bf29610dda54a790
|
|
BLAKE2b-256 checksum How to use checksums |
35a94139fd92d6cd6522f5e5e0a447af0d72fdded32ca190ea14acfcd5c93a1b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.12.9
|
Release files / openai_toolchain-0.3.0-py3-none-any.whl
| Download URL | openai_toolchain-0.3.0-py3-none-any.whl |
|---|---|
| Size | 15.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4fa171ebfe894bc3743becf2cf3b6254ffa3b0785f8162734c9ad470f9754eb8
|
|
BLAKE2b-256 checksum How to use checksums |
c2e0494323d6c16913a5b73e67dca2075e806992de6c7106d0a70ea8fa4542a4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.12.9
|
Security for openai-toolchain 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.