@botbotgo/better-call 0.1.0
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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +133 -0
- package/benchmarks/bfcl-targeted-summary.json +23 -0
- package/dist/better-tool.d.ts +18 -0
- package/dist/better-tool.js +60 -0
- package/dist/better-tool.js.map +1 -0
- package/dist/default-repair.d.ts +5 -0
- package/dist/default-repair.js +41 -0
- package/dist/default-repair.js.map +1 -0
- package/dist/guard.d.ts +6 -0
- package/dist/guard.js +30 -0
- package/dist/guard.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/prompts.d.ts +3 -0
- package/dist/prompts.js +25 -0
- package/dist/prompts.js.map +1 -0
- package/dist/reliable.d.ts +2 -0
- package/dist/reliable.js +25 -0
- package/dist/reliable.js.map +1 -0
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +94 -0
- package/dist/schema.js.map +1 -0
- package/dist/types.d.ts +59 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/docs/banner.svg +29 -0
- package/package.json +50 -0
- package/scripts/bench-bfcl.mjs +77 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 BotBotGo
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="docs/banner.svg" alt="BetterCall - one-line wrapper for small-model tool calls">
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
# BetterCall
|
|
6
|
+
|
|
7
|
+
**One-line wrapper. BFCL tool-call accuracy: 81.3% → 91.3%.**
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
const tools = betterTools([searchTool, calculatorTool]);
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
No model means validate + block only. Add `repairModel` when you want automatic repair.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install @botbotgo/better-call
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## LangGraph Quick Start
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { betterTools } from "@botbotgo/better-call";
|
|
25
|
+
|
|
26
|
+
// Validate + block: stop bad calls before execution.
|
|
27
|
+
const tools = betterTools([searchTool, calculatorTool]);
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Pass a repair model to let BetterCall fix rejected calls automatically. This can be the same chat model your agent uses, or a separate cheaper/stronger model dedicated to repair:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
// Validate + repair: validate, repair with a model, validate again, then execute.
|
|
34
|
+
const tools = betterTools([searchTool, calculatorTool], {
|
|
35
|
+
repairModel: model,
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Run The BFCL Benchmark
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npm run bench:bfcl
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
This prints the BFCL v4 targeted weak-category table used above. It is a BetterCall wrapper benchmark, not an official leaderboard submission.
|
|
46
|
+
|
|
47
|
+
For the full official BFCL v4 reproduction, use Berkeley's published checkpoint/package: commit `f7cf735` or `pip install bfcl-eval==2025.12.17`.
|
|
48
|
+
|
|
49
|
+
## What It Catches
|
|
50
|
+
|
|
51
|
+
| Category | Failures | Example |
|
|
52
|
+
| --- | --- | --- |
|
|
53
|
+
| Tool selection | Unknown tool | `stock_price` instead of `stock_quote` |
|
|
54
|
+
| Tool selection | Irrelevant call | Model calls a tool when no tool should be used |
|
|
55
|
+
| Arguments | Missing required arg | Missing required `ticker` |
|
|
56
|
+
| Arguments | Wrong arg name | `symbol` instead of `ticker` |
|
|
57
|
+
| Arguments | Wrong type | `"3"` where an integer is required |
|
|
58
|
+
| Schema | Invalid enum | `NASDAQ` where only `US`, `HK`, `CN` are allowed |
|
|
59
|
+
| Schema | Extra arg | `currency` when `additionalProperties: false` |
|
|
60
|
+
| Policy | Semantic validator rejection | Domain-specific validator rejects unsafe args |
|
|
61
|
+
|
|
62
|
+
In validate + block mode, BetterCall rejects these calls before execution. With `repairModel`, it asks the model to fix rejected calls, validates again, and only then executes.
|
|
63
|
+
|
|
64
|
+
## API
|
|
65
|
+
|
|
66
|
+
### `betterTools`
|
|
67
|
+
|
|
68
|
+
Wrap a LangGraph-style tools array.
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
// Validate + block.
|
|
72
|
+
const tools = betterTools([searchTool, calculatorTool]);
|
|
73
|
+
|
|
74
|
+
// Validate + repair.
|
|
75
|
+
const toolsWithRepair = betterTools([searchTool, calculatorTool], { repairModel: model });
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`options` is optional. Each tool must expose `name` and `invoke(input)`. BetterCall preserves each tool's shape and wraps `invoke`.
|
|
79
|
+
|
|
80
|
+
Without `repairModel` or `repair`, BetterCall validates and blocks unsafe calls instead of fixing them. `repairModel` only needs an `invoke(input)` method, such as a LangChain chat model. If it is provided, BetterCall supplies the repair prompt and JSON parser.
|
|
81
|
+
|
|
82
|
+
Modes:
|
|
83
|
+
|
|
84
|
+
| Mode | Behavior |
|
|
85
|
+
| --- | --- |
|
|
86
|
+
| no model | Validate and block only |
|
|
87
|
+
| `repairModel` | Validate, repair rejected calls, then validate again |
|
|
88
|
+
| custom `repair` | Use your own repair function |
|
|
89
|
+
| `review` | Ask for a full self-check even when calls pass schema |
|
|
90
|
+
|
|
91
|
+
Default recommendation: start with validate + block, then add `repairModel` for small models or unreliable tool callers. `review` is more expensive and model-dependent.
|
|
92
|
+
|
|
93
|
+
`irrelevance` is one validation failure type: the model called a tool when no tool should be called. BetterCall also validates tool names, argument names, JSON schema, types, enums, and semantic validators.
|
|
94
|
+
|
|
95
|
+
## Benchmark
|
|
96
|
+
|
|
97
|
+
Measured on BFCL v4 single-turn targeted weak categories with remote Ollama models.
|
|
98
|
+
|
|
99
|
+
This is **not an official BFCL leaderboard score**. It measures BetterCall as a runtime reliability layer.
|
|
100
|
+
|
|
101
|
+
| Model | Raw | BetterCall repair | Accuracy lift |
|
|
102
|
+
| --- | ---: | ---: | ---: |
|
|
103
|
+
| `gemma4:e2b` | 81.3% | 91.3% | +10.0pp |
|
|
104
|
+
| `qwen3.5:2b` | 75.3% | 84.0% | +8.7pp |
|
|
105
|
+
| `qwen3.5:9b` | 84.0% | 90.0% | +6.0pp |
|
|
106
|
+
| `qwen3.5:4b` | 82.0% | 87.3% | +5.3pp |
|
|
107
|
+
| `granite4.1:3b` | 66.0% | 69.3% | +3.3pp |
|
|
108
|
+
|
|
109
|
+
Strongest result: BFCL `irrelevance`, where the model should not call any tool.
|
|
110
|
+
|
|
111
|
+
| Model | Raw irrelevance | BetterCall repair |
|
|
112
|
+
| --- | ---: | ---: |
|
|
113
|
+
| `qwen3.5:2b` | 74% | 100% |
|
|
114
|
+
| `qwen3.5:4b` | 84% | 100% |
|
|
115
|
+
| `qwen3.5:9b` | 84% | 100% |
|
|
116
|
+
| `granite4.1:3b` | 92% | 100% |
|
|
117
|
+
| `gemma4:e2b` | 70% | 100% |
|
|
118
|
+
|
|
119
|
+
## Why It Exists
|
|
120
|
+
|
|
121
|
+
Small models are useful because they are cheap and fast. They also make tool mistakes:
|
|
122
|
+
|
|
123
|
+
- call a tool that does not exist
|
|
124
|
+
- fill the wrong parameter names
|
|
125
|
+
- pass the wrong types
|
|
126
|
+
- call tools when no tool is relevant
|
|
127
|
+
- produce a call that looks valid but is unsafe to execute
|
|
128
|
+
|
|
129
|
+
BetterCall reduces those failures before they reach production tools.
|
|
130
|
+
|
|
131
|
+
## License
|
|
132
|
+
|
|
133
|
+
Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "BFCL v4 targeted weak categories",
|
|
3
|
+
"source": "BetterCall targeted wrapper benchmark over BFCL v4 single-turn weak categories",
|
|
4
|
+
"officialBenchmark": "https://gorilla.cs.berkeley.edu/leaderboard",
|
|
5
|
+
"officialReproduction": {
|
|
6
|
+
"commit": "f7cf735",
|
|
7
|
+
"pythonPackage": "bfcl-eval==2025.12.17"
|
|
8
|
+
},
|
|
9
|
+
"rows": [
|
|
10
|
+
{ "model": "gemma4:e2b", "total": 150, "rawCorrect": 122, "betterCorrect": 137 },
|
|
11
|
+
{ "model": "qwen3.5:2b", "total": 150, "rawCorrect": 113, "betterCorrect": 126 },
|
|
12
|
+
{ "model": "qwen3.5:9b", "total": 150, "rawCorrect": 126, "betterCorrect": 135 },
|
|
13
|
+
{ "model": "qwen3.5:4b", "total": 150, "rawCorrect": 123, "betterCorrect": 131 },
|
|
14
|
+
{ "model": "granite4.1:3b", "total": 150, "rawCorrect": 99, "betterCorrect": 104 }
|
|
15
|
+
],
|
|
16
|
+
"irrelevance": [
|
|
17
|
+
{ "model": "qwen3.5:2b", "total": 50, "rawCorrect": 37, "betterCorrect": 50 },
|
|
18
|
+
{ "model": "qwen3.5:4b", "total": 50, "rawCorrect": 42, "betterCorrect": 50 },
|
|
19
|
+
{ "model": "qwen3.5:9b", "total": 50, "rawCorrect": 42, "betterCorrect": 50 },
|
|
20
|
+
{ "model": "granite4.1:3b", "total": 50, "rawCorrect": 46, "betterCorrect": 50 },
|
|
21
|
+
{ "model": "gemma4:e2b", "total": 50, "rawCorrect": 35, "betterCorrect": 50 }
|
|
22
|
+
]
|
|
23
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type RepairModelLike } from "./default-repair.js";
|
|
2
|
+
import type { GuardPolicy, JsonSchema, RepairFunction, SemanticValidator } from "./types.js";
|
|
3
|
+
export type BetterToolLike = {
|
|
4
|
+
name: string;
|
|
5
|
+
description?: string;
|
|
6
|
+
schema?: unknown;
|
|
7
|
+
invoke(input: unknown, config?: unknown): Promise<unknown> | unknown;
|
|
8
|
+
};
|
|
9
|
+
export type BetterToolsOptions = {
|
|
10
|
+
userInput?: string | ((toolInput: Record<string, unknown>) => string);
|
|
11
|
+
schema?: JsonSchema;
|
|
12
|
+
validate?: SemanticValidator;
|
|
13
|
+
repairModel?: RepairModelLike;
|
|
14
|
+
repair?: RepairFunction;
|
|
15
|
+
policy?: GuardPolicy;
|
|
16
|
+
mode?: "guard" | "repair" | "review";
|
|
17
|
+
};
|
|
18
|
+
export declare function betterTools<T extends BetterToolLike>(tools: T[], options?: BetterToolsOptions): T[];
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { defaultRepair } from "./default-repair.js";
|
|
2
|
+
import { reliableToolCalls } from "./reliable.js";
|
|
3
|
+
export function betterTools(tools, options = {}) {
|
|
4
|
+
return tools.map((tool) => wrapOneTool(tool, options));
|
|
5
|
+
}
|
|
6
|
+
function wrapOneTool(tool, options) {
|
|
7
|
+
const wrapped = Object.assign(Object.create(Object.getPrototypeOf(tool)), tool);
|
|
8
|
+
wrapped.invoke = async (input, config) => {
|
|
9
|
+
const args = extractArgs(input);
|
|
10
|
+
const result = await reliableToolCalls({
|
|
11
|
+
userInput: resolveUserInput(options.userInput, args),
|
|
12
|
+
tools: [toToolDefinition(tool, options)],
|
|
13
|
+
calls: [{ tool: tool.name, args }],
|
|
14
|
+
policy: options.policy,
|
|
15
|
+
repair: resolveRepair(options),
|
|
16
|
+
mode: options.mode,
|
|
17
|
+
});
|
|
18
|
+
if (!result.ok) {
|
|
19
|
+
throw new Error(`BetterCall rejected ${tool.name}: ${result.issues.map((issue) => issue.message).join("; ")}`);
|
|
20
|
+
}
|
|
21
|
+
const safeCall = result.calls.find((call) => call.tool === tool.name);
|
|
22
|
+
if (!safeCall)
|
|
23
|
+
throw new Error(`BetterCall removed ${tool.name} before execution.`);
|
|
24
|
+
return tool.invoke.call(tool, applySafeArgs(input, safeCall.args), config);
|
|
25
|
+
};
|
|
26
|
+
return wrapped;
|
|
27
|
+
}
|
|
28
|
+
function resolveRepair(options) {
|
|
29
|
+
return options.repair ?? (options.repairModel ? defaultRepair(options.repairModel) : undefined);
|
|
30
|
+
}
|
|
31
|
+
function toToolDefinition(tool, options) {
|
|
32
|
+
return {
|
|
33
|
+
name: tool.name,
|
|
34
|
+
description: tool.description,
|
|
35
|
+
schema: options.schema ?? (isJsonSchema(tool.schema) ? tool.schema : undefined),
|
|
36
|
+
validate: options.validate,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function resolveUserInput(userInput, args) {
|
|
40
|
+
if (typeof userInput === "function")
|
|
41
|
+
return userInput(args);
|
|
42
|
+
return userInput ?? JSON.stringify(args);
|
|
43
|
+
}
|
|
44
|
+
function extractArgs(input) {
|
|
45
|
+
if (isRecord(input) && isRecord(input.args))
|
|
46
|
+
return input.args;
|
|
47
|
+
return isRecord(input) ? input : { input };
|
|
48
|
+
}
|
|
49
|
+
function applySafeArgs(input, args) {
|
|
50
|
+
if (isRecord(input) && isRecord(input.args))
|
|
51
|
+
return { ...input, args };
|
|
52
|
+
return args;
|
|
53
|
+
}
|
|
54
|
+
function isJsonSchema(value) {
|
|
55
|
+
return isRecord(value) && (typeof value.type === "string" || Array.isArray(value.type) || isRecord(value.properties));
|
|
56
|
+
}
|
|
57
|
+
function isRecord(value) {
|
|
58
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=better-tool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"better-tool.js","sourceRoot":"","sources":["../src/better-tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE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,CAAC,KAAK,CAAC,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC,IAAI,CAAC;IAC/D,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC;AAC7C,CAAC;AAED,SAAS,aAAa,CAAC,KAAc,EAAE,IAA6B;IAClE,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC;QAAE,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC;IACvE,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,QAAQ,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC;AACxH,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { buildRepairPrompt } from "./prompts.js";
|
|
2
|
+
export function defaultRepair(model) {
|
|
3
|
+
return async (input) => {
|
|
4
|
+
const response = await model.invoke(buildRepairPrompt(input));
|
|
5
|
+
return parseToolCalls(response);
|
|
6
|
+
};
|
|
7
|
+
}
|
|
8
|
+
function parseToolCalls(response) {
|
|
9
|
+
const value = parseJson(extractContent(response));
|
|
10
|
+
const calls = Array.isArray(value) ? value : isRecord(value) ? value.calls : undefined;
|
|
11
|
+
if (!Array.isArray(calls))
|
|
12
|
+
return [];
|
|
13
|
+
return calls.filter(isToolCall).map((call) => ({ tool: call.tool, args: call.args }));
|
|
14
|
+
}
|
|
15
|
+
function extractContent(response) {
|
|
16
|
+
if (isRecord(response) && "content" in response)
|
|
17
|
+
return response.content;
|
|
18
|
+
return response;
|
|
19
|
+
}
|
|
20
|
+
function parseJson(value) {
|
|
21
|
+
if (typeof value !== "string")
|
|
22
|
+
return value;
|
|
23
|
+
try {
|
|
24
|
+
return JSON.parse(stripCodeFence(value));
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return {};
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function stripCodeFence(value) {
|
|
31
|
+
const trimmed = value.trim();
|
|
32
|
+
const match = /^```(?:json)?\s*([\s\S]*?)\s*```$/u.exec(trimmed);
|
|
33
|
+
return match ? match[1] : trimmed;
|
|
34
|
+
}
|
|
35
|
+
function isToolCall(value) {
|
|
36
|
+
return isRecord(value) && typeof value.tool === "string" && isRecord(value.args);
|
|
37
|
+
}
|
|
38
|
+
function isRecord(value) {
|
|
39
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=default-repair.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"default-repair.js","sourceRoot":"","sources":["../src/default-repair.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAOjD,MAAM,UAAU,aAAa,CAAC,KAAsB;IAClD,OAAO,KAAK,EAAE,KAAK,EAAE,EAAE;QACrB,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,MAAM,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC9D,OAAO,cAAc,CAAC,QAAQ,CAAC,CAAC;IAClC,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,cAAc,CAAC,QAAiB;IACvC,MAAM,KAAK,GAAG,SAAS,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC,CAAC;IAClD,MAAM,KAAK,GAAG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IAAI,KAAK,QAAQ,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AACnF,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC"}
|
package/dist/guard.d.ts
ADDED
package/dist/guard.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { validateSchema } from "./schema.js";
|
|
2
|
+
export async function guardToolCalls(input) {
|
|
3
|
+
const policy = input.policy ?? {};
|
|
4
|
+
const issues = [];
|
|
5
|
+
if (policy.expected === "none" && input.calls.length > 0) {
|
|
6
|
+
issues.push({ kind: "irrelevant_call", path: "$.calls", message: "tool call was not expected" });
|
|
7
|
+
}
|
|
8
|
+
if (policy.expected === "some" && input.calls.length === 0) {
|
|
9
|
+
issues.push({ kind: "missing_call", path: "$.calls", message: "tool call was expected" });
|
|
10
|
+
}
|
|
11
|
+
for (const [index, call] of input.calls.entries()) {
|
|
12
|
+
issues.push(...await validateOneCall(call, index, input.tools, policy));
|
|
13
|
+
}
|
|
14
|
+
return { ok: issues.length === 0, calls: input.calls, issues };
|
|
15
|
+
}
|
|
16
|
+
async function validateOneCall(call, index, tools, policy) {
|
|
17
|
+
const tool = tools.find((item) => item.name === call.tool);
|
|
18
|
+
if (!tool) {
|
|
19
|
+
return policy.allowUnknownTools ? [] : [{
|
|
20
|
+
kind: "unknown_tool",
|
|
21
|
+
path: `$.calls[${index}].tool`,
|
|
22
|
+
message: `unknown tool ${call.tool}`,
|
|
23
|
+
tool: call.tool,
|
|
24
|
+
}];
|
|
25
|
+
}
|
|
26
|
+
const schemaIssues = validateSchema(tool.schema, call.args, `$.calls[${index}].args`);
|
|
27
|
+
const semanticIssues = tool.validate ? await tool.validate({ call, tool }) : [];
|
|
28
|
+
return [...schemaIssues.map((issue) => ({ ...issue, tool: call.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C5B,IAAc,EACd,KAAa,EACb,KAAuB,EACvB,MAAmB;IAEnB,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3D,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,OAAO,MAAM,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;gBACtC,IAAI,EAAE,cAAc;gBACpB,IAAI,EAAE,WAAW,KAAK,QAAQ;gBAC9B,OAAO,EAAE,gBAAgB,IAAI,CAAC,IAAI,EAAE;gBACpC,IAAI,EAAE,IAAI,CAAC,IAAI;aAChB,CAAC,CAAC;IACL,CAAC;IACD,MAAM,YAAY,GAAG,cAAc,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE,WAAW,KAAK,QAAQ,CAAC,CAAC;IACtF,MAAM,cAAc,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAChF,OAAO,CAAC,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,GAAG,cAAc,CAAC,CAAC;AAC9F,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { guardToolCalls } from "./guard.js";
|
|
2
|
+
export { buildRepairPrompt, buildReviewPrompt } from "./prompts.js";
|
|
3
|
+
export { defaultRepair } from "./default-repair.js";
|
|
4
|
+
export type { RepairModelLike } from "./default-repair.js";
|
|
5
|
+
export { reliableToolCalls } from "./reliable.js";
|
|
6
|
+
export { betterTools } from "./better-tool.js";
|
|
7
|
+
export type { BetterToolLike, BetterToolsOptions } from "./better-tool.js";
|
|
8
|
+
export type { GuardPolicy, GuardResult, IssueKind, JsonSchema, ReliableToolCallsInput, ReliableToolCallsResult, RepairFunction, RepairInput, SemanticValidator, ToolCall, ToolCallIssue, ToolDefinition, } from "./types.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { guardToolCalls } from "./guard.js";
|
|
2
|
+
export { buildRepairPrompt, buildReviewPrompt } from "./prompts.js";
|
|
3
|
+
export { defaultRepair } from "./default-repair.js";
|
|
4
|
+
export { reliableToolCalls } from "./reliable.js";
|
|
5
|
+
export { betterTools } from "./better-tool.js";
|
|
6
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACpE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC"}
|
package/dist/prompts.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export function buildRepairPrompt(input) {
|
|
2
|
+
return [
|
|
3
|
+
"The previous LLM tool call was rejected before execution.",
|
|
4
|
+
"Return corrected JSON only as {\"calls\":[{\"tool\":\"name\",\"args\":{}}]}.",
|
|
5
|
+
"If no tool should be called, return {\"calls\":[]}.",
|
|
6
|
+
"",
|
|
7
|
+
`User request: ${input.userInput}`,
|
|
8
|
+
`Tools: ${JSON.stringify(input.tools)}`,
|
|
9
|
+
`Rejected calls: ${JSON.stringify(input.calls)}`,
|
|
10
|
+
`Issues: ${JSON.stringify(input.issues)}`,
|
|
11
|
+
].join("\n");
|
|
12
|
+
}
|
|
13
|
+
export function buildReviewPrompt(input) {
|
|
14
|
+
return [
|
|
15
|
+
"Review the previous LLM tool calls for completeness and correctness.",
|
|
16
|
+
"Keep correct calls, add missing calls, remove irrelevant calls, and fix arguments if needed.",
|
|
17
|
+
"Return final JSON only as {\"calls\":[{\"tool\":\"name\",\"args\":{}}]}.",
|
|
18
|
+
"",
|
|
19
|
+
`User request: ${input.userInput}`,
|
|
20
|
+
`Tools: ${JSON.stringify(input.tools)}`,
|
|
21
|
+
`Previous calls: ${JSON.stringify(input.calls)}`,
|
|
22
|
+
`Validation issues, if any: ${JSON.stringify(input.issues)}`,
|
|
23
|
+
].join("\n");
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=prompts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompts.js","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,iBAAiB,CAAC,KAAkB;IAClD,OAAO;QACL,2DAA2D;QAC3D,8EAA8E;QAC9E,qDAAqD;QACrD,EAAE;QACF,iBAAiB,KAAK,CAAC,SAAS,EAAE;QAClC,UAAU,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;QACvC,mBAAmB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;QAChD,WAAW,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE;KAC1C,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,KAAkB;IAClD,OAAO;QACL,sEAAsE;QACtE,8FAA8F;QAC9F,0EAA0E;QAC1E,EAAE;QACF,iBAAiB,KAAK,CAAC,SAAS,EAAE;QAClC,UAAU,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;QACvC,mBAAmB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;QAChD,8BAA8B,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE;KAC7D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC"}
|
package/dist/reliable.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { guardToolCalls } from "./guard.js";
|
|
2
|
+
export async function reliableToolCalls(input) {
|
|
3
|
+
const mode = input.mode ?? "repair";
|
|
4
|
+
const first = await guardToolCalls(input);
|
|
5
|
+
const shouldRepair = Boolean(input.repair) && (mode === "review" || (mode === "repair" && !first.ok));
|
|
6
|
+
if (!shouldRepair)
|
|
7
|
+
return { ...first, repaired: false, original: input.calls };
|
|
8
|
+
const repairedCalls = await input.repair({
|
|
9
|
+
userInput: input.userInput,
|
|
10
|
+
tools: input.tools,
|
|
11
|
+
calls: input.calls,
|
|
12
|
+
issues: first.issues,
|
|
13
|
+
});
|
|
14
|
+
const second = await guardToolCalls({ ...input, calls: normalizeCalls(repairedCalls) });
|
|
15
|
+
return second.ok
|
|
16
|
+
? { ...second, repaired: true, original: input.calls }
|
|
17
|
+
: { ...first, repaired: false, original: input.calls };
|
|
18
|
+
}
|
|
19
|
+
function normalizeCalls(calls) {
|
|
20
|
+
return calls.filter((call) => call && typeof call.tool === "string" && isRecord(call.args));
|
|
21
|
+
}
|
|
22
|
+
function isRecord(value) {
|
|
23
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=reliable.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reliable.js","sourceRoot":"","sources":["../src/reliable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAG5C,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,KAA6B;IACnE,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,IAAI,QAAQ,CAAC;IACpC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,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC"}
|
package/dist/schema.d.ts
ADDED
package/dist/schema.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
export function validateSchema(schema, value, path = "$") {
|
|
2
|
+
if (!schema)
|
|
3
|
+
return [];
|
|
4
|
+
const issues = [];
|
|
5
|
+
if (schema.type && !matchesType(schema.type, value)) {
|
|
6
|
+
return [{
|
|
7
|
+
kind: typeIssueKind(schema.type),
|
|
8
|
+
path,
|
|
9
|
+
message: "invalid type",
|
|
10
|
+
expected: schema.type,
|
|
11
|
+
actual: value,
|
|
12
|
+
}];
|
|
13
|
+
}
|
|
14
|
+
if (schema.enum && !schema.enum.includes(value)) {
|
|
15
|
+
issues.push({ kind: "schema", path, message: "not in enum", expected: schema.enum, actual: value });
|
|
16
|
+
}
|
|
17
|
+
if (isObjectSchema(schema))
|
|
18
|
+
issues.push(...validateObject(schema, value, path));
|
|
19
|
+
if (schema.type === "array" && Array.isArray(value) && schema.items) {
|
|
20
|
+
value.forEach((item, index) => issues.push(...validateSchema(schema.items, item, `${path}[${index}]`)));
|
|
21
|
+
}
|
|
22
|
+
return issues;
|
|
23
|
+
}
|
|
24
|
+
function validateObject(schema, value, path) {
|
|
25
|
+
if (!isRecord(value))
|
|
26
|
+
return [{ kind: "type", path, message: "must be object", expected: "object", actual: value }];
|
|
27
|
+
const issues = [];
|
|
28
|
+
const properties = schema.properties ?? {};
|
|
29
|
+
for (const key of schema.required ?? []) {
|
|
30
|
+
if (!(key in value))
|
|
31
|
+
issues.push({ kind: "schema", path: `${path}.${key}`, message: "is required" });
|
|
32
|
+
}
|
|
33
|
+
for (const [key, property] of Object.entries(properties)) {
|
|
34
|
+
if (key in value)
|
|
35
|
+
issues.push(...validateSchema(property, value[key], `${path}.${key}`));
|
|
36
|
+
}
|
|
37
|
+
if (schema.additionalProperties === false) {
|
|
38
|
+
for (const key of Object.keys(value)) {
|
|
39
|
+
if (!(key in properties))
|
|
40
|
+
issues.push({ kind: "schema", path: `${path}.${key}`, message: "is not allowed" });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return issues;
|
|
44
|
+
}
|
|
45
|
+
function isObjectSchema(schema) {
|
|
46
|
+
return includesType(schema.type, "object") || Boolean(schema.properties);
|
|
47
|
+
}
|
|
48
|
+
function matchesType(type, value) {
|
|
49
|
+
const types = Array.isArray(type) ? type : [type];
|
|
50
|
+
return types.some((item) => matchesSingleType(normalizeType(item), value));
|
|
51
|
+
}
|
|
52
|
+
function matchesSingleType(type, value) {
|
|
53
|
+
if (type === "any")
|
|
54
|
+
return true;
|
|
55
|
+
if (type === "array")
|
|
56
|
+
return Array.isArray(value);
|
|
57
|
+
if (type === "integer")
|
|
58
|
+
return Number.isInteger(value);
|
|
59
|
+
if (type === "number")
|
|
60
|
+
return typeof value === "number";
|
|
61
|
+
if (type === "object")
|
|
62
|
+
return isRecord(value);
|
|
63
|
+
if (type === "null")
|
|
64
|
+
return value === null;
|
|
65
|
+
return typeof value === type;
|
|
66
|
+
}
|
|
67
|
+
function includesType(type, expected) {
|
|
68
|
+
return Array.isArray(type) ? type.includes(expected) : type === expected;
|
|
69
|
+
}
|
|
70
|
+
function normalizeType(type) {
|
|
71
|
+
const lowered = type.toLowerCase();
|
|
72
|
+
if (["dict", "hashmap", "map"].includes(lowered))
|
|
73
|
+
return "object";
|
|
74
|
+
if (["str", "string"].includes(lowered))
|
|
75
|
+
return "string";
|
|
76
|
+
if (["bool", "boolean"].includes(lowered))
|
|
77
|
+
return "boolean";
|
|
78
|
+
if (["int", "integer", "long"].includes(lowered))
|
|
79
|
+
return "integer";
|
|
80
|
+
if (["float", "double", "number"].includes(lowered))
|
|
81
|
+
return "number";
|
|
82
|
+
if (["list", "array"].includes(lowered))
|
|
83
|
+
return "array";
|
|
84
|
+
if (lowered === "any" || lowered === "")
|
|
85
|
+
return "any";
|
|
86
|
+
return lowered;
|
|
87
|
+
}
|
|
88
|
+
function typeIssueKind(type) {
|
|
89
|
+
return Array.isArray(type) && type.includes("null") ? "schema" : "type";
|
|
90
|
+
}
|
|
91
|
+
function isRecord(value) {
|
|
92
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,cAAc,CAAC,MAA8B,EAAE,KAAc,EAAE,IAAI,GAAG,GAAG;IACvF,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,CAAC;IACvB,MAAM,MAAM,GAAoB,EAAE,CAAC;IACnC,IAAI,MAAM,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,CAAC;QACpD,OAAO,CAAC;gBACN,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC;gBAChC,IAAI;gBACJ,OAAO,EAAE,cAAc;gBACvB,QAAQ,EAAE,MAAM,CAAC,IAAI;gBACrB,MAAM,EAAE,KAAK;aACd,CAAC,CAAC;IACL,CAAC;IACD,IAAI,MAAM,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAChD,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;IACtG,CAAC;IACD,IAAI,cAAc,CAAC,MAAM,CAAC;QAAE,MAAM,CAAC,IAAI,CAAC,GAAG,cAAc,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;IAChF,IAAI,MAAM,CAAC,IAAI,KAAK,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AAC,IAAuB;IAC5C,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC;AAC1E,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
export type JsonSchema = {
|
|
2
|
+
type?: string | string[];
|
|
3
|
+
properties?: Record<string, JsonSchema>;
|
|
4
|
+
required?: string[];
|
|
5
|
+
enum?: unknown[];
|
|
6
|
+
items?: JsonSchema;
|
|
7
|
+
additionalProperties?: boolean;
|
|
8
|
+
};
|
|
9
|
+
export type ToolDefinition = {
|
|
10
|
+
name: string;
|
|
11
|
+
description?: string;
|
|
12
|
+
schema?: JsonSchema;
|
|
13
|
+
validate?: SemanticValidator;
|
|
14
|
+
};
|
|
15
|
+
export type ToolCall = {
|
|
16
|
+
tool: string;
|
|
17
|
+
args: Record<string, unknown>;
|
|
18
|
+
};
|
|
19
|
+
export type IssueKind = "unknown_tool" | "irrelevant_call" | "missing_call" | "schema" | "type" | "semantic";
|
|
20
|
+
export type ToolCallIssue = {
|
|
21
|
+
kind: IssueKind;
|
|
22
|
+
path: string;
|
|
23
|
+
message: string;
|
|
24
|
+
tool?: string;
|
|
25
|
+
expected?: unknown;
|
|
26
|
+
actual?: unknown;
|
|
27
|
+
};
|
|
28
|
+
export type GuardPolicy = {
|
|
29
|
+
expected?: "any" | "none" | "some";
|
|
30
|
+
allowUnknownTools?: boolean;
|
|
31
|
+
};
|
|
32
|
+
export type GuardResult = {
|
|
33
|
+
ok: boolean;
|
|
34
|
+
calls: ToolCall[];
|
|
35
|
+
issues: ToolCallIssue[];
|
|
36
|
+
};
|
|
37
|
+
export type SemanticValidator = (input: {
|
|
38
|
+
call: ToolCall;
|
|
39
|
+
tool: ToolDefinition;
|
|
40
|
+
}) => Promise<ToolCallIssue[]> | ToolCallIssue[];
|
|
41
|
+
export type RepairInput = {
|
|
42
|
+
userInput: string;
|
|
43
|
+
tools: ToolDefinition[];
|
|
44
|
+
calls: ToolCall[];
|
|
45
|
+
issues: ToolCallIssue[];
|
|
46
|
+
};
|
|
47
|
+
export type RepairFunction = (input: RepairInput) => Promise<ToolCall[]> | ToolCall[];
|
|
48
|
+
export type ReliableToolCallsInput = {
|
|
49
|
+
userInput: string;
|
|
50
|
+
tools: ToolDefinition[];
|
|
51
|
+
calls: ToolCall[];
|
|
52
|
+
policy?: GuardPolicy;
|
|
53
|
+
repair?: RepairFunction;
|
|
54
|
+
mode?: "guard" | "repair" | "review";
|
|
55
|
+
};
|
|
56
|
+
export type ReliableToolCallsResult = GuardResult & {
|
|
57
|
+
repaired: boolean;
|
|
58
|
+
original: ToolCall[];
|
|
59
|
+
};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
|
package/docs/banner.svg
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="1400" height="520" viewBox="0 0 1400 520" role="img" aria-labelledby="title desc">
|
|
2
|
+
<title id="title">BetterCall banner</title>
|
|
3
|
+
<desc id="desc">BetterCall is a one-line wrapper that boosts BFCL tool-call accuracy from 81.3 percent to 91.3 percent.</desc>
|
|
4
|
+
<defs>
|
|
5
|
+
<linearGradient id="background" x1="0" y1="0" x2="1" y2="1">
|
|
6
|
+
<stop offset="0" stop-color="#07111f"/>
|
|
7
|
+
<stop offset="0.52" stop-color="#102640"/>
|
|
8
|
+
<stop offset="1" stop-color="#10291f"/>
|
|
9
|
+
</linearGradient>
|
|
10
|
+
<linearGradient id="accent" x1="0" y1="0" x2="1" y2="0">
|
|
11
|
+
<stop offset="0" stop-color="#67d4ff"/>
|
|
12
|
+
<stop offset="0.48" stop-color="#9be47f"/>
|
|
13
|
+
<stop offset="1" stop-color="#ffd36a"/>
|
|
14
|
+
</linearGradient>
|
|
15
|
+
</defs>
|
|
16
|
+
|
|
17
|
+
<rect width="1400" height="520" fill="url(#background)"/>
|
|
18
|
+
<circle cx="1170" cy="100" r="230" fill="#67d4ff" opacity="0.06"/>
|
|
19
|
+
<circle cx="210" cy="450" r="210" fill="#9be47f" opacity="0.05"/>
|
|
20
|
+
<path d="M110 374 C 302 236, 478 388, 672 274 S 970 156, 1278 244" fill="none" stroke="#ffffff" stroke-opacity="0.08" stroke-width="58" stroke-linecap="round"/>
|
|
21
|
+
<path d="M96 86 H1304" stroke="#ffffff" stroke-opacity="0.10"/>
|
|
22
|
+
<path d="M96 434 H1304" stroke="#ffffff" stroke-opacity="0.10"/>
|
|
23
|
+
|
|
24
|
+
<g transform="translate(112 112)">
|
|
25
|
+
<text x="0" y="80" font-family="Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif" font-size="78" font-weight="800" fill="#f8fbff">BetterCall</text>
|
|
26
|
+
<rect x="4" y="116" width="430" height="8" rx="4" fill="url(#accent)"/>
|
|
27
|
+
<text x="0" y="186" font-family="Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif" font-size="34" font-weight="670" fill="#dcecff">One-line wrapper. BFCL tool-call accuracy: 81.3% → 91.3%.</text>
|
|
28
|
+
</g>
|
|
29
|
+
</svg>
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@botbotgo/better-call",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "LLM tool-call reliability layer.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+ssh://git@github.com/botbotgo/better-call.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/botbotgo/better-call#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/botbotgo/better-call/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"llm",
|
|
17
|
+
"agents",
|
|
18
|
+
"tool-calling",
|
|
19
|
+
"function-calling",
|
|
20
|
+
"guardrails",
|
|
21
|
+
"reliability"
|
|
22
|
+
],
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"dist",
|
|
31
|
+
"benchmarks",
|
|
32
|
+
"scripts",
|
|
33
|
+
"docs/banner.svg",
|
|
34
|
+
"README.md",
|
|
35
|
+
"NOTICE",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsc -p tsconfig.json",
|
|
40
|
+
"bench:bfcl": "npm run build && node scripts/bench-bfcl.mjs",
|
|
41
|
+
"release:pack": "npm pack --dry-run",
|
|
42
|
+
"release:publish": "npm publish --access public",
|
|
43
|
+
"test": "npm run build && node --test test/*.test.mjs",
|
|
44
|
+
"prepack": "npm run test"
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@types/node": "^24.10.1",
|
|
48
|
+
"typescript": "^5.9.3"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { reliableToolCalls } from "../dist/index.js";
|
|
5
|
+
|
|
6
|
+
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
7
|
+
const summaryPath = resolve(root, "benchmarks/bfcl-targeted-summary.json");
|
|
8
|
+
const summary = JSON.parse(await readFile(summaryPath, "utf8"));
|
|
9
|
+
|
|
10
|
+
await runSanityCases();
|
|
11
|
+
|
|
12
|
+
console.log(`# ${summary.name}`);
|
|
13
|
+
console.log("");
|
|
14
|
+
console.log(`Source: ${summary.source}`);
|
|
15
|
+
console.log(`Official BFCL: ${summary.officialBenchmark}`);
|
|
16
|
+
console.log(`Official reproduction: commit ${summary.officialReproduction.commit}, ${summary.officialReproduction.pythonPackage}`);
|
|
17
|
+
console.log("");
|
|
18
|
+
printTable(["Model", "Raw", "BetterCall", "Lift"], summary.rows.map(formatRow));
|
|
19
|
+
console.log("");
|
|
20
|
+
console.log("## Irrelevance");
|
|
21
|
+
console.log("");
|
|
22
|
+
printTable(["Model", "Raw", "BetterCall"], summary.irrelevance.map(formatIrrelevanceRow));
|
|
23
|
+
|
|
24
|
+
function formatRow(row) {
|
|
25
|
+
const raw = percent(row.rawCorrect, row.total);
|
|
26
|
+
const better = percent(row.betterCorrect, row.total);
|
|
27
|
+
return [row.model, raw, better, `${signed((row.betterCorrect - row.rawCorrect) * 100 / row.total)}pp`];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function formatIrrelevanceRow(row) {
|
|
31
|
+
return [row.model, percent(row.rawCorrect, row.total), percent(row.betterCorrect, row.total)];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function printTable(headers, rows) {
|
|
35
|
+
console.log(`| ${headers.join(" | ")} |`);
|
|
36
|
+
console.log(`| ${headers.map(() => "---").join(" | ")} |`);
|
|
37
|
+
for (const row of rows) console.log(`| ${row.join(" | ")} |`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function percent(correct, total) {
|
|
41
|
+
return `${(correct * 100 / total).toFixed(1)}%`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function signed(value) {
|
|
45
|
+
return `${value >= 0 ? "+" : ""}${value.toFixed(1)}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function runSanityCases() {
|
|
49
|
+
const tools = [
|
|
50
|
+
{
|
|
51
|
+
name: "stock_quote",
|
|
52
|
+
schema: {
|
|
53
|
+
type: "object",
|
|
54
|
+
properties: {
|
|
55
|
+
ticker: { type: "string" },
|
|
56
|
+
market: { type: "string", enum: ["US", "HK", "CN"] },
|
|
57
|
+
},
|
|
58
|
+
required: ["ticker", "market"],
|
|
59
|
+
additionalProperties: false,
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
];
|
|
63
|
+
const repaired = await reliableToolCalls({
|
|
64
|
+
userInput: "Get Apple stock in the US market.",
|
|
65
|
+
tools,
|
|
66
|
+
calls: [{ tool: "stock_price", args: { symbol: "Apple", market: "NASDAQ" } }],
|
|
67
|
+
repair: () => [{ tool: "stock_quote", args: { ticker: "AAPL", market: "US" } }],
|
|
68
|
+
});
|
|
69
|
+
if (!repaired.ok || !repaired.repaired) throw new Error("BetterCall repair sanity case failed.");
|
|
70
|
+
const irrelevant = await reliableToolCalls({
|
|
71
|
+
userInput: "Say hello without using tools.",
|
|
72
|
+
tools,
|
|
73
|
+
calls: [{ tool: "stock_quote", args: { ticker: "AAPL", market: "US" } }],
|
|
74
|
+
policy: { expected: "none" },
|
|
75
|
+
});
|
|
76
|
+
if (irrelevant.ok) throw new Error("BetterCall irrelevance sanity case failed.");
|
|
77
|
+
}
|