|
|
from langchain_huggingface import HuggingFacePipeline |
|
|
from transformers import pipeline |
|
|
from langchain.agents import initialize_agent |
|
|
from langchain.tools import Tool |
|
|
from langchain_community.tools import DuckDuckGoSearchRun |
|
|
from datetime import datetime |
|
|
import pytz |
|
|
import gradio as gr |
|
|
|
|
|
|
|
|
search_web = DuckDuckGoSearchRun() |
|
|
search_tool = Tool("web_search", search_web.invoke, "Look up current info") |
|
|
|
|
|
def calculator(query: str) -> str: |
|
|
try: |
|
|
return str(eval(query, {"__builtins__": None}, {})) |
|
|
except Exception as e: |
|
|
return f"Error: {e}" |
|
|
calculator_tool = Tool("calculator_tool", calculator, "Arithmetic calculator") |
|
|
|
|
|
def get_time(location: str) -> str: |
|
|
try: |
|
|
tz = pytz.timezone(location) |
|
|
return datetime.now(tz).strftime("The current time in %Z is %H:%M:%S.") |
|
|
except Exception as e: |
|
|
return f"Error: {e}" |
|
|
time_tool = Tool("time_tool", get_time, "Time in a timezone") |
|
|
|
|
|
tools = [search_tool, calculator_tool, time_tool] |
|
|
|
|
|
|
|
|
hf_pipeline = pipeline("text-generation", model="distilgpt2") |
|
|
llm = HuggingFacePipeline(pipeline=hf_pipeline) |
|
|
|
|
|
|
|
|
agent = initialize_agent( |
|
|
tools, |
|
|
llm, |
|
|
agent_type="chat-conversational-react-description", |
|
|
verbose=True |
|
|
) |
|
|
|
|
|
|
|
|
def alfred_chat(user_input: str): |
|
|
return agent.run(user_input) |
|
|
|
|
|
iface = gr.Interface( |
|
|
fn=alfred_chat, |
|
|
inputs=gr.Textbox(lines=2, placeholder="Ask Alfred something..."), |
|
|
outputs="text" |
|
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
iface.launch() |
|
|
|