File size: 16,500 Bytes
79ebcf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
from typing import List, Union
from langchain_core.messages.ai import AIMessage
from langchain_core.messages.human import HumanMessage
from langchain_core.messages.chat import ChatMessage
from langchain_core.messages.system import SystemMessage
from langchain_core.messages.function import FunctionMessage
from langchain_core.messages.tool import ToolMessage
from langchain_core.prompts.chat import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    MessagesPlaceholder
)
from langchain_core.prompts.prompt import PromptTemplate
from langchain.prompts import HumanMessagePromptTemplate

class PersonalTemplate:
    def __init__(self):
        MessageTypes = Union[
            AIMessage, 
            HumanMessage, 
            ChatMessage, 
            SystemMessage, 
            FunctionMessage, 
            ToolMessage
        ]

        assistant_description = (
                            'Assistant is a friendly conversational model.\n'
                            '\n'
                            'Assistant is designed to be able to assist with a wide range of tasks, from '
                            'answering simple questions to providing in-depth explanations and '
                            'discussions on a wide range of topics. As a language model, Assistant is '
                            'able to generate human-like text based on the input it receives, allowing it '
                            'to engage in natural-sounding conversations and provide responses that are '
                            'coherent and relevant to the topic at hand.\n'
                            '\n'
                            'Assistant is constantly learning and improving, and its capabilities are '
                            'constantly evolving. It is able to process and understand large amounts of '
                            'text, and can use this knowledge to provide accurate and informative '
                            'responses to a wide range of questions. Additionally, Assistant is able to '
                            'generate its own text based on the input it receives, allowing it to engage '
                            'in discussions and provide explanations and descriptions on a wide range of '
                            'topics.\n'
                            '\n'
                            'Overall, Assistant is a powerful system that can help with a wide range of '
                            'tasks and provide valuable insights and information on a wide range of '
                            'topics. Whether you need help with a specific question or just want to have '
                            'a conversation about a particular topic, Assistant is here to assist.'
                            'Assistant always uses a tool when the question involves tax knowledge, legal entities, taxes, and related subjects.'
                            )

        tool_instructions = (
                            'TOOLS\n'
                            '------\n'
                            'Assistant can ask the user to use tools to look up information that may be '
                            'helpful in answering the users original question. '
                            'For common inquiries such as greetings, small talk, and simple, familiar questions, there\'s no need to use a tool.'
                            'The tools the human can '
                            'use are:\n'
                            '\n'
                            '{tools}\n'
                            '\n'
                            'RESPONSE FORMAT INSTRUCTIONS\n'
                            '----------------------------\n'
                            '\n'
                            'When responding to me, please output a response in one of two formats:\n'
                            '\n'
                            '**Option 1:**\n'
                            'Use this if you want the human to use a tool.\n'
                            'A response must be selected from the {tool_names} options; do not choose this response format if the tool is not listed among them.'
                            'Markdown code snippet formatted in the following schema:\n'
                            '\n'
                            '```json\n'
                            '{{\n'
                            '    "action": string, \\ The action to take. Must be one of {tool_names}\n'
                            '    "action_input": string \\ The input to the action\n'
                            '}}\n'
                            '```\n'
                            '\n'
                            '**Option #2:**\n'
                            'Use this if you want to respond directly to the human. Markdown code snippet '
                            'formatted in the following schema:\n'
                            '\n'
                            '```json\n'
                            '{{\n'
                            '    "action": "Final Answer",\n'
                            '    "action_input": string \\ You should put what you want to return to use '
                            'here\n'
                            '}}\n'
                            '```\n'
                            '\n'
                            'Keep the final answer concise and to the point.'
                            'The Final Answer always must be in portuguese'
                            '\n'
                            '\n'
                            "USER'S INPUT\n"
                            '--------------------\n'
                            "Here is the user's input (remember to respond with a markdown code snippet "
                            'of a json blob with a single action, and NOTHING else):\n'
                            '\n'
                            '{input}'
                            )

        prompt_messages = [
            SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], template=assistant_description)),
            MessagesPlaceholder(variable_name='chat_history', optional=True),
            HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input', 'tool_names', 'tools'], 
                                                            template=tool_instructions)),
            MessagesPlaceholder(variable_name='agent_scratchpad')
        ]

        self.chatbot_tributario_prompt = ChatPromptTemplate(
            input_variables=['agent_scratchpad', 'input', 'tool_names', 'tools'],
            input_types={
                'chat_history': List[MessageTypes],
                'agent_scratchpad': List[MessageTypes]
            },
            messages=prompt_messages
        )
        
        self.description_direito_tributario_tool = """
Esta ferramenta é um sistema avançado de assistência e consulta para questões relacionadas ao direito tributário de pessoas jurídicas. Desenvolvida para advogados, contadores, gestores financeiros e empresários, ela oferece informações detalhadas e análises específicas sobre legislação tributária, jurisprudência relevante, e orientações práticas para a gestão fiscal de empresas.

Os usuários podem utilizar esta ferramenta em uma variedade de contextos, como: 

1. **Planejamento Tributário**: Auxilia na identificação de estratégias legais para a redução da carga tributária, considerando a legislação atual e as particularidades do negócio.
2. **Resolução de Disputas Fiscais**: Fornece orientações sobre procedimentos e defesas em casos de litígios tributários, incluindo análises de casos semelhantes e interpretações de leis.
3. **Compliance Fiscal**: Ajuda na compreensão e cumprimento das obrigações tributárias, evitando penalidades e multas por descumprimento de normas fiscais.
4. **Atualizações Legislativas**: Mantém os usuários atualizados sobre as mais recentes alterações na legislação tributária, impactando diretamente a gestão fiscal das empresas.

A ferramenta é intuitiva e adaptada para atender às necessidades específicas de cada usuário, com uma interface amigável e recursos de busca avançada. Também oferece a possibilidade de consultas personalizadas com especialistas na área.

Para utilizar esta ferramenta, o input deve ser uma consulta de busca, formulada de maneira clara e específica, relacionada a questões tributárias de pessoas jurídicas.
"""

        self.description_direito_tributario_tool2 = """This tool is an advanced assistance system for corporate tax law brazilian queries. Designed for lawyers, accountants, financial managers, and business owners, it provides detailed information and specific analyses on tax legislation, relevant case law, and practical guidance for corporate tax management.

The tool can be used in various contexts, specifically related to corporate tax law, including:

1. **Tax Planning**: Assists in identifying legal strategies to minimize tax liabilities, tailored to current laws and business specifics.
2. **Tax Dispute Resolution**: Offers guidance on procedures and defenses in tax litigation, with case analyses and law interpretations.
3. **Tax Compliance**: Aids in understanding and fulfilling tax obligations to avoid penalties for non-compliance.
4. **Legislative Information**: Provides comprehensive insights into tax laws, covering a range of topics from the intricacies of various taxes, legal scenarios requiring tax law knowledge, and essential information about different types of taxes and their implications.

The tool is user-friendly with an intuitive interface and advanced search capabilities. Use this tool by submitting clear, specific search queries related to corporate tax law issues.
"""
        self.chatbot_tributario_prompt_react = PromptTemplate.from_template(template='''Assistant is an AI.

Assistant is designed to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant generates human-like text based on the input it receives, allowing it to engage in conversations and provide coherent and relevant responses.

Assistant is constantly learning and improving. It processes and understands large amounts of text and can use this knowledge to provide accurate and informative responses. Additionally, Assistant generates its own text based on the input it receives, engaging in discussions and providing explanations on various topics.

Overall, Assistant is a powerful tool for a wide range of tasks, offering valuable insights and information.

TOOLS:
------

Assistant has access to the following tools:

{tools}

Do not use a tool if Action Input is not related to the tool.
Use a tool when the question involves tax knowledge, legal entities, taxes, and related subjects
Use the tool only use this if you want the human to use a tool to answer questions about brazilian tax law and legal entities. 
For common inquiries such as greetings, small talk, and simple, familiar questions, there\'s no need to use a tool.

To use a tool, please use the following format:

```
Thought: Do I need to use a tool? Yes
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
```

When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:

```
Thought: Do I need to use a tool? No
Final Answer: [your response here]
```

Keep the Final Answer concise and to the point.
The Final Answer always must be in portuguese

Begin!

Previous conversation history:
{chat_history}

Input: {input}
Thought:{agent_scratchpad}''')
        
        self.retriever_prompt = PromptTemplate.from_template("""Use the following pieces of information to answer the user's question.
If you don't know the answer, just say that you don't know, don't try to make up an answer.
Context: {context}
Question: {question}
Answer the question in portuguese.
Only return the helpful answer below and nothing else.
Helpful answer:
""") 
        self.chatbot_tributario_prompt_react2 = PromptTemplate.from_template(template="""**Assistant is an AI.**

Assistant is designed to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant generates human-like text based on the input it receives, allowing it to engage in conversations and provide coherent and relevant responses.

Assistant is constantly learning and improving. It processes and understands large amounts of text and can use this knowledge to provide accurate and informative responses. Additionally, Assistant generates its own text based on the input it receives, engaging in discussions and providing explanations on various topics.

Overall, Assistant is a powerful tool for a wide range of tasks, offering valuable insights and information.

**Previous Conversation History:**
This section includes a record of the user's and Assistant's past interactions. It provides context and continuity, helping the Assistant understand the background and flow of the conversation, ensuring more relevant and informed responses.

{chat_history}

Answer the following questions as best you can. You have access to the following tools:

{tools}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do and if you need to use a tool or no
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat 5 times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: {input}
Thought:{agent_scratchpad}
""" )
        
        self.chatbot_tributario_prompt_react2 = PromptTemplate.from_template(template='''You are a Assistant.

Assistant is designed as a versatile and knowledgeable companion, adept at engaging in conversations across a broad range of topics. It is capable of processing and comprehending vast amounts of text, which it uses to provide accurate and informative responses to a wide spectrum of inquiries.

Assistant is well-equipped for both specific queries and general discussions, making it a reliable source of assistance for any user. Its conversational ability is extensive, enabling it to adapt its tone and style to fit the context of the discussion, ensuring that interactions are both natural and engaging.

In addition to its conversational skills, the Assistant is also equipped with a variety of tools that enhance its ability to respond effectively and accurately. These tools augment the Assistant capabilities, making it more efficient in providing relevant and context-aware responses.

Users can interact with the Assistant by posing questions or initiating conversations on topics of interest. The Assistant utilizes its array of skills and tools to provide the best possible assistance, focusing on delivering coherent, relevant, and engaging responses to enhance the user experience.

TOOLS:
------

The Assistant has access to the following tools:

{tools}

Use a tool only if the Action Input is directly related to the tool. There are two distinct formats to follow based on the Input:

1. **Using a Tool**: When a tool is necessary, utilize this format:
Use this if you want the human to use a tool.

```
Thought: Do I need to use a tool? Yes
Action: [Select an appropriate action from {tool_names}]
Action Input: [Provide the necessary input for the action]
Observation: [Note the result or outcome of the action]
```
A response must be selected from the {tool_names} options; do not choose this response format if the tool is not listed among them.
After making an observation or if an action was taken, consider whether a direct response to the user is now appropriate.

2. **Direct Response**: When you are ready to provide a response, or if a tool is not required, switch to this format:
Use this if you want to respond directly to the human

```
Thought: Do I need to use a tool? No
Final Answer: [Provide your direct response to the user here]
```

Keep the Final Answer concise and to the point.
The Final Answer always must be in portuguese

Begin!

Previous conversation history:
{chat_history}

Input: {input}
Thought:{agent_scratchpad}''')