Parse function/tool calls from LLM output that may be in different formats. Your parser should:
- Detect JSON format and extract function name + arguments
- Detect XML-like tags
- Parse natural language patterns like 'Call X with Y=Z'
- Return confidence score based on parsing certainty
Constraints:
- Handle malformed inputs gracefully
- Return None for unparseable outputs
- Arguments should always be a dictionary
- Confidence: 1.0 for JSON, 0.8 for XML, 0.6 for NL
Examples
Example 1:
Input:
parse_function_call('{"function": "search", "arguments": {"query": "python"}}')Output:
{'function': 'search', 'arguments': {'query': 'python'}, 'confidence': 1.0}Explanation: Valid JSON format detected, full confidence
Example 2:
Input:
parse_function_call('Call calculator with x=5, y=10')Output:
{'function': 'calculator', 'arguments': {'x': '5', 'y': '10'}, 'confidence': 0.6}Explanation: Natural language pattern matched, lower confidence due to string values
Starter Code
import json
import re
def parse_function_call(llm_output):
"""
Parse function calls from LLM output.
Handles both JSON and natural language formats.
Expected formats:
1. JSON: {"function": "name", "arguments": {...}}
2. XML: <function>name</function><args>{...}</args>
3. NL: Call function_name with arg1=value1
Returns: dict with 'function', 'arguments', 'confidence' (0-1)
"""
# Your implementation here
passPython3
ReadyLines: 1Characters: 0
Ready