Weather agent#
1# You may need to add your working directory to the Python path. To do so, uncomment the following lines of code
2# import sys
3# sys.path.append("/Path/to/directory/agentic-framework") # Replace with your directory path
4
5import logging
6import random
7
8from baf.core.agent import Agent
9from baf.core.session import Session
10from baf.exceptions.logger import logger
11from baf.nlp.intent_classifier.intent_classifier_prediction import IntentClassifierPrediction
12
13# Configure the logging module (optional)
14logger.setLevel(logging.INFO)
15
16agent = Agent('weather_agent')
17# Load agent properties stored in a dedicated file
18agent.load_properties('config.yaml')
19# Define the platform your agent will use
20websocket_platform = agent.use_websocket_platform(use_ui=True)
21
22# STATES
23
24s0 = agent.new_state('s0', initial=True)
25weather_state = agent.new_state('weather_state')
26
27# ENTITIES
28
29city_entity = agent.new_entity('city_entity', entries={
30 'Barcelona': ['BCN', 'barna'],
31 'Madrid': [],
32 'Luxembourg': ['LUX']
33})
34
35# INTENTS
36
37weather_intent = agent.new_intent('weather_intent', [
38 'what is the weather in CITY?',
39 'what is the weather like in CITY?',
40 'weather in CITY',
41])
42weather_intent.parameter('city1', 'CITY', city_entity)
43
44# STATES BODIES' DEFINITION + TRANSITIONS
45
46
47def s0_body(session: Session):
48 session.reply(
49 "Welcome! 👋\n"
50 "I can tell you the weather in a city.\n"
51 "Just type something like:\n"
52 "- 'What is the weather in Barcelona?'\n"
53 )
54
55
56s0.set_body(s0_body)
57s0.when_intent_matched(weather_intent).go_to(weather_state)
58
59
60def weather_body(session: Session):
61 predicted_intent: IntentClassifierPrediction = session.event.predicted_intent
62 city = predicted_intent.get_parameter('city1')
63 temperature = round(random.uniform(0, 30), 2)
64 if city.value is None:
65 session.reply("Sorry, I didn't get the city")
66 else:
67 session.reply(f"The weather in {city.value} is {temperature}°C")
68 if temperature < 15:
69 session.reply('🥶')
70 else:
71 session.reply('🥵')
72
73
74weather_state.set_body(weather_body)
75weather_state.go_to(s0)
76
77# RUN APPLICATION
78
79if __name__ == '__main__':
80 agent.run()