0% found this document useful (0 votes)
7 views4 pages

AI Agent Code Compilation

The document outlines the code for an Enhanced AI Agent built using FastAPI, which integrates services for weather, news, and Wikipedia. It includes the main application code, along with implementations for weather, news, and Wikipedia services, as well as a voice interaction utility. The AI Agent processes user queries and returns relevant information based on the service requested.

Uploaded by

abhaygaur.78
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views4 pages

AI Agent Code Compilation

The document outlines the code for an Enhanced AI Agent built using FastAPI, which integrates services for weather, news, and Wikipedia. It includes the main application code, along with implementations for weather, news, and Wikipedia services, as well as a voice interaction utility. The AI Agent processes user queries and returns relevant information based on the service requested.

Uploaded by

abhaygaur.78
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

AI Agent Code Compilation

1. AI Agent Main Code

import os

from fastapi import FastAPI

from pydantic import BaseModel

from services.weather_service import WeatherService

from services.news_service import NewsService

from services.wikipedia_service import WikipediaService

from utils.voice_interaction import VoiceInteraction

from dotenv import load_dotenv

# Load environment variables

load_dotenv()

app = FastAPI(title="Enhanced AI Agent")

# Services initialization

weather_service = WeatherService(os.getenv("WEATHER_API_KEY"))

news_service = NewsService(os.getenv("NEWS_API_KEY"))

wikipedia_service = WikipediaService()

voice_interaction = VoiceInteraction()

class QueryModel(BaseModel):

query: str

@app.post("/query")

async def handle_query(query_model: QueryModel):

query = query_model.query.lower()

if "weather" in query:

city = query.split("in")[-1].strip()
weather_data = await weather_service.get_weather(city)

return {"response": weather_data}

elif "wikipedia" in query:

topic = query.split("for")[-1].strip()

summary = wikipedia_service.search_summary(topic)

return {"response": summary}

elif "news" in query:

news_list = await news_service.get_news()

return {"response": news_list[:3]}

else:

return {"response": "Query not understood."}

2. Weather Service

import httpx

class WeatherService:

def __init__(self, api_key: str):

self.api_key = api_key

self.base_url = "http://api.weatherapi.com/v1"

async def get_weather(self, city: str) -> dict:

try:

async with httpx.AsyncClient() as client:

response = await client.get(

f"{self.base_url}/current.json",

params={"key": self.api_key, "q": city}

response.raise_for_status()

return response.json()

except httpx.RequestError as e:

return {"error": str(e)}


3. News Service

import httpx

class NewsService:

def __init__(self, api_key: str):

self.api_key = api_key

self.base_url = "https://newsapi.org/v2/top-headlines"

async def get_news(self, country="us", category="technology") -> list:

try:

async with httpx.AsyncClient() as client:

response = await client.get(

self.base_url,

params={"apiKey": self.api_key, "country": country, "category":

category}

response.raise_for_status()

return response.json().get("articles", [])

except httpx.RequestError as e:

return [{"error": str(e)}]

4. Wikipedia Service

import wikipedia

class WikipediaService:

def search_summary(self, topic: str, lang="en") -> str:

wikipedia.set_lang(lang)
try:

return wikipedia.summary(topic, sentences=2)

except wikipedia.exceptions.DisambiguationError as e:

return f"Ambiguous topic. Suggestions: {', '.join(e.options[:5])}."

except wikipedia.exceptions.PageError:

return "No page found for the topic."

5. Voice Interaction Utility

import pyttsx3

import speech_recognition as sr

class VoiceInteraction:

def __init__(self):

self.engine = pyttsx3.init()

self.recognizer = sr.Recognizer()

def text_to_speech(self, text: str):

self.engine.say(text)

self.engine.runAndWait()

def speech_to_text(self) -> str:

with sr.Microphone() as source:

try:

audio = self.recognizer.listen(source)

return self.recognizer.recognize_google(audio)

except sr.UnknownValueError:

return "Sorry, I couldn't understand the audio."

except sr.RequestError:

return "Speech recognition service is unavailable."

You might also like