toolproxy 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
11
+ Universal Tool
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 toolproxy contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,243 @@
1
+ Metadata-Version: 2.4
2
+ Name: toolproxy
3
+ Version: 0.1.0
4
+ Summary: Universal tool-calling wrapper for non-tool-native LLMs — emulates function calling via structured JSON planning
5
+ Project-URL: Homepage, https://github.com/yourusername/toolproxy
6
+ Project-URL: Repository, https://github.com/yourusername/toolproxy
7
+ Project-URL: Bug Tracker, https://github.com/yourusername/toolproxy/issues
8
+ Author: toolproxy contributors
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: agents,ai,function-calling,llm,ollama,openrouter,pydantic,structured-output,tool-calling
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: httpx>=0.25
25
+ Requires-Dist: openai>=1.0
26
+ Requires-Dist: pydantic>=2.0
27
+ Provides-Extra: dev
28
+ Requires-Dist: build>=1.0; extra == 'dev'
29
+ Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
30
+ Requires-Dist: pytest-mock>=3.0; extra == 'dev'
31
+ Requires-Dist: pytest>=7.0; extra == 'dev'
32
+ Requires-Dist: twine>=5.0; extra == 'dev'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # toolproxy
36
+
37
+ [![PyPI version](https://badge.fury.io/py/toolproxy.svg)](https://pypi.org/project/toolproxy/)
38
+ [![Python Versions](https://img.shields.io/pypi/pyversions/toolproxy.svg)](https://pypi.org/project/toolproxy/)
39
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
40
+
41
+ **Universal Tool-Calling Wrapper for Non-Tool-Native LLMs**
42
+
43
+ A provider-agnostic Python library that adds reliable tool/function calling to *any* LLM — even models that have no native tool-calling API.
44
+
45
+ ---
46
+
47
+ ## Problem
48
+
49
+ Many LLM providers (OpenRouter, Ollama, local LLMs) expose models that don't support function calling. This library solves that by:
50
+
51
+ - **Detecting** whether the model supports native tool calling.
52
+ - **Using** native tool calls when available (OpenAI format).
53
+ - **Falling back** to a structured JSON planning protocol when not.
54
+
55
+ The developer always uses the same API regardless of the underlying model.
56
+
57
+ ---
58
+
59
+ ## Installation
60
+
61
+ ```bash
62
+ pip install toolproxy
63
+ ```
64
+
65
+ Or from source:
66
+
67
+ ```bash
68
+ pip install -e ".[dev]"
69
+ ```
70
+
71
+ ---
72
+
73
+ ## Quick Start
74
+
75
+ ```python
76
+ from toolproxy import UniversalAgent, tool
77
+
78
+ @tool
79
+ def get_weather(city: str) -> str:
80
+ """Get the current weather for a city."""
81
+ return f"Sunny, 25°C in {city}"
82
+
83
+ agent = UniversalAgent(
84
+ model="openrouter/mistralai/mistral-7b-instruct",
85
+ tools=[get_weather],
86
+ )
87
+
88
+ result = agent.run("What is the weather in Chennai today?")
89
+ print(result.content)
90
+ ```
91
+
92
+ The same code works whether the model supports native tools or not.
93
+
94
+ ---
95
+
96
+ ## How It Works
97
+
98
+ ```
99
+ Developer
100
+
101
+
102
+ UniversalAgent.run(prompt)
103
+
104
+ ├─ Planner (auto-detects native vs emulated mode)
105
+ │ │
106
+ │ ├── Native mode → provider tool calls (OpenAI format)
107
+ │ └── Emulated mode → structured JSON Action schema
108
+
109
+ ├─ Executor (validates args, runs tool, captures errors)
110
+
111
+ └─ LoopController (repeats until final answer or max_steps)
112
+ ```
113
+
114
+ ---
115
+
116
+ ## Model Prefixes
117
+
118
+ | Prefix | Backend |
119
+ |---|---|
120
+ | `openrouter/...` | OpenRouter API |
121
+ | `ollama/...` | Local Ollama server |
122
+ | `mock/...` | MockClient (for testing, no API key needed) |
123
+ | *(no prefix)* | OpenAI / any OpenAI-compatible endpoint |
124
+
125
+ ---
126
+
127
+ ## Advanced Options
128
+
129
+ ```python
130
+ from toolproxy import UniversalAgent, tool
131
+ from toolproxy.config import ExecutionPolicy
132
+
133
+ agent = UniversalAgent(
134
+ model="openrouter/your-model",
135
+ tools=[get_weather],
136
+ mode="auto", # "auto" | "native_only" | "emulated_only"
137
+ max_steps=10,
138
+ execution_policy=ExecutionPolicy(
139
+ mode="allow_only",
140
+ allowed_tools=["get_weather"],
141
+ ),
142
+ )
143
+
144
+ result = agent.run("...", return_trace=True)
145
+ print(result.content)
146
+ for call in result.trace.tool_calls:
147
+ print(call.tool_name, call.arguments)
148
+ ```
149
+
150
+ ### Callbacks (streaming-style)
151
+
152
+ ```python
153
+ result = agent.run(
154
+ "...",
155
+ on_tool_call=lambda step, tc: print(f"Calling: {tc.tool_name}"),
156
+ on_tool_result=lambda step, tr: print(f"Result: {tr.output}"),
157
+ on_model_output=lambda step, text: print(f"Model: {text}"),
158
+ )
159
+ ```
160
+
161
+ ---
162
+
163
+ ## Emulated Mode Protocol
164
+
165
+ When the model does not support native tools, the agent injects a system prompt instructing the model to output one of two JSON formats:
166
+
167
+ ```json
168
+ // Tool call
169
+ {"type": "tool_call", "tool": {"tool_name": "get_weather", "arguments": {"city": "Chennai"}}}
170
+
171
+ // Final answer
172
+ {"type": "final", "content": "The weather is sunny."}
173
+ ```
174
+
175
+ Malformed responses are retried up to `parse_retries` times (default: 3) with an error explanation.
176
+
177
+ ---
178
+
179
+ ## Project Structure
180
+
181
+ ```
182
+ src/toolproxy/
183
+ __init__.py # Public API re-exports
184
+ agent.py # UniversalAgent class
185
+ llm_client.py # LLMClient + adapters
186
+ tools.py # @tool decorator + ToolRegistry
187
+ schemas.py # Pydantic schemas
188
+ planner.py # Planner logic
189
+ executor.py # Tool execution + policies
190
+ loop.py # Loop controller
191
+ exceptions.py # Custom exceptions
192
+ config.py # Configuration + capability map
193
+ examples/
194
+ basic_chat.py
195
+ openrouter_tools.py
196
+ local_ollama.py
197
+ tests/
198
+ test_agent_basic.py
199
+ test_emulated_mode.py
200
+ test_native_mode.py
201
+ test_error_handling.py
202
+ test_tool_registry.py
203
+ ```
204
+
205
+ ---
206
+
207
+ ## Publishing to PyPI
208
+
209
+ ```bash
210
+ # 1. Install build tools
211
+ pip install build twine
212
+
213
+ # 2. Build wheel + sdist
214
+ python -m build
215
+
216
+ # 3. Check the distribution
217
+ twine check dist/*
218
+
219
+ # 4. Upload to PyPI (you will be prompted for credentials)
220
+ twine upload dist/*
221
+
222
+ # Or upload to TestPyPI first
223
+ twine upload --repository testpypi dist/*
224
+ ```
225
+
226
+ ---
227
+
228
+ ## Running Tests
229
+
230
+ ```bash
231
+ pytest tests/ -v
232
+ ```
233
+
234
+ ---
235
+
236
+ ## Environment Variables
237
+
238
+ | Variable | Description |
239
+ |---|---|
240
+ | `OPENROUTER_API_KEY` | API key for OpenRouter |
241
+ | `OPENAI_API_KEY` | API key for OpenAI |
242
+ | `OLLAMA_BASE_URL` | Ollama server URL (default: `http://localhost:11434`) |
243
+ | `OLLAMA_MODEL` | Ollama model name (default: `llama3`) |
@@ -0,0 +1,209 @@
1
+ # toolproxy
2
+
3
+ [![PyPI version](https://badge.fury.io/py/toolproxy.svg)](https://pypi.org/project/toolproxy/)
4
+ [![Python Versions](https://img.shields.io/pypi/pyversions/toolproxy.svg)](https://pypi.org/project/toolproxy/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
6
+
7
+ **Universal Tool-Calling Wrapper for Non-Tool-Native LLMs**
8
+
9
+ A provider-agnostic Python library that adds reliable tool/function calling to *any* LLM — even models that have no native tool-calling API.
10
+
11
+ ---
12
+
13
+ ## Problem
14
+
15
+ Many LLM providers (OpenRouter, Ollama, local LLMs) expose models that don't support function calling. This library solves that by:
16
+
17
+ - **Detecting** whether the model supports native tool calling.
18
+ - **Using** native tool calls when available (OpenAI format).
19
+ - **Falling back** to a structured JSON planning protocol when not.
20
+
21
+ The developer always uses the same API regardless of the underlying model.
22
+
23
+ ---
24
+
25
+ ## Installation
26
+
27
+ ```bash
28
+ pip install toolproxy
29
+ ```
30
+
31
+ Or from source:
32
+
33
+ ```bash
34
+ pip install -e ".[dev]"
35
+ ```
36
+
37
+ ---
38
+
39
+ ## Quick Start
40
+
41
+ ```python
42
+ from toolproxy import UniversalAgent, tool
43
+
44
+ @tool
45
+ def get_weather(city: str) -> str:
46
+ """Get the current weather for a city."""
47
+ return f"Sunny, 25°C in {city}"
48
+
49
+ agent = UniversalAgent(
50
+ model="openrouter/mistralai/mistral-7b-instruct",
51
+ tools=[get_weather],
52
+ )
53
+
54
+ result = agent.run("What is the weather in Chennai today?")
55
+ print(result.content)
56
+ ```
57
+
58
+ The same code works whether the model supports native tools or not.
59
+
60
+ ---
61
+
62
+ ## How It Works
63
+
64
+ ```
65
+ Developer
66
+
67
+
68
+ UniversalAgent.run(prompt)
69
+
70
+ ├─ Planner (auto-detects native vs emulated mode)
71
+ │ │
72
+ │ ├── Native mode → provider tool calls (OpenAI format)
73
+ │ └── Emulated mode → structured JSON Action schema
74
+
75
+ ├─ Executor (validates args, runs tool, captures errors)
76
+
77
+ └─ LoopController (repeats until final answer or max_steps)
78
+ ```
79
+
80
+ ---
81
+
82
+ ## Model Prefixes
83
+
84
+ | Prefix | Backend |
85
+ |---|---|
86
+ | `openrouter/...` | OpenRouter API |
87
+ | `ollama/...` | Local Ollama server |
88
+ | `mock/...` | MockClient (for testing, no API key needed) |
89
+ | *(no prefix)* | OpenAI / any OpenAI-compatible endpoint |
90
+
91
+ ---
92
+
93
+ ## Advanced Options
94
+
95
+ ```python
96
+ from toolproxy import UniversalAgent, tool
97
+ from toolproxy.config import ExecutionPolicy
98
+
99
+ agent = UniversalAgent(
100
+ model="openrouter/your-model",
101
+ tools=[get_weather],
102
+ mode="auto", # "auto" | "native_only" | "emulated_only"
103
+ max_steps=10,
104
+ execution_policy=ExecutionPolicy(
105
+ mode="allow_only",
106
+ allowed_tools=["get_weather"],
107
+ ),
108
+ )
109
+
110
+ result = agent.run("...", return_trace=True)
111
+ print(result.content)
112
+ for call in result.trace.tool_calls:
113
+ print(call.tool_name, call.arguments)
114
+ ```
115
+
116
+ ### Callbacks (streaming-style)
117
+
118
+ ```python
119
+ result = agent.run(
120
+ "...",
121
+ on_tool_call=lambda step, tc: print(f"Calling: {tc.tool_name}"),
122
+ on_tool_result=lambda step, tr: print(f"Result: {tr.output}"),
123
+ on_model_output=lambda step, text: print(f"Model: {text}"),
124
+ )
125
+ ```
126
+
127
+ ---
128
+
129
+ ## Emulated Mode Protocol
130
+
131
+ When the model does not support native tools, the agent injects a system prompt instructing the model to output one of two JSON formats:
132
+
133
+ ```json
134
+ // Tool call
135
+ {"type": "tool_call", "tool": {"tool_name": "get_weather", "arguments": {"city": "Chennai"}}}
136
+
137
+ // Final answer
138
+ {"type": "final", "content": "The weather is sunny."}
139
+ ```
140
+
141
+ Malformed responses are retried up to `parse_retries` times (default: 3) with an error explanation.
142
+
143
+ ---
144
+
145
+ ## Project Structure
146
+
147
+ ```
148
+ src/toolproxy/
149
+ __init__.py # Public API re-exports
150
+ agent.py # UniversalAgent class
151
+ llm_client.py # LLMClient + adapters
152
+ tools.py # @tool decorator + ToolRegistry
153
+ schemas.py # Pydantic schemas
154
+ planner.py # Planner logic
155
+ executor.py # Tool execution + policies
156
+ loop.py # Loop controller
157
+ exceptions.py # Custom exceptions
158
+ config.py # Configuration + capability map
159
+ examples/
160
+ basic_chat.py
161
+ openrouter_tools.py
162
+ local_ollama.py
163
+ tests/
164
+ test_agent_basic.py
165
+ test_emulated_mode.py
166
+ test_native_mode.py
167
+ test_error_handling.py
168
+ test_tool_registry.py
169
+ ```
170
+
171
+ ---
172
+
173
+ ## Publishing to PyPI
174
+
175
+ ```bash
176
+ # 1. Install build tools
177
+ pip install build twine
178
+
179
+ # 2. Build wheel + sdist
180
+ python -m build
181
+
182
+ # 3. Check the distribution
183
+ twine check dist/*
184
+
185
+ # 4. Upload to PyPI (you will be prompted for credentials)
186
+ twine upload dist/*
187
+
188
+ # Or upload to TestPyPI first
189
+ twine upload --repository testpypi dist/*
190
+ ```
191
+
192
+ ---
193
+
194
+ ## Running Tests
195
+
196
+ ```bash
197
+ pytest tests/ -v
198
+ ```
199
+
200
+ ---
201
+
202
+ ## Environment Variables
203
+
204
+ | Variable | Description |
205
+ |---|---|
206
+ | `OPENROUTER_API_KEY` | API key for OpenRouter |
207
+ | `OPENAI_API_KEY` | API key for OpenAI |
208
+ | `OLLAMA_BASE_URL` | Ollama server URL (default: `http://localhost:11434`) |
209
+ | `OLLAMA_MODEL` | Ollama model name (default: `llama3`) |
@@ -0,0 +1,93 @@
1
+ """
2
+ Basic chat example — demonstrates the @tool decorator and UniversalAgent.run().
3
+
4
+ Runs without a real API key using MockClient responses so you can see the flow.
5
+ To use with a real model, set OPENROUTER_API_KEY and change the model string.
6
+ """
7
+ import os
8
+ import sys
9
+
10
+ # Allow running from repo root
11
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
12
+
13
+ from toolproxy import UniversalAgent, tool
14
+ from toolproxy.llm_client import MockClient, ModelResponse
15
+ from toolproxy.schemas import ToolCall
16
+
17
+
18
+ # ---------------------------------------------------------------------------
19
+ # Define tools
20
+ # ---------------------------------------------------------------------------
21
+
22
+ @tool
23
+ def get_weather(city: str) -> str:
24
+ """Get the current weather for a city."""
25
+ # In a real app this would call a weather API
26
+ weather_data = {
27
+ "Chennai": "Sunny, 34°C, humidity 72%",
28
+ "Mumbai": "Partly cloudy, 31°C, humidity 85%",
29
+ "Delhi": "Hazy, 38°C, humidity 45%",
30
+ }
31
+ return weather_data.get(city, f"Weather data not available for {city}")
32
+
33
+
34
+ @tool
35
+ def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
36
+ """Convert an amount from one currency to another."""
37
+ # Simplified fixed rates for demo
38
+ rates = {"USD": 1.0, "INR": 83.5, "EUR": 0.92, "GBP": 0.79}
39
+ if from_currency not in rates or to_currency not in rates:
40
+ return f"Currency not supported. Supported: {', '.join(rates)}"
41
+ converted = amount / rates[from_currency] * rates[to_currency]
42
+ return f"{amount} {from_currency} = {converted:.2f} {to_currency}"
43
+
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # Mock responses simulating: tool call → final answer
47
+ # ---------------------------------------------------------------------------
48
+
49
+ MOCK_RESPONSES = [
50
+ # Step 1: model calls get_weather
51
+ ModelResponse(
52
+ raw_text='{"type": "tool_call", "tool": {"tool_name": "get_weather", "arguments": {"city": "Chennai"}}}',
53
+ tool_calls=[],
54
+ ),
55
+ # Step 2: model gives final answer after seeing result
56
+ ModelResponse(
57
+ raw_text='{"type": "final", "content": "The weather in Chennai is Sunny, 34°C with 72% humidity. Have a great day!"}',
58
+ tool_calls=[],
59
+ ),
60
+ ]
61
+
62
+
63
+ def run_demo():
64
+ mock_client = MockClient(responses=MOCK_RESPONSES, native_tools=False)
65
+
66
+ agent = UniversalAgent(
67
+ model="mock/demo",
68
+ tools=[get_weather, convert_currency],
69
+ client=mock_client,
70
+ mode="emulated_only",
71
+ )
72
+
73
+ print("=== Universal Agent — Basic Chat Demo ===\n")
74
+ print(f"Agent: {agent}\n")
75
+
76
+ result = agent.run(
77
+ "What is the weather in Chennai today?",
78
+ return_trace=True,
79
+ on_tool_call=lambda step, tc: print(f"[Step {step}] Calling tool: {tc.tool_name}({tc.arguments})"),
80
+ on_tool_result=lambda step, tr: print(f"[Step {step}] Tool result: {tr.output or tr.error}"),
81
+ )
82
+
83
+ print(f"\n[OK] Final Answer: {result.content}")
84
+ print(f"Steps taken: {result.steps_taken}")
85
+ if result.trace:
86
+ print(f"\nTrace summary:")
87
+ for entry in result.trace.steps:
88
+ if entry.tool_call:
89
+ print(f" - Called: {entry.tool_call.tool_name}")
90
+
91
+
92
+ if __name__ == "__main__":
93
+ run_demo()
@@ -0,0 +1,83 @@
1
+ """
2
+ Local Ollama example — runs toolproxy against a local Ollama server.
3
+
4
+ Requires: Ollama installed and running locally.
5
+ Usage:
6
+ ollama pull llama3
7
+ python examples/local_ollama.py
8
+ """
9
+ import os
10
+ import sys
11
+
12
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
13
+
14
+ from toolproxy import UniversalAgent, tool
15
+ from toolproxy.llm_client import OllamaClient
16
+
17
+
18
+ @tool
19
+ def list_files(directory: str) -> str:
20
+ """List files in a local directory."""
21
+ import os as _os
22
+ try:
23
+ entries = _os.listdir(directory)
24
+ if not entries:
25
+ return f"Directory '{directory}' is empty."
26
+ return "\n".join(entries[:20]) # limit output
27
+ except FileNotFoundError:
28
+ return f"Directory '{directory}' not found."
29
+ except PermissionError:
30
+ return f"Permission denied for '{directory}'."
31
+
32
+
33
+ @tool
34
+ def read_file(path: str, max_lines: int = 50) -> str:
35
+ """Read the contents of a file (up to max_lines lines)."""
36
+ try:
37
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
38
+ lines = []
39
+ for i, line in enumerate(f):
40
+ if i >= max_lines:
41
+ lines.append(f"... (truncated at {max_lines} lines)")
42
+ break
43
+ lines.append(line.rstrip())
44
+ return "\n".join(lines) if lines else "(empty file)"
45
+ except FileNotFoundError:
46
+ return f"File '{path}' not found."
47
+ except PermissionError:
48
+ return f"Permission denied for '{path}'."
49
+
50
+
51
+ def main():
52
+ model = os.environ.get("OLLAMA_MODEL", "llama3")
53
+ base_url = os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434")
54
+
55
+ print(f"=== Local Ollama Demo ===")
56
+ print(f"Model: {model} @ {base_url}")
57
+ print("Mode: emulated (Ollama default)\n")
58
+
59
+ client = OllamaClient(model=model, base_url=base_url, native_tools=False)
60
+
61
+ agent = UniversalAgent(
62
+ model=f"ollama/{model}",
63
+ tools=[list_files, read_file],
64
+ mode="emulated_only",
65
+ client=client,
66
+ )
67
+
68
+ prompt = "List the files in the current directory."
69
+ print(f"Prompt: {prompt}\n")
70
+
71
+ result = agent.run(
72
+ prompt,
73
+ return_trace=True,
74
+ on_tool_call=lambda s, tc: print(f"[Step {s}] → {tc.tool_name}({tc.arguments})"),
75
+ on_tool_result=lambda s, tr: print(f"[Step {s}] ← {(tr.output or tr.error)[:200]}"),
76
+ )
77
+
78
+ print(f"\n✅ Answer: {result.content}")
79
+ print(f"Steps: {result.steps_taken}")
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()