Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from langchain.schema.runnable import RunnablePassthrough
|
| 3 |
+
from langchain.memory import ConversationBufferWindowMemory
|
| 4 |
+
from langchain.agents import AgentExecutor
|
| 5 |
+
from langchain.agents.format_scratchpad import format_to_openai_functions
|
| 6 |
+
import wikipedia
|
| 7 |
+
from langchain.tools.render import format_tool_to_openai_function
|
| 8 |
+
from langchain.prompts import MessagesPlaceholder
|
| 9 |
+
from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser
|
| 10 |
+
from langchain.chat_models import ChatOpenAI
|
| 11 |
+
from langchain.prompts import ChatPromptTemplate
|
| 12 |
+
from langchain.agents import tool
|
| 13 |
+
import requests
|
| 14 |
+
import datetime,os
|
| 15 |
+
from langchain.pydantic_v1 import BaseModel,Field
|
| 16 |
+
|
| 17 |
+
st.set_page_config(page_title="ChatBot", page_icon="🤖")
|
| 18 |
+
st.header('Agent ChatBot')
|
| 19 |
+
st.write('Allows users to interact with the ChatGPT,Wikipedia and fetch current weather temperature of any place.')
|
| 20 |
+
if "messages" not in st.session_state:
|
| 21 |
+
st.session_state["messages"] = [{"role":"assistant","content":"Hello! How can I assist you today?"}]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
chat_model = ChatOpenAI(model="gpt-3.5-turbo-1106",
|
| 25 |
+
streaming=True,)
|
| 26 |
+
|
| 27 |
+
# Define the input schema
|
| 28 |
+
class OpenMeteoInput(BaseModel):
|
| 29 |
+
latitude: float = Field(..., description="Latitude of the location to fetch weather data for")
|
| 30 |
+
longitude: float = Field(..., description="Longitude of the location to fetch weather data for")
|
| 31 |
+
|
| 32 |
+
@tool(args_schema=OpenMeteoInput)
|
| 33 |
+
def get_current_temperature(latitude: float, longitude: float) -> dict:
|
| 34 |
+
"""Fetch current temperature for given coordinates."""
|
| 35 |
+
|
| 36 |
+
BASE_URL = "https://api.open-meteo.com/v1/forecast"
|
| 37 |
+
|
| 38 |
+
# Parameters for the request
|
| 39 |
+
params = {
|
| 40 |
+
'latitude': latitude,
|
| 41 |
+
'longitude': longitude,
|
| 42 |
+
'hourly': 'temperature_2m',
|
| 43 |
+
'forecast_days': 1,
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
# Make the request
|
| 47 |
+
response = requests.get(BASE_URL, params=params)
|
| 48 |
+
|
| 49 |
+
if response.status_code == 200:
|
| 50 |
+
results = response.json()
|
| 51 |
+
else:
|
| 52 |
+
return f"API Request failed with status code: {response.status_code}"
|
| 53 |
+
|
| 54 |
+
current_utc_time = datetime.datetime.utcnow()
|
| 55 |
+
time_list = [datetime.datetime.fromisoformat(time_str.replace('Z', '+00:00')) for time_str in results['hourly']['time']]
|
| 56 |
+
temperature_list = results['hourly']['temperature_2m']
|
| 57 |
+
|
| 58 |
+
closest_time_index = min(range(len(time_list)), key=lambda i: abs(time_list[i] - current_utc_time))
|
| 59 |
+
current_temperature = temperature_list[closest_time_index]
|
| 60 |
+
|
| 61 |
+
return f'The current temperature is {current_temperature}°C'
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@tool
|
| 65 |
+
def SearchWikiPedia(query: str):
|
| 66 |
+
"Serach wikipedia and get page summaries."
|
| 67 |
+
|
| 68 |
+
page_titles = wikipedia.search(query)
|
| 69 |
+
|
| 70 |
+
summaries = []
|
| 71 |
+
|
| 72 |
+
for page_title in page_titles[: 3]:
|
| 73 |
+
try:
|
| 74 |
+
|
| 75 |
+
wiki_page = wikipedia.page(title=page_title,auto_suggest=False)
|
| 76 |
+
|
| 77 |
+
summaries.append(f"Page: {wiki_page.title}\nSummary: {wiki_page.summary}")
|
| 78 |
+
|
| 79 |
+
except Exception:
|
| 80 |
+
pass
|
| 81 |
+
|
| 82 |
+
if not summaries:
|
| 83 |
+
return "No Good WikiPedia Search results found."
|
| 84 |
+
return "\n\n".join(summaries)
|
| 85 |
+
|
| 86 |
+
tools = [get_current_temperature,SearchWikiPedia]
|
| 87 |
+
|
| 88 |
+
functions = [format_tool_to_openai_function(t) for t in tools]
|
| 89 |
+
model_with_function = chat_model.bind(functions = functions)
|
| 90 |
+
|
| 91 |
+
prompt = ChatPromptTemplate.from_messages([("system","You are helpfull assistant.You can query from wikipedia if you donot know the answer of user query also you can check current weather temperature of any place."),
|
| 92 |
+
MessagesPlaceholder(variable_name="chat_history"),
|
| 93 |
+
("user","{user_input}"),
|
| 94 |
+
MessagesPlaceholder(variable_name="agent_scratchpad")])
|
| 95 |
+
|
| 96 |
+
chain = prompt | model_with_function | OpenAIFunctionsAgentOutputParser()
|
| 97 |
+
|
| 98 |
+
agent_chain = RunnablePassthrough.assign(
|
| 99 |
+
agent_scratchpad = lambda x: format_to_openai_functions(x['intermediate_steps'])
|
| 100 |
+
) | chain
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
for msg in st.session_state["messages"]:
|
| 104 |
+
st.chat_message(msg["role"]).write(msg["content"])
|
| 105 |
+
|
| 106 |
+
@st.cache_resource
|
| 107 |
+
def main():
|
| 108 |
+
memory=ConversationBufferWindowMemory(return_messages=True,memory_key="chat_history",k=54)
|
| 109 |
+
return AgentExecutor(agent=agent_chain,tools=tools,memory=memory)
|
| 110 |
+
|
| 111 |
+
def _main():
|
| 112 |
+
if user_input:= st.chat_input("Send Message To GPT..."):
|
| 113 |
+
st.chat_message("user").write(user_input)
|
| 114 |
+
st.session_state.messages.append({"role":"user","content":user_input})
|
| 115 |
+
response = main().invoke({'user_input':user_input})
|
| 116 |
+
with st.chat_message("assistant"):
|
| 117 |
+
st.write(response["output"])
|
| 118 |
+
st.session_state.messages.append({"role":"assistant","content":response["output"]})
|
| 119 |
+
try:
|
| 120 |
+
_main()
|
| 121 |
+
except Exception as error:
|
| 122 |
+
st.error(error)
|