Spaces:
Sleeping
Sleeping
Create app.py for Travel Planner bot
Browse files
app.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from typing import List
|
| 4 |
+
#from pydantic import BaseModel,Field
|
| 5 |
+
from langchain_core.pydantic_v1 import BaseModel, Field
|
| 6 |
+
#from langchain.chat_models import ChatOpenAI
|
| 7 |
+
from langchain_openai import ChatOpenAI
|
| 8 |
+
from langchain.prompts import HumanMessagePromptTemplate, ChatPromptTemplate
|
| 9 |
+
from langchain.output_parsers import PydanticOutputParser
|
| 10 |
+
|
| 11 |
+
# with open('../openai_api_key.txt') as f:
|
| 12 |
+
# api_key = f.read()
|
| 13 |
+
|
| 14 |
+
# os.environ['OPENAI_API_KEY'] = api_key
|
| 15 |
+
|
| 16 |
+
# creating model instance
|
| 17 |
+
chat = ChatOpenAI()
|
| 18 |
+
|
| 19 |
+
# define pydantic model
|
| 20 |
+
class TravelPlanner(BaseModel):
|
| 21 |
+
places: List[str] = Field(description='Python list containing list of places that can be visited. ')
|
| 22 |
+
itenary: dict = Field(description="Python dictionary of itenary details")
|
| 23 |
+
|
| 24 |
+
# get format instructions
|
| 25 |
+
output_parser = PydanticOutputParser(pydantic_object=TravelPlanner)
|
| 26 |
+
format_instructions = output_parser.get_format_instructions()
|
| 27 |
+
|
| 28 |
+
def travel_planner(place : str) -> List:
|
| 29 |
+
human_template = """
|
| 30 |
+
I want to visit {place}. Suggest me a travel itenary. {format_instructions}"""
|
| 31 |
+
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])
|
| 35 |
+
prompt = chat_prompt.format_prompt(place = place, format_instructions = format_instructions)
|
| 36 |
+
|
| 37 |
+
messages = prompt.messages
|
| 38 |
+
response = chat(messages = messages)
|
| 39 |
+
output = output_parser.parse(response.content)
|
| 40 |
+
|
| 41 |
+
places, itenary = output.places, output.itenary
|
| 42 |
+
return places, itenary
|
| 43 |
+
|
| 44 |
+
# building interface
|
| 45 |
+
with gr.Blocks() as demo:
|
| 46 |
+
gr.HTML("<h1 align = 'center'> Travel Planner </h1>")
|
| 47 |
+
|
| 48 |
+
inputs = [gr.Textbox(label = 'Enter the place that you want to go for vacation')]
|
| 49 |
+
generate_btn = gr.Button(value = 'Generate')
|
| 50 |
+
outputs = [gr.Text(label = 'List of places that you can visit'), gr.JSON(label = 'Itenary details')]
|
| 51 |
+
generate_btn.click(fn = travel_planner,inputs=inputs, outputs=outputs)
|
| 52 |
+
|
| 53 |
+
if __name__ == '__main__':
|
| 54 |
+
demo.launch()
|