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)