8000 added search videos tools and added some validation in api connections · allient/create-fastapi-project@2a34127 · GitHub
[go: up one dir, main page]

8000 Skip to content

Commit 2a34127

Browse files
committed
added search videos tools and added some validation in api connections
1 parent 174e32b commit 2a34127

File tree

6 files changed

+87
-26
lines changed

6 files changed

+87
-26
lines changed
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
PROJECT_NAME=
22
OPENAI_API_KEY=
3-
UNSPLASH_API_KEY=
3+
UNSPLASH_API_KEY=
4+
SERP_API_KEY=

create_fastapi_project/templates/langchain_basic/app/app/api/v1/endpoints/chat.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,12 @@
77
CustomAsyncCallbackHandler,
88
CustomFinalStreamingStdOutCallbackHandler,
99
)
10-
from app.utils.tools import GeneralKnowledgeTool, ImageSearchTool, PokemonSearchTool
10+
from app.utils.tools import (
11+
GeneralKnowledgeTool,
12+
ImageSearchTool,
13+
PokemonSearchTool,
14+
YoutubeSearchTool,
15+
)
1116
from fastapi import APIRouter, WebSocket
1217
from app.utils.uuid6 import uuid7
1318
from app.core.config import settings
@@ -115,6 +120,7 @@ async def websocket_endpoint(websocket: WebSocket):
115120
GeneralKnowledgeTool(),
116121
PokemonSearchTool(),
117122
ImageSearchTool(),
123+
YoutubeSearchTool(),
118124
]
119125

