llm-tool-parser
A flexible, multi-language parser for extracting tool calls from LLM-generated text. Built with a single ANTLR4 grammar that generates native parsers for Rust, Swift, and Python.
Problem
LLMs generate tool calls in wildly different formats depending on the provider, model, and prompt:
| Provider / Model |
Format |
Example |
| OpenAI (GPT-4o) |
Inline JSON |
{"name":"get_weather","arguments":{...}} |
| Anthropic (Claude) |
XML-like tags |
<tool_use>{...}</tool_use> |
| Meta Llama 3.1 |
JSON with <|python_tag|> |
<|python_tag|>{"name":...} |
| Meta Llama 3.2+ |
Pythonic |
[get_weather(city='SF')] |
| Mistral |
Tagged array |
[TOOL_CALLS][{...}] |
| DeepSeek |
Code fence JSON |
json\n{...}\n |
| Google Gemini |
JSON-like |
{...} or ` blocks |
| Qwen3 |
XML tags |
<tool_calls>...</tool_calls> |
| FunctionGemma |
Custom tags |
<start_function_call>...<end_function_call> |
Building a separate parser for each format is expensive and brittle. This project provides a single ANTLR4 grammar that recognizes all common formats, with generated parsers for Rust, Swift, and Python.
Quick Start
Rust
[dependencies]
llm_tool_parser = { git = "https://github.com/your-org/llm-tool-parser.git" }
use llm_tool_parser::ToolCallParser;
fn main() {
let parser = ToolCallParser::new();
let text = r#"{"name": "get_weather", "arguments": {"location": "SF", "unit": "celsius"}}"#;
let result = parser.parse(text);
for call in result.tool_calls {
println!("Tool: {}", call.name);
println!("Args: {}", call.arguments);
}
}
Swift (SwiftPM)
// Package.swift
dependencies: [
.package(url: "https://github.com/your-org/llm-tool-parser.git", branch: "main")
]
import ToolParserLLM
let parser = ToolCallParser()
let text = #"[{"name": "get_weather", "arguments": {"location": "SF", "unit": "celsius"}}]"#
let result = parser.parse(text)
for call in result.toolCalls {
print("Tool: \(call.name)")
print("Args: \(call.arguments)")
}
Python
pip install -e .
from llm_tool_parser import ToolCallParser
parser = ToolCallParser()
text = '{"name": "get_weather", "arguments": {"location": "SF", "unit": "celsius"}}'
result = parser.parse(text)
for call in result.tool_calls:
print(f"Tool: {call.name}")
print(f"Args: {call.arguments}")
Installation
Rust
Option 1: From Git
[dependencies]
llm_tool_parser = { git = "https://github.com/your-org/llm-tool-parser.git" }
Option 2: Local path (for development)
[dependencies]
llm_tool_parser = { path = "../llm-tool-parser" }
Build and test from the repo root:
cargo build
cargo test --workspace
Swift
Option 1: Swift Package Manager
// Package.swift
dependencies: [
.package(url: "https://github.com/your-org/llm-tool-parser.git", branch: "main")
]
Option 2: Local path (for development)
dependencies: [
.package(path: "../llm-tool-parser")
]
Option 3: Xcode project
- File → Add Package Dependency
- Enter:
https://github.com/your-org/llm-tool-parser.git
Note: Requires the Antlr4 runtime, downloaded automatically by SwiftPM.
Python
From source
git clone https://github.com/your-org/llm-tool-parser.git
cd llm-tool-parser/python
pip install -e .
Usage Examples
Rust
use llm_tool_parser::ToolCallParser;
fn main() {
let parser = ToolCallParser::new();
// Parse text with mixed content
let text = r#"I'll check the weather for you.
[get_weather(city="San Francisco", unit="celsius"), get_time()]
Let me also search for the latest AI news.
"#;
let result: ParseResult = parser.parse(text);
println!("Has tool calls: {}", result.has_tool_calls);
println!("Plain text: {}", result.plain_text);
for call in &result.tool_calls {
println!("\nTool: {}", call.name);
println!("Args: {:?}", call.arguments);
}
}
Swift
import ToolParserLLM
let parser = ToolCallParser()
let text = """
I'll check the weather and time for you.
<tool_use>
{"name": "get_weather", "arguments": {"city": "Paris", "unit": "celsius"}}
</tool_use>
<tool_use>
{"name": "get_time", "arguments": {}}
</tool_use>
"""
let result = parser.parse(text)
print("Has tool calls: \\(result.hasToolCalls)")
print("Plain text: \\(result.plainText)")
for call in result.toolCalls {
print("\\nTool: \\(call.name)")
print("Args: \\(call.arguments)")
}
Python
from llm_tool_parser import ToolCallParser
parser = ToolCallParser()
# Parse text with multiple tool calls
text = """
I'll help you search and get the weather.
```json
{"name": "search", "arguments": {"query": "AI news"}}
{"name": "get_weather", "arguments": {"city": "San Francisco", "unit": "fahrenheit"}}
"""
result = parser.parse(text)
print(f"Has tool calls: {result.has_tool_calls}")
print(f"Plain text: {result.plain_text}")
for call in result.tool_calls:
print(f"\nTool: {call.name}")
print(f"Args: {call.arguments}")
## Supported Formats
### 1. Bare JSON
```json
{"name": "get_weather", "arguments": {"location": "San Francisco"}}
2. JSON Arrays
[
{"name": "get_weather", "arguments": {"location": "SF"}},
{"name": "get_time", "arguments": {}}
]
3. Code-Fenced JSON
```json
{"name": "search", "arguments": {"query": "AI"}}
### 4. XML-Style Tags (Anthropic Claude)
```xml
<tool_use>
{"name": "search", "arguments": {"query": "AI news", "filters": {"type": "news"}}}
</tool_use>
<tool_calls>
{"name": "get_weather", "arguments": {"city": "Paris", "unit": "celsius"}}
{"name": "get_time", "arguments": {}}
</tool_calls>
5. Tagged Arrays (Mistral)
[TOOL_CALLS]
[
{"name": "add", "arguments": {"a": 3.5, "b": 4.0}}
]
6. Pythonic (Meta Llama 3.2+, Olmo 3)
[get_weather(city="San Francisco", unit="celsius")]
[get_weather(city="Paris"), get_time()]
[utils.database.query(sql="SELECT * FROM users")]
7. Prefixed JSON (Meta Llama 3.1)
<|python_tag|>{"name": "get_weather", "arguments": {"location": "SF"}}
<|tool|>{"name": "search", "arguments": {"q": "AI"}}
8. Mixed Content
Text before and after tool calls is captured separately:
Let me look that up for you.
{"name": "search", "arguments": {"query": "AI"}}
That's all.
Result:
tool_calls: [ToolCall(name="search", arguments={...})]
text_segments: ["Let me look that up for you.", "That's all."]
API Reference
Rust
pub struct ToolCallParser {
pub fn new() -> Self;
pub fn parse(&self, text: &str) -> ParseResult;
}
pub struct ParseResult {
pub tool_calls: Vec<ToolCall>,
pub text_segments: Vec<String>,
pub fn has_tool_calls(&self) -> bool,
pub fn plain_text(&self) -> String,
}
pub struct ToolCall {
pub name: String,
pub arguments: serde_json::Value,
pub span: Option<(usize, usize)>,
}
Swift
public final class ToolCallParser {
public init()
public func parse(_ text: String) -> ParseResult
}
public struct ParseResult {
public let toolCalls: [ToolCall]
public let textSegments: [String]
public var hasToolCalls: Bool { get }
public var plainText: String { get }
}
public struct ToolCall {
public let name: String
public let arguments: [String: AnyCodable]
public let span: Range<String.Index>?
}
Python
class ToolCallParser:
def __init__(self, use_antlr4: bool = True, recover: bool = True, max_depth: int = 32)
def parse(self, text: str) -> ParseResult:
...
@dataclass
class ToolCall:
name: str
arguments: dict[str, Any]
span: Optional[tuple[int, int]]
@dataclass
class ParseResult:
tool_calls: list[ToolCall]
text_segments: list[str]
@property
def has_tool_calls(self) -> bool: ...
@property
def plain_text(self) -> str: ...
Architecture
┌────────────────────────────────────┐
│ LLM Raw Output (text) │
└──────────────┬─────────────────────┘
│
┌─────────▼─────────┐
│ ToolCallsParser │ ← ANTLR4-generated, native per language
│ (Rust/Swift/Py) │
└─────────┬─────────┘
│
┌───────┴───────┐
▼ ▼
ToolCall[] Text[]
(structured) (non-tool content)
Development
Regenerating Parsers
After modifying grammars/ToolCalls.g4, regenerate the parsers:
# Generate all targets
./scripts/generate-parsers.sh --all
# Generate only Python
./scripts/generate-parsers.sh --python
# Generate only Swift
./scripts/generate-parsers.sh --swift
Requirements
- Java 17+ (for ANTLR4 code generation only — not needed at runtime)
- Rust 1.70+ (for Rust target)
- Swift 5.9+ (for Swift target)
- Python 3.9+ (for Python target)
macOS (Homebrew)
# Install Java and ANTLR4
brew install openjdk@17 antlr
# Or install Java and set JAVA_HOME
export JAVA_HOME=/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home
Testing
All three language parsers are tested against a shared corpus of 20 fixtures
covering every supported format and edge case. Tests live in two layers:
- Unit tests: format-specific tests in each language's native test suite.
- Corpus tests: each language's parser is driven by the same JSON fixture
files at
test/fixtures/, ensuring cross-language consistency.
# Rust (from repo root)
cargo test --manifest-path rust/Cargo.toml
# Swift (from repo root)
cd swift && swift test
# Python (from repo root)
python3 test_integration.py
Test fixtures are derived from real LLM outputs across providers (see docs/02_llm_tool_call_formats.md). After grammar changes, use
scripts/generate-parsers.sh --all and re-run all three suites.
License
MIT