()
| 285 | |
| 286 | # Function to use LLMs with web search |
| 287 | def use_llms_with_web(): |
| 288 | from langchain.agents import ConversationalChatAgent, AgentExecutor |
| 289 | from langchain.callbacks import StreamlitCallbackHandler |
| 290 | from langchain.chat_models import ChatOpenAI |
| 291 | from langchain.memory import ConversationBufferMemory |
| 292 | from langchain.memory.chat_message_histories import StreamlitChatMessageHistory |
| 293 | from langchain.tools import DuckDuckGoSearchRun |
| 294 | import streamlit as st |
| 295 | |
| 296 | |
| 297 | st.title("Use web search with LLMs") |
| 298 | # Taking OpenAI API key input from the user |
| 299 | openai_api_key = st.sidebar.text_input("OpenAI API Key", type="password") |
| 300 | # Initializing message history and memory |
| 301 | msgs = StreamlitChatMessageHistory() |
| 302 | memory = ConversationBufferMemory( |
| 303 | chat_memory=msgs, return_messages=True, memory_key="chat_history", output_key="output" |
| 304 | ) |
| 305 | # Resetting chat history logic |
| 306 | if len(msgs.messages) == 0 or st.sidebar.button("Reset chat history"): |
| 307 | msgs.clear() |
| 308 | msgs.add_ai_message("How can I help you?") |
| 309 | st.session_state.steps = {} |
| 310 | |
| 311 | # Defining avatars for chat messages |
| 312 | avatars = {"human": "user", "ai": "assistant"} |
| 313 | for idx, msg in enumerate(msgs.messages): |
| 314 | with st.chat_message(avatars[msg.type]): |
| 315 | # Render intermediate steps if any were saved |
| 316 | for step in st.session_state.steps.get(str(idx), []): |
| 317 | if step[0].tool == "_Exception": |
| 318 | continue |
| 319 | with st.status(f"**{step[0].tool}**: {step[0].tool_input}", state="complete"): |
| 320 | st.write(step[0].log) |
| 321 | st.write(step[1]) |
| 322 | st.write(msg.content) |
| 323 | |
| 324 | # Taking new input from the user |
| 325 | if prompt := st.chat_input(placeholder="Who won the 2022 Cricket World Cup?"): |
| 326 | st.chat_message("user").write(prompt) |
| 327 | # Checking if OpenAI API key is provided |
| 328 | if not openai_api_key: |
| 329 | st.info("Please add your OpenAI API key to continue.") |
| 330 | st.stop() |
| 331 | # Initializing LLM and tools for web search |
| 332 | llm = ChatOpenAI(model_name="gpt-3.5-turbo", openai_api_key=openai_api_key, streaming=True) |
| 333 | tools = [DuckDuckGoSearchRun(name="Search")] |
| 334 | chat_agent = ConversationalChatAgent.from_llm_and_tools(llm=llm, tools=tools) |
| 335 | |
| 336 | executor = AgentExecutor.from_agent_and_tools( |
| 337 | agent=chat_agent, |
| 338 | tools=tools, |
| 339 | memory=memory, |
| 340 | return_intermediate_steps=True, |
| 341 | handle_parsing_errors=True, |
| 342 | ) |
| 343 | |
| 344 | with st.chat_message("assistant"): |
nothing calls this directly
no outgoing calls
no test coverage detected