File size: 10,325 Bytes
c0f4bac
b08c23b
 
 
 
7b3d1a4
 
 
f4d8679
 
b08c23b
c0f4bac
 
 
b08c23b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0f4bac
 
b08c23b
 
ccb83a2
7b3d1a4
 
 
b08c23b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0f4bac
 
b08c23b
 
ccb83a2
7b3d1a4
 
 
b08c23b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0f4bac
 
 
b08c23b
 
ccb83a2
7b3d1a4
 
 
b08c23b
 
 
 
 
 
c0f4bac
 
51da116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccb83a2
7b3d1a4
ccb83a2
 
7b3d1a4
 
 
50d9ad3
7b3d1a4
 
 
ccb83a2
7b3d1a4
 
51da116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ce07e5
51da116
c0f4bac
 
 
 
 
 
 
 
51da116
c0f4bac
51da116
 
 
 
 
 
 
f4d8679
 
 
 
 
 
 
 
 
 
 
 
 
c0f4bac
f4d8679
c0f4bac
 
 
 
 
 
 
7b3d1a4
f4d8679
 
 
 
 
c0f4bac
 
 
 
 
f4d8679
 
b08c23b
 
 
 
 
 
 
7b3d1a4
 
 
ccb83a2
7b3d1a4
 
3b0a72a
f4d8679
7b3d1a4
3b0a72a
 
 
 
 
51da116
3b0a72a
 
 
 
 
b08c23b
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
import base64
import logging
from typing import List
import os

import markdownify 
import requests

from smolagents import Tool, PythonInterpreterTool, VisitWebpageTool, WikipediaSearchTool
from duckduckgo_search import DDGS

from openai import OpenAI


import whisper
from youtube_transcript_api import YouTubeTranscriptApi

logger = logging.getLogger(__name__)


class ReadFileTool(Tool):
    """
    Tool to read a file and return its content.

    Args:
        file_path (str): Path to the file to read.

    Returns:
        str: Content of the file or error message.
    """

    name = 'read_file'
    description = 'Reads a file and returns its content'
    inputs = {'file_path': {'type': 'string', 'description': 'Path to the file to read'},
              }
    output_type = 'string'

    def __init__(self):
        """Nothing to do for this class here, but kick the constructor of the base class."""
        super().__init__()

    def forward(self, file_path: str) -> str:
        try:
            with open(file_path, 'r') as file:
                return file.read()
        except Exception as e:
            logger.error('error while reading attempt of %s: %s', file_path, e)
            return f'Error reading file: {str(e)}'



class OpenAISpeechToTextTool(Tool):
    """
    Tool to convert speech to text using OpenAI's Whisper model.

    Args:
        audio_path (str): Path to the audio file.

    Returns:
        str: Transcribed text from the audio file.
    """

    name = 'transcribe_audio'
    description = 'Transcribes audio to text and returns the text'
    inputs = {'audio_path': {'type': 'string', 'description': 'Path to the audio file'},
              }
    output_type = 'string'

    def __init__(self):
        """Nothing to do for this class here, but kick the constructor of the base class."""
        super().__init__()

    def forward(self, audio_path: str) -> str:
        try:
            model = whisper.load_model('small')

            if not os.path.exists(audio_path):
                return f'Error: Audio file not found at {audio_path}'

            result = model.transcribe(audio_path)
            return result['text']
        except Exception as e:
            return f'Error transcribing audio: {str(e)}'


class YouTubeTranscriptionTool(Tool):
    """
    Tool to fetch the transcript of a YouTube video given its URL.

    Args:
        video_url (str): YouTube video URL.

    Returns:
        str: Transcript of the video as a single string.
    """

    name = 'youtube_transcription'
    description = 'Fetches the transcript of a YouTube video given its URL'
    inputs = {'video_url': {'type': 'string', 
                            'description': 'YouTube video URL'},
              }
    output_type = 'string'

    def __init__(self):
        """Nothing to do for this class here, but kick the constructor of the base class."""
        super().__init__()

    def forward(self, video_url: str) -> str:
        video_id = video_url.strip().split('v=')[-1]
        transcript = YouTubeTranscriptApi.get_transcript(video_id)
        return ' '.join([entry['text'] for entry in transcript])




