File size: 6,966 Bytes
2854813
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8507fc0
2854813
 
ea5dd9a
2854813
 
 
 
 
 
 
 
a082340
2854813
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8507fc0
 
2854813
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ede8a06
 
 
 
2854813
 
 
 
 
9a919aa
2854813
 
 
ede8a06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2854813
 
 
 
ede8a06
2854813
 
 
 
 
 
ede8a06
 
 
 
 
2854813
 
 
 
 
 
 
 
ede8a06
2854813
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8507fc0
 
 
 
 
 
ede8a06
 
 
2854813
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""app.py

Smolagents agent given an SQL tool over a SQLite database built with data files 
from the Internation Consortium of Investigative Journalism (ICIJ.org).

Agentic framework:
    - smolagents

Database:
    - SQLite

Generation:
    - Mistral

:author: Didier Guillevic
:date: 2025-01-12
"""

import gradio as gr
import icij_utils
import sqlalchemy
import smolagents
import os
import pathlib

#
# Init a SQLite database with the data files from ICIJ.org
#
ICIJ_LEAKS_DB_NAME = 'icij_leaks.db'
ICIJ_LEAKS_DATA_DIR = './icij_data'

# Remove existing database (if present), since we will recreate it below.
icij_db_path = pathlib.Path(ICIJ_LEAKS_DB_NAME)
icij_db_path.unlink(missing_ok=True)

# Load ICIJ data files into an SQLite database
loader = icij_utils.ICIJDataLoader(ICIJ_LEAKS_DB_NAME)
loader.load_all_files(ICIJ_LEAKS_DATA_DIR)

#
# Init an SQLAchemy instane (over the SQLite database)
#
db = icij_utils.ICIJDatabaseConnector(ICIJ_LEAKS_DB_NAME)
schema = db.get_full_database_schema()

#
# Build an SQL tool
#
schema = db.get_full_database_schema()
metadata = icij_utils.ICIJDatabaseMetadata()

tool_description = (
    "Tool for querying the ICIJ offshore database containing financial data leaks. "
    "This tool can execute SQL queries and return the results. "
    "Beware that this tool's output is a string representation of the execution output.\n"
    "It can use the following tables:"
)

# Add table documentation
for table, doc in metadata.TABLE_DOCS.items():
    tool_description += f"\n\nTable: {table}\n"
    tool_description += f"Description: {doc.strip()}\n"
    tool_description += "Columns:\n"

    # Add column documentation and types
    if table in schema:
        for col_name, col_type in schema[table].items():
            col_doc = metadata.COLUMN_DOCS.get(table, {}).get(col_name, "No documentation available")
            tool_description += f"  - {col_name}: {col_type}: {col_doc}\n"
            #tool_description += f"  - {col_name}: {col_type}\n"
        
# Add source documentation
#tool_description += "\n\nSource IDs:\n"
#for source_id, descrip in metadata.SOURCE_IDS.items():
#    tool_description += f"- {source_id}: {descrip}\n"

@smolagents.tool
def sql_tool(query: str) -> str:
    """Description to be set beloiw...

    Args:
        query: The query to perform. This should be correct SQL.
    """
    output = ""
    with db.get_engine().connect() as con:
        rows = con.execute(sqlalchemy.text(query))
        for row in rows:
            output += "\n" + str(row)
    return output

sql_tool.description = tool_description

#
# language models
#
default_model = smolagents.HfApiModel()

mistral_api_key = os.environ["MISTRAL_API_KEY"]
mistral_model_id = "mistral/codestral-latest"
mistral_model = smolagents.LiteLLMModel(
    model_id=mistral_model_id,
    api_key=mistral_api_key,
    temperature=0.0
)

#
# Define the agent
#
agent = smolagents.CodeAgent(
    tools=[sql_tool],
    model=mistral_model
)

#
# Handler to extract the response's content
#
from typing import Union, Any
from dataclasses import is_dataclass
import json

class ResponseHandler:
    @staticmethod
    def extract_content(response: Any) -> str:
        """
        Extract content from various types of agent responses.
        
        Args:
            response: The response from the agent, could be string, Message object, or dict
            
        Returns:
            str: The extracted content
        """
        # If it's already a string, return it
        if isinstance(response, str):
            return response
            
        # If it's a Message object
        if hasattr(response, 'content') and isinstance(response.content, str):
            return response.content
            
        # If it's a dictionary (e.g., from json.loads())
        if isinstance(response, dict) and 'content' in response:
            return response['content']
            
        # If it's a dataclass
        if is_dataclass(response):
            if hasattr(response, 'content'):
                return response.content
                
        # If it's JSON string
        if isinstance(response, str):
            try:
                parsed = json.loads(response)
                if isinstance(parsed, dict) and 'content' in parsed:
                    return parsed['content']
            except json.JSONDecodeError:
                pass
                
        # If we can't determine the type, return the string representation
        return str(response)

handler = ResponseHandler()


def generate_response(query: str) -> str:
    """Generate a response given query.

    Args:
        - query: the question from the user

    Returns:
        - the response from the agent having access to a database over the ICIJ
          data and a large language model.
    """
    agent_output = agent.run(query)

    # At times, the response appears to be a class instance with a 'content'
    # part. Hence, we will pass the agent's response to some handler that will
    # extract the response's content.
    return handler.extract_content(agent_output)


#
# User interface
#
with gr.Blocks() as demo:
    gr.Markdown("""
        # SQL agent
        Database: ICIJ data on offshore financial data leaks. Very early "fast" prorotyping.
    """)

    # Inputs: question
    question = gr.Textbox(
        label="Question to answer",
        placeholder=""
    )

    # Response
    response = gr.Textbox(
        label="Response",
        placeholder=""
    )
    
    # Button
    with gr.Row():
        response_button = gr.Button("Submit", variant='primary')
        clear_button = gr.Button("Clear", variant='secondary')

    # Example questions given default provided PDF file
    with gr.Accordion("Sample questions", open=False):
        gr.Examples(
            [
                [
                    (
                        "Can you list the entities with an address in Canada? "
                        "Please give the name of the entity an its  address."
                    ),
                ],
                [
                    "Are there any entities located on Montreal, Canada?",
                ]
            ],
            inputs=[question,],
            outputs=[response,],
            fn=generate_response,
            cache_examples=False,
            label="Sample questions"
        )

    # Documentation
    with gr.Accordion("Documentation", open=False):
        gr.Markdown("""
            - Agentic framework: smolagents
            - Data: icij.org
            - Database: SQLite, SQLAlchemy
            - Generation: Mistral
            - Examples: Generated using Claude.ai
        """)

    # Click actions
    response_button.click(
        fn=generate_response,
        inputs=[question,],
        outputs=[response,]
    )
    clear_button.click(
        fn=lambda: ('', ''),
        inputs=[],
        outputs=[question, response]
    )


demo.launch(show_api=False)