Chatwork / app.py
huzaifa456's picture
initial commit
59a34af verified
Raw History Blame Contribute Delete
6.51 kB
import streamlit as st
import matplotlib.pyplot as plt
st.tittle("Chatwork")
from langchain.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper
wikipedia = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())
from langchain.agents import Tool
tools = [
Tool(
name = "Wikipedia",
func=wikipedia.run,
description="Usefull for answering every Wikipedia"
)
]
from langchain_google_genai import ChatGoogleGenerativeAI
llm = ChatGoogleGenerativeAI(model="gemini-1.5-pro", temperature=0.8, google_api_key="AIzaSyBOARVkuQ1nbaQCnKrRHqRUDqklP9JfdKY")
from langchain.agents import initialize_agent, AgentType
agent = initialize_agent(tools , llm, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.invoke({"input": "tell me the most funny summary ever about poets"})
import requests
from langchain_core.tools import tool
@tool
def get_joke(joke_type: str="Any") -> str:
"""Generate a joke of the specified type."""
url = f"https://v2.jokeapi.dev/joke/{joke_type}"
response = requests.get(url)
joke_data = response.json()
if joke_data.get("error"):
return "No jokes found for the specified type."
if joke_data["type"] == "single":
return joke_data["joke"]
else:
return f"{joke_data['delivery']}"
print(get_joke("Any"))
from langchain_groq import ChatGroq
#llm init
llm = ChatGroq(
api_key="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",
verbose=True,
model="llmama3-8b-8192"
)
import os
from textwrap import dedent
# Ensure correct module name and path
from crew_ai.tools import Agent
from crewai_tools import ScrapeWebsiteTool, SerperDevTool
os.environ["SERPER_API_KEY"] = "294d3cb863f951cea074386f5340e5df46955d47"
def web_researcher_agent(topic):
return Agent(
role="Expert on every question. Answer/web researcher and a voice agent.",
goal=dedent(f"""your goal is to search the web or answer the question of the user search the web or scrape. and search the answer from wikipedia and reply also in text and in voice like google voice agent or serie. use the tool provided to search/and answer any random question or make the user choice graph and creating images.
Topic: {topic}"""),
tools=[ScrapeWebsiteTool(), SerperDevTool()],
backstory=dedent("""You are a professional for searching for specific topics on the web or searching any prompt of user at wikipedia search the best information and creating images."""),
verbose=True,
allow_delegation=False,
llm=llm
)
from diffusers import StableDiffusionPipeline
import torch
model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
pipe = pipe.to("cuda")
prompt = ""
image = pipe(prompt).images[0]
image.save("image.png")
from os import system
from langchain_core.tools import tool
@tool
def create_image(prompt: str) -> str:
"""Create stunning AI Generated Images"""
image = pipe(prompt).images[0]
image.save("image.png")
return "Image saved on user device."
print(create_image(""))
tools = [
create_image
]
from langchain import hub
prompt = hub.pull("hwchase17/openai-tools-agent")
print(prompt.messages[0].prompt.template)
prompt.messages[0].prompt.template = """
You are an expert in generating detailed prompts for AI generated images.
The user will provide you a basic prompt and your goal is to convert it into a detailed but SHORT prompt for an AI generated image.
After creating a prompt use the create_image tool to create the image with the prompt.
Respond with just "Image generated" when tool call is succesfull.
Here is an example:
User: "I want you to create a prompt for a girl looking over a battle with a sword in her hand in a fantasy book"
AI: "Create an illustration of a young girl standing on a cliff, overlooking a vast battlefield with a sword in her hand, ready for battle. The scene should be set in a high-fantasy world, with a medieval-inspired aesthetic. The girl should be wearing armor that is practical and functional for combat, but also displays her personal flair and style. The landscape should be mountainous and rugged, with dramatic clouds in the sky and hints of magic or otherworldly elements. The overall tone should be serious and intense, with a sense of impending danger and conflict. Use a color palette that is bold and striking, emphasizing the contrast between light and shadow. The art style should be highly detailed and polished, with influences from classic fantasy illustrators such as Frank Frazetta and Boris Vallejo."
AI: invoke create_image tool with the prompt.
"""
from langchain_groq import ChatGroq
#llm init
llm = ChatGroq(
api_key="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",
verbose=True,
model="llmama3-8b-8192"
)
from langchain.agents import AgentExecutor,create_tool_calling_agent
agent = create_tool_calling_agent(llm, tools, prompt)
agent_executer = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executer.invoke({"input":""})
import speech_recognition as sr
import pyttsx3
from langchain import Agent, Memory
from langchain.llms import Groq
recognizer = sr.Recognizer()
tts_engine = pyttsx3.init()
llm = Groq(api_key='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')
memory = Memory()
agent = Agent(llm, memory=memory)
def recognize_speech():
with sr.Microphone() as source:
print("Listening...")
audio = recognizer.listen(source)
try:
text = recognizer.recognize_google(audio)
print(f": {text}")
return text
except sr.UnknownValueError:
print("")
return None
except sr.RequestError as e:
print(f"; {e}")
return None
def speak_text(text):
tts_engine.say(text)
tts_engine.runAndWait()
def main():
print("Voice Agent is running. Say 'stop' to end the session.")
while True:
command = recognize_speech()
if command:
if 'stop' in command.lower():
print("Stopping the voice agent.")
break
# Process the command and store it in memory
response = agent.run(command)
# Store the interaction in memory
memory.store(command, response)
print(f"Agent: {response}")
speak_text(response)
if __name__ == "__main__":
main()