Spaces:
Build error
Build error
File size: 2,737 Bytes
184024c 3e2f6be 184024c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | from langchain_community.utilities import WikipediaAPIWrapper
from langchain_community.tools import WikipediaQueryRun, DuckDuckGoSearchRun
from langchain.agents import initialize_agent, AgentType
from langchain.tools import Tool
from langchain.callbacks import StreamlitCallbackHandler
from langchain_groq import ChatGroq
import streamlit as st
# Streamlit setup
st.title("Your AI Assistant")
# User inputs
st.sidebar.title("Settings")
groq_api_key = st.sidebar.text_input("Please Enter Groq API key", type="password")
name = st.sidebar.text_input("Enter Ai Assitant Name", value="RagedAi")
if groq_api_key:
# Initialize LLM
llm = ChatGroq(
model="Llama-3.3-70b-Versatile", groq_api_key=groq_api_key, streaming=True
)
# Define tools
wiki_wrapper = WikipediaAPIWrapper(top_k_results=3, doc_content_chars_max=500)
wiki = WikipediaQueryRun(api_wrapper=wiki_wrapper)
search = DuckDuckGoSearchRun()
def fallback_tool(input_text: str) -> str:
"""Respond directly in character."""
return f" Let's talk: {input_text}"
fallback = Tool(
name="Fallback",
func=fallback_tool,
description="Respond directly as a AI Assistant without using any tools.",
)
tools = [wiki, search, fallback]
# Initialize agent with persona embedding
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
handle_parsing_errors=True,
prefix=f"You are {name}, the user's AI Assistant. "
"You respond like a AI which helps to plan strategies.",
suffix="Start the conversation now!",
)
# User interaction
if "messages" not in st.session_state:
st.session_state.messages = [
{
"role": "assistant",
"content": f"Hi! I'm {name}, your AI Assistant. How can I help you?",
}
]
for msg in st.session_state.messages:
st.chat_message(msg["role"]).write(msg["content"])
if user_input := st.chat_input(f"Talk to {name}!"):
st.session_state.messages.append({"role": "user", "content": user_input})
st.chat_message("user").write(user_input)
with st.chat_message("assistant"):
st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
try:
# Agent processes the input
response = agent.run(st.session_state.messages, callbacks=[st_cb])
except Exception as e:
response = f"Sorry, I encountered an error: {e}"
st.session_state.messages.append({"role": "assistant", "content": response})
st.write(response)
|