class DescribeImageTool(Tool):
    """
    Tool to analyze and describe any image using GPT-4 Vision API.

    Args:
        image_path (str): Path to the image file.
        description_type (str): Type of description to generate. Options:
            - "general": General description of the image
            - "detailed": Detailed analysis of the image
            - "chess": Analysis of a chess position
            - "text": Extract and describe text from the image
            - "custom": Custom description based on user prompt

    Returns:
        str: Description of the image based on the requested type.
    """

    name = 'describe_image'
    description = 'Analyzes and describes images using GPT-4 Vision API'
    inputs = {'image_path': {'type': 'string', 'description': 'Path to the image file'},
              'description_type': {'type': 'string',
                                   'description': 'Type of description to generate (general, detailed, chess, text, custom)',
                                   'nullable': True,
                                   },
              'custom_prompt': {'type': 'string',
                                'description': 'Custom prompt for description (only used when description_type is "custom")',
                                'nullable': True,
                                },
              }
    output_type = 'string'

    _client = None            # OpenAI (compatible) client.  Instantiated on first use


    def __init__(self):
        """ensure, that the super class is instantiated properly and creat an OpenAI client (if not already done)."""
        super().__init__()

        if not self.__class__._client:     
            openai_api_key  = os.environ.get('REAL_OPENAI_API_KEY',              # just in case we run with other openAI compatibel providers
                                             os.environ.get('OPENAI_API_KEY')
                                             )
            self.__class__._client = OpenAI(api_key=openai_api_key)
                                                   

    def encode_image(self, image_path: str) -> str:
        """Encode image to base64 string."""
        with open(image_path, 'rb') as image_file:
            return base64.b64encode(image_file.read()).decode('utf-8')

    def get_prompt(self, description_type: str, custom_prompt: str = None) -> str:
        """Get appropriate prompt based on description type."""
        prompts = {'general': 'Provide a general description of this image. Focus on the main subjects, colors, and overall scene.',
                   'detailed': """Analyze this image in detail. Include:
                                    1. Main subjects and their relationships
                                    2. Colors, lighting, and composition
                                    3. Any text or symbols present
                                    4. Context or possible meaning
                                    5. Notable details or interesting elements""",
                   'chess': """Analyze this chess position and provide a detailed description including:
                               1. List of pieces on the board for both white and black
                               2. Whose turn it is to move
                               3. Basic evaluation of the position
                               4. Any immediate tactical opportunities or threats
                               5. Suggested next moves with brief explanations""",
                   'text': 'Extract and describe any text present in this image. If there are multiple pieces of text, organize them clearly.',
                   }
        return (custom_prompt
                if description_type == 'custom'
                else prompts.get(description_type, prompts['general'])
                )

    def forward(self, image_path: str, description_type: str = 'general', custom_prompt: str = None
                ) -> str:
        try:
            if not os.path.exists(image_path):
                return f'Error: Image file not found at {image_path}'

            # Encode the image
            base64_image = self.encode_image(image_path)

            # Get appropriate prompt
            prompt = self.get_prompt(description_type, custom_prompt)

            # Make the API call
            response = self.__class__._client.chat.completions.create(
                model='gpt-4.1',
                messages=[{'role': 'user',
                           'content': [{'type': 'text', 
                                        'text': prompt},
                                       {'type': 'image_url',
                                        'image_url': {'url': f'data:image/jpeg;base64,{base64_image}'
                                                      },
                                        }, ],
                           }],
                max_tokens=1000,
                )

            return response.choices[0].message.content

        except Exception as e:
            return f'Error analyzing image: {str(e)}'


class ReliableDuckDuckGoSearchTool(Tool):
    """Reliable search for web content.

    especially try to avoid the ratelimit problems of the lite duckduckgosearch.

    Args:
        query (str): query to search with

    Returns:
        str: the query results
    """

    name = 'duckduckgo_search'
    description = 'Performs a duckduckgo web search based on your query (think a Google search) then returns the top search results.'

    inputs = {'query': {'type': 'string', 
                        'description': 'The search query to perform.'},
              }
    output_type = 'string'


    def __init__(self, num_results=3):
        super().__init__()
        self.num_results = num_results

    def forward(self, query: str) -> str:
        with DDGS() as ddgs:
            results = ddgs.text(query, max_results=self.num_results)
            if len(results) == 0:
                raise Exception("No results found! Try a less restrictive/shorter query.")
            postprocessed_results = [f"[{result['title']}]({result['href']})\n{result['body']}" 
                                     for result in results]
        return "## Search Results\n\n" + "\n\n".join(postprocessed_results)


def get_tools() -> List[Tool]:
    """
    Returns a list of available tools for the agent.

    Returns:
        List[Tool]: List of initialized tool instances.
    """

    authorized_imports = ['requests',
                          'markdownify',
                          'wikipedia-api',
                          ]

    try:
        tools = [ReliableDuckDuckGoSearchTool(),
                 PythonInterpreterTool(authorized_imports=authorized_imports),
                 WikipediaSearchTool(),
                 VisitWebpageTool(),
                 OpenAISpeechToTextTool(),
                 YouTubeTranscriptionTool(),
                 ReadFileTool(),
                 DescribeImageTool()
                 ]
    except Exception as e:
        logger.error('error while instantiating the tools: %s', e)
        return f'error instantiating the tools {str(e)}'

    return tools