Update tools/youtube_search.py
Browse files- tools/youtube_search.py +52 -0
tools/youtube_search.py
CHANGED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
from smolagents.tools import Tool
|
| 3 |
+
import duckduckgo_search
|
| 4 |
+
from googleapiclient.discovery import build
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
YOUTUBE_API_KEY=os.environ.get('YOUTUBE_API_KEY')
|
| 9 |
+
|
| 10 |
+
def youtube_search(query):
|
| 11 |
+
max_results=10
|
| 12 |
+
print(f"query -> {query}")
|
| 13 |
+
|
| 14 |
+
return_result = []
|
| 15 |
+
youtube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)
|
| 16 |
+
|
| 17 |
+
request = youtube.search().list(
|
| 18 |
+
q=query,
|
| 19 |
+
part='snippet',
|
| 20 |
+
maxResults=max_results,
|
| 21 |
+
type='video'
|
| 22 |
+
)
|
| 23 |
+
response = request.execute()
|
| 24 |
+
print(f"Stap 5 {response}")
|
| 25 |
+
|
| 26 |
+
for item in response.get('items', []):
|
| 27 |
+
print(f"Title: {item['snippet']['title']}")
|
| 28 |
+
print(f"Video ID: {item['id']['videoId']}")
|
| 29 |
+
print()
|
| 30 |
+
return_result.append({'aquery': query, 'titlevideo': item['snippet']['title'], 'videoId': item['id']['videoId']})
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
print("Stap 6")
|
| 34 |
+
return return_result
|
| 35 |
+
|
| 36 |
+
class YoutubeSearchTool(Tool):
|
| 37 |
+
name = "youtube_search"
|
| 38 |
+
#description = "Performs a search with youtube API to select a potentially related song of band based on your query and return top X results."
|
| 39 |
+
description = "Performs a search on youtube to select a potentially related song of band based on your query and return top X results. Never use named parameter use on positional parameters"
|
| 40 |
+
inputs = {'aquery': {'type': 'string', 'description': 'The search query to perform.'}}
|
| 41 |
+
output_type = "object" # TODO or Dict or List ????!???
|
| 42 |
+
|
| 43 |
+
def __init__(self, max_results=10, **kwargs):
|
| 44 |
+
super().__init__()
|
| 45 |
+
self.max_results = max_results
|
| 46 |
+
|
| 47 |
+
def forward(self, aquery: str) -> str:
|
| 48 |
+
results = youtube_search(aquery)
|
| 49 |
+
if len(results) == 0:
|
| 50 |
+
raise Exception("No results found! Try a less restrictive/shorter query.")
|
| 51 |
+
|
| 52 |
+
return results
|