File size: 6,520 Bytes
ec8f374
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
"""
Tool Use Generator Module

Generates training data for teaching LLMs to use tools and functions.
"""

import json
from typing import List, Dict, Any, Optional


class ToolUseGenerator:
    """Generate tool use training data for function calling."""

    def __init__(self, tools: Optional[List[Dict]] = None):
        """
        Initialize tool use generator.

        Args:
            tools: List of tool definitions
        """
        self.tools = tools or self._get_default_financial_tools()

    def _get_default_financial_tools(self) -> List[Dict]:
        """Get default financial tools."""
        return [
            {
                "name": "get_market_data",
                "description": "Get current market data for a stock",
                "parameters": {
                    "symbol": "string",
                    "data_type": "string (price, volume, market_cap)"
                },
                "returns": "dict"
            },
            {
                "name": "calculate_compound_interest",
                "description": "Calculate compound interest",
                "parameters": {
                    "principal": "float",
                    "rate": "float",
                    "time": "float",
                    "frequency": "int"
                },
                "returns": "float"
            },
            {
                "name": "get_portfolio_allocation",
                "description": "Get current portfolio allocation",
                "parameters": {
                    "user_id": "string"
                },
                "returns": "dict"
            },
            {
                "name": "calculate_retirement_needs",
                "description": "Calculate retirement savings needs",
                "parameters": {
                    "current_age": "int",
                    "retirement_age": "int",
                    "current_savings": "float",
                    "annual_contribution": "float"
                },
                "returns": "dict"
            }
        ]

    def generate_tool_use_examples(
        self,
        num_examples: int = 10,
        complexity: str = "single"
    ) -> List[Dict[str, Any]]:
        """
        Generate tool use training examples.

        Args:
            num_examples: Number of examples to generate
            complexity: "single" or "multi" (multi-step tool chains)

        Returns:
            List of tool use examples
        """
        examples = []

        for _ in range(num_examples):
            if complexity == "single":
                example = self._generate_single_tool_example()
            else:
                example = self._generate_multi_tool_example()

            if example:
                examples.append(example)

        return examples

    def _generate_single_tool_example(self) -> Dict[str, Any]:
        """Generate example with single tool call."""
        import random

        tool = random.choice(self.tools)

        # Create example based on tool
        if tool["name"] == "get_market_data":
            return {
                "instruction": "What is the current price of Apple stock?",
                "input": "",
                "output": "I'll check the current market data for Apple stock.",
                "tool_calls": [
                    {
                        "tool": "get_market_data",
                        "parameters": {
                            "symbol": "AAPL",
                            "data_type": "price"
                        }
                    }
                ]
            }
        elif tool["name"] == "calculate_compound_interest":
            return {
                "instruction": "If I invest $10,000 at 5% interest compounded quarterly, how much will I have in 10 years?",
                "input": "",
                "output": "I'll calculate that for you using compound interest formula.",
                "tool_calls": [
                    {
                        "tool": "calculate_compound_interest",
                        "parameters": {
                            "principal": 10000,
                            "rate": 0.05,
                            "time": 10,
                            "frequency": 4
                        }
                    }
                ]
            }

        # Generic example
        return {
            "instruction": f"Use the {tool['name']} tool",
            "input": "",
            "output": f"I'll use {tool['name']} to help with that.",
            "tool_calls": [{"tool": tool["name"], "parameters": {}}]
        }

    def _generate_multi_tool_example(self) -> Dict[str, Any]:
        """Generate example with multiple tool calls (chain)."""
        return {
            "instruction": "Should I rebalance my portfolio given current market conditions?",
            "input": "",
            "output": "Let me check your portfolio and current market data to provide a recommendation.",
            "tool_calls": [
                {
                    "tool": "get_portfolio_allocation",
                    "parameters": {"user_id": "user123"}
                },
                {
                    "tool": "get_market_data",
                    "parameters": {"symbol": "SPY", "data_type": "price"}
                }
            ],
            "reasoning": "First get the user's current portfolio allocation, then check market conditions, and finally provide rebalancing advice."
        }

    def add_custom_tool(self, tool: Dict[str, Any]) -> None:
        """
        Add a custom tool definition.

        Args:
            tool: Tool definition dict
        """
        required_keys = ["name", "description", "parameters", "returns"]
        if not all(key in tool for key in required_keys):
            raise ValueError(f"Tool must have keys: {required_keys}")

        self.tools.append(tool)

    def get_tools_schema(self) -> List[Dict]:
        """Get OpenAI-compatible tools schema."""
        schema = []

        for tool in self.tools:
            schema.append({
                "type": "function",
                "function": {
                    "name": tool["name"],
                    "description": tool["description"],
                    "parameters": {
                        "type": "object",
                        "properties": tool["parameters"],
                        "required": list(tool["parameters"].keys())
                    }
                }
            })

        return schema