120126
llm = ChatOpenAI(

create_fastapi_project/templates/langchain_basic/app/app/core/config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ class Settings(BaseSettings):
1616
API_V1_STR: str = f"/api/{API_VERSION}"
1717
OPENAI_API_KEY: str
1818
UNSPLASH_API_KEY: str
19+
SERP_API_KEY: str
1920

2021
class Config:
2122
case_sensitive = True

create_fastapi_project/templates/langchain_basic/app/app/utils/tools.py

Lines changed: 44 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
from langchain.chat_models import ChatOpenAI
44
from langchain.schema import HumanMessage
55
import httpx
6+
from serpapi import GoogleSearch
7+
68

79
from app.core.config import settings
810

@@ -12,23 +14,17 @@
1214

1315
class GeneralKnowledgeTool(BaseTool):
1416
name = "Search"
15-
description = (
16-
# "Useful when needs to recommend general knowledge and mantains a conversation"
17-
# "Useful when needs general answers and mantains a conversation"
18-
"useful for when you need to answer questions about current events"
19-
)
17+
description = "useful for when you need to answer questions about current events"
2018

2119
def __init__(self):
2220
super().__init__()
23-
# self.return_direct = True
2421

2522
def _run(self, query: str, run_manager: Optional[Any] = None) -> str:
2623
"""Use the tool."""
2724
pass
2825

2926
async def _arun(self, query: str, run_manager: Optional[Any] = None) -> str:
3027
"""Use the tool asynchronously."""
31-
# create a async client with httpx and get request
3228
chat = ChatOpenAI()
3329
response = await chat.agenerate([[HumanMessage(content=query)]])
3430
message = response.generations[0][0].text
@@ -38,11 +34,9 @@ async def _arun(self, query: str, run_manager: Optional[Any] = None) -> str:
3834
class PokemonSearchTool(BaseTool):
3935
name = "search_pokemon"
4036
description = " Useful when asked to answer information about a pokemon"
41-
# return_direct = True
4237

4338
def __init__(self):
4439
super().__init__()
45-
# self.return_direct = True
4640

4741
def _run(self, query: str, run_manager: Optional[Any] = None) -> str:
4842
"""Use the tool."""
@@ -54,13 +48,11 @@ def _run(self, query: str, run_manager: Optional[Any] = None) -> str:
5448

5549
async def _arun(self, query: str, run_manager: Optional[Any] = None) -> str:
5650
"""Use the tool asynchronously."""
57-
# create a async client with httpx and get request
5851
async with httpx.AsyncClient() as client:
5952
pokemon_url = pokemon_api_url + query.lower()
60-
print("#" * 100)
61-
print(pokemon_url)
62-
print("#" * 100)
6353
response = await client.get(pokemon_url)
54+
if response.status_code == 404:
55+
return "Pokemon not found"
6456
body = response.json()
6557
pokemon_number = body["id"]
6658
pokemon_name = body["name"]
@@ -77,7 +69,6 @@ async def _arun(self, query: str, run_manager: Optional[Any] = None) -> str:
7769
for ability in abilities:
7870
abilities_list_names.append(ability["ability"]["name"])
7971
abilities_names = ", ".join(abilities_list_names)
80-
# create a card with the information
8172
return f"""{pokemon_image} \n
8273
{pokemon_name} - #{pokemon_number} \n
8374
Abilities: {abilities_names} \n
@@ -95,20 +86,17 @@ class ImageSearchTool(BaseTool):
9586

9687
def __init__(self):
9788
super().__init__()
98-
# self.return_direct = True
9989

10090
def _run(self, query: str, run_manager: Optional[Any] = None) -> str:
10191
"""Use the tool."""
102-
response = httpx.get(unsplash_api_url + query.lower())
103-
body = response.json()
104-
pokemon_number = body["id"]
105-
pokemon_name = body["name"]
106-
return f"{pokemon_name} - #{pokemon_number} "
92+
pass
10793

10894
async def _arun(self, query: str, run_manager: Optional[Any] = None) -> str:
10995
"""Use the tool asynchronously."""
110-
# create a async client with httpx and get request
11196
async with httpx.AsyncClient() as client:
97+
if settings.UNSPLASH_API_KEY == "":
98+
return "You need to set a UNSPLASH_API_KEY"
99+
112100
unsplash_url = unsplash_api_url + query.lower()
113101
response = await client.get(unsplash_url)
114102
body = response.json()
@@ -120,5 +108,39 @@ async def _arun(self, query: str, run_manager: Optional[Any] = None) -> str:
120108
image_list_string = "\n".join(
121109
[f"{i+1}. [Image {i+1}]({url})" for i, url in enumerate(images_urls)]
122110
)
123-
124111
return image_list_string
112+
113+
114+
class YoutubeSearchTool(BaseTool):
115+
name = "search_videos"
116+
description = " Useful when asked to answer information about find videos"
117+
return_direct = True
118+
119+
def __init__(self):
120+
super().__init__()
121+
122+
def _run(self, query: str, run_manager: Optional[Any] = None) -> str:
123+
"""Use the tool."""
124+
pass
125+
126+
async def _arun(self, query: str, run_manager: Optional[Any] = None) -> str:
127+
"""Use the tool asynchronously."""
128+
async with httpx.AsyncClient() as client:
129+
if not settings.SERP_API_KEY or settings.SERP_API_KEY == "":
130+
return "You need to set a SERP_API_KEY"
131+
132+
params = {
133+
"engine": "youtube",
134+
"search_query": query,
135+
"api_key": settings.SERP_API_KEY,
136+
}
137+
search = GoogleSearch(params)
138+
results = search.get_dict()
139+
videos = results["video_results"]
140+
video_list_string = "\n".join(
141+
[
142+
f"{i+1}. [{video['title']}]({video['link']})"
143+
for i, video in enumerate(videos)
144+
]
145+
)
146+
return video_list_string

create_fastapi_project/templates/langchain_basic/app/poetry.lock

Lines changed: 32 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

create_fastapi_project/templates/langchain_basic/app/pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ langchain = "^0.0.265"
1414
fastapi = {version = "0.99.1", extras = ["all"]}
1515
openai = "^0.27.8"
1616
adaptive-cards-py = "^0.0.7"
17+
google-search-results = "^2.4.2"
1718

1819

1920
[build-system]

0 commit comments

Comments
 (0)
0