faizanmumtaz commited on
Commit
7d91ba8
·
1 Parent(s): 9cfc2fe

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -0
app.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 pydantic import Field,BaseModel
13
+ from langchain.agents import tool
14
+ from dotenv import load_dotenv
15
+ import requests
16
+ from pydantic import BaseModel, Field
17
+ import datetime
18
+ load_dotenv()
19
+
20
+ st.set_page_config(page_title="Chatbot", page_icon="💬")
21
+ st.header('Agent Chatbot')
22
+ st.write('Allows users to interact with the ChatGPT,Wikipedia and fetch current weather temperature of any place.')
23
+
24
+ chat_model = ChatOpenAI(model="gpt-3.5-turbo-1106",max_tokens=50,streaming=True)
25
+
26
+ # Define the input schema
27
+ class OpenMeteoInput(BaseModel):
28
+ latitude: float = Field(..., description="Latitude of the location to fetch weather data for")
29
+ longitude: float = Field(..., description="Longitude of the location to fetch weather data for")
30
+
31
+ @tool(args_schema=OpenMeteoInput)
32
+ def get_current_temperature(latitude: float, longitude: float) -> dict:
33
+ """Fetch current temperature for given coordinates."""
34
+
35
+ BASE_URL = "https://api.open-meteo.com/v1/forecast"
36
+
37
+ # Parameters for the request
38
+ params = {
39
+ 'latitude': latitude,
40
+ 'longitude': longitude,
41
+ 'hourly': 'temperature_2m',
42
+ 'forecast_days': 1,
43
+ }
44
+
45
+ # Make the request
46
+ response = requests.get(BASE_URL, params=params)
47
+
48
+ if response.status_code == 200:
49
+ results = response.json()
50
+ else:
51
+ return f"API Request failed with status code: {response.status_code}"
52
+
53
+ current_utc_time = datetime.datetime.utcnow()
54
+ time_list = [datetime.datetime.fromisoformat(time_str.replace('Z', '+00:00')) for time_str in results['hourly']['time']]
55
+ temperature_list = results['hourly']['temperature_2m']
56
+
57
+ closest_time_index = min(range(len(time_list)), key=lambda i: abs(time_list[i] - current_utc_time))
58
+ current_temperature = temperature_list[closest_time_index]
59
+
60
+ return f'The current temperature is {current_temperature}°C'
61
+
62
+
63
+ @tool
64
+ def SearchWikiPedia(query: str):
65
+ "Serach wikipedia and get page summaries."
66
+
67
+ page_titles = wikipedia.search(query)
68
+
69
+ summaries = []
70
+
71
+ for page_title in page_titles[: 3]:
72
+ try:
73
+
74
+ wiki_page = wikipedia.page(title=page_title,auto_suggest=False)
75
+
76
+ summaries.append(f"Page: {wiki_page.title}\nSummary: {wiki_page.summary}")
77
+
78
+ except Exception:
79
+ pass
80
+
81
+ if not summaries:
82
+ return "No Good WikiPedia Search results found."
83
+ return "\n\n".join(summaries)
84
+
85
+ tools = [get_current_temperature,SearchWikiPedia]
86
+
87
+ functions = [format_tool_to_openai_function(t) for t in tools]
88
+ model_with_function = chat_model.bind(functions = functions)
89
+
90
+
91
+ prompt = ChatPromptTemplate.from_messages([("system","You are helfull assistant."),
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
+ # memory = ConversationBufferWindowMemory(return_messages=True,memory_key="chat_history",k=2)
103
+ if "chat_history" not in st.session_state:
104
+ st.session_state["chat_history"] = ConversationBufferWindowMemory(return_messages=True,memory_key="chat_history",k=2)
105
+
106
+ agent_Executor = AgentExecutor(agent=agent_chain,tools=tools,memory=st.session_state["chat_history"])
107
+
108
+ # Streamlit code
109
+ from langchain.schema import HumanMessage,AIMessage
110
+ if user_input:= st.chat_input("HI: Please Enter some thing"):
111
+ response = agent_Executor.invoke({'user_input':user_input})
112
+ for msg in st.session_state["chat_history"].chat_memory.messages:
113
+ if isinstance(msg,HumanMessage):
114
+ st.chat_message("user").write(msg.content)
115
+ else:
116
+ st.chat_message("assistant").write(msg.content)