sgongora27 commited on
Commit
64fcca7
·
1 Parent(s): 2cb7e93

Replicate integration

Browse files
Files changed (3) hide show
  1. app.py +24 -20
  2. models.py +44 -22
  3. prompts.py +67 -60
app.py CHANGED
@@ -1,14 +1,13 @@
1
  import gradio as gr
2
- from gradio import ChatMessage
3
  import re
4
  import time
5
  import json
6
  import os
7
  import jsonpickle
8
  import configparser
9
-
10
  import example_worlds
11
- from models import GeminiModel
 
12
  from prompts import prompt_narrate_current_scene, prompt_world_update, prompt_describe_objective
13
  from huggingface_hub import HfApi
14
  from huggingface_hub import login
@@ -24,11 +23,11 @@ config.read('config.ini')
24
  # language of the game
25
  language = config['Options']['Language']
26
 
27
- # Initialize the model and disable the safety settings
28
  reasoning_model_name = config['Models']['ReasoningModel']
29
  narrative_model_name = config['Models']['NarrativeModel']
30
- reasoning_model = GeminiModel("API_key", reasoning_model_name)
31
- narrative_model = GeminiModel("API_key", narrative_model_name)
32
 
33
  # Create a name for the log file
34
  timestamp = time.time()
@@ -52,8 +51,8 @@ def game_loop(message, history):
52
  answer = ""
53
 
54
  # Get the changes in the world
55
- prompt_update = prompt_world_update(world.render_world(language=language), message, language=language)
56
- response_update = reasoning_model.prompt_model(prompt_update)
57
 
58
  # Show the detected changes in the fictional world
59
  print("🛠️ Predicted outcomes of the player input 🛠️")
@@ -74,12 +73,13 @@ def game_loop(message, history):
74
  if last_player_position is not world.player.location:
75
  #Narrate new scene
76
  last_player_position = world.player.location
77
- new_scene_narration = narrative_model.prompt_model(
78
- prompt_narrate_current_scene(world.render_world(language=language),
79
- previous_narrations = world.player.visited_locations[world.player.location.name],
80
- language=language)
 
81
 
82
- )
83
  world.player.visited_locations[world.player.location.name]+=[new_scene_narration]
84
  answer += f"\n{new_scene_narration}\n\n"
85
  else:
@@ -104,7 +104,7 @@ def game_loop(message, history):
104
  with open(os.path.join(PATH_GAMELOGS,log_filename), 'w', encoding='utf-8') as f:
105
  json.dump(game_log_dictionary, f, ensure_ascii=False, indent=4)
106
 
107
- if world.check_objective():
108
 
109
  api = HfApi()
110
  api.upload_file(
@@ -116,6 +116,7 @@ def game_loop(message, history):
116
 
117
  return answer.replace("<",r"\<").replace(">", r"\>")
118
 
 
119
  # Instantiate the world
120
  world_id = config["Options"]["WorldID"]
121
  world = example_worlds.get_world(world_id, language=language)
@@ -137,15 +138,18 @@ game_log_dictionary[0]["initial_symbolic_world_state"] = jsonpickle.encode(world
137
  game_log_dictionary[0]["initial_rendered_world_state"] = world.render_world(language=language)
138
 
139
  #Generate a description of the starting scene
140
- starting_narration = narrative_model.prompt_model(
141
- prompt_narrate_current_scene(world.render_world(language=language),
142
- previous_narrations = world.player.visited_locations[world.player.location.name],
143
- language=language,
144
- starting_scene=True))
 
 
145
  world.player.visited_locations[world.player.location.name]+=[starting_narration]
146
 
147
  #Generate a description of the main objective
148
- narrated_objective = narrative_model.prompt_model(prompt_describe_objective(world.objective, language=language))
 
149
  starting_narration += f"\n\n🎯 {re.findall(r'#([^#]*?)#',narrated_objective)[0]}"
150
  game_log_dictionary[0]["starting_narration"] = starting_narration
151
 
 
1
  import gradio as gr
 
2
  import re
3
  import time
4
  import json
5
  import os
6
  import jsonpickle
7
  import configparser
 
8
  import example_worlds
9
+
10
+ from models import get_llm
11
  from prompts import prompt_narrate_current_scene, prompt_world_update, prompt_describe_objective
12
  from huggingface_hub import HfApi
13
  from huggingface_hub import login
 
23
  # language of the game
24
  language = config['Options']['Language']
25
 
26
+ # Initialize the model
27
  reasoning_model_name = config['Models']['ReasoningModel']
28
  narrative_model_name = config['Models']['NarrativeModel']
29
+ reasoning_model = get_llm(reasoning_model_name)
30
+ narrative_model = get_llm(narrative_model_name)
31
 
32
  # Create a name for the log file
33
  timestamp = time.time()
 
51
  answer = ""
52
 
53
  # Get the changes in the world
54
+ system_msg_update, user_msg_update = prompt_world_update(world.render_world(language=language), message, language=language)
55
+ response_update = reasoning_model.prompt_model(system_msg=system_msg_update, user_msg=user_msg_update)
56
 
57
  # Show the detected changes in the fictional world
58
  print("🛠️ Predicted outcomes of the player input 🛠️")
 
73
  if last_player_position is not world.player.location:
74
  #Narrate new scene
75
  last_player_position = world.player.location
76
+ system_msg_new_scene, user_msg_new_scene = prompt_narrate_current_scene(
77
+ world.render_world(language=language),
78
+ previous_narrations = world.player.visited_locations[world.player.location.name],
79
+ language=language
80
+ )
81
 
82
+ new_scene_narration = narrative_model.prompt_model(system_msg=system_msg_new_scene, user_msg=user_msg_new_scene)
83
  world.player.visited_locations[world.player.location.name]+=[new_scene_narration]
84
  answer += f"\n{new_scene_narration}\n\n"
85
  else:
 
104
  with open(os.path.join(PATH_GAMELOGS,log_filename), 'w', encoding='utf-8') as f:
105
  json.dump(game_log_dictionary, f, ensure_ascii=False, indent=4)
106
 
107
+ if world.check_objective() or "EXIT NOW" in message:
108
 
109
  api = HfApi()
110
  api.upload_file(
 
116
 
117
  return answer.replace("<",r"\<").replace(">", r"\>")
118
 
119
+
120
  # Instantiate the world
121
  world_id = config["Options"]["WorldID"]
122
  world = example_worlds.get_world(world_id, language=language)
 
138
  game_log_dictionary[0]["initial_rendered_world_state"] = world.render_world(language=language)
139
 
140
  #Generate a description of the starting scene
141
+ system_msg_current_scene, user_msg_current_scene = prompt_narrate_current_scene(
142
+ world.render_world(language=language),
143
+ previous_narrations = world.player.visited_locations[world.player.location.name],
144
+ language=language,
145
+ starting_scene=True
146
+ )
147
+ starting_narration = narrative_model.prompt_model(system_msg=system_msg_current_scene, user_msg=user_msg_current_scene)
148
  world.player.visited_locations[world.player.location.name]+=[starting_narration]
149
 
150
  #Generate a description of the main objective
151
+ system_msg_objective, user_msg_objective = prompt_describe_objective(world.objective, language=language)
152
+ narrated_objective = narrative_model.prompt_model(system_msg=system_msg_objective, user_msg=user_msg_objective)
153
  starting_narration += f"\n\n🎯 {re.findall(r'#([^#]*?)#',narrated_objective)[0]}"
154
  game_log_dictionary[0]["starting_narration"] = starting_narration
155
 
models.py CHANGED
@@ -1,11 +1,51 @@
1
  """Load models to use them as a narrator and a common-sense oracle in the PAYADOR pipeline."""
2
  import google.generativeai as genai
3
  import requests
 
4
  import os
 
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  class GeminiModel():
8
- def __init__ (self, api_key_file:str, model_name:str = "gemini-1.0-pro") -> None:
9
  """"Initialize the Gemini model using an API key."""
10
  self.safety_settings = [
11
  {
@@ -29,27 +69,9 @@ class GeminiModel():
29
  "threshold": "BLOCK_NONE",
30
  },
31
  ]
32
- genai.configure(api_key=os.getenv(api_key_file))
33
  self.model = genai.GenerativeModel(model_name)
34
 
35
- def prompt_model(self,prompt: str) -> str:
36
  """Prompt the Gemini model."""
37
- return self.model.generate_content(prompt, safety_settings=self.safety_settings).text
38
-
39
-
40
- def prompt_HF_API (prompt: str, model: str = "microsoft/Phi-3-mini-4k-instruct", api_key_file: str = "HF_API_key"):
41
- API_URL = f"https://api-inference.huggingface.co/models/{model}"
42
-
43
- headers = {"Authorization": f"Bearer {get_api_key(api_key_file)}"}
44
- payload = {"inputs": prompt}
45
-
46
- output = requests.post(API_URL, headers=headers, json=payload).json()
47
-
48
- return output[0]["generated_text"]
49
-
50
- def get_api_key(path: str) -> str:
51
- """Load an API key from path."""
52
- key = ""
53
- with open(path) as f:
54
- key = f.readline()
55
- return key
 
1
  """Load models to use them as a narrator and a common-sense oracle in the PAYADOR pipeline."""
2
  import google.generativeai as genai
3
  import requests
4
+ import replicate
5
  import os
6
+ from dotenv import load_dotenv
7
 
8
+ load_dotenv()
9
+
10
+ def get_llm(model_name: str = "gemini-1.5-flash") -> object:
11
+
12
+ google_models = ["gemini-1.0-pro", "gemini-1.5-pro", "gemini-1.5-flash"]
13
+ replicate_models = ["meta/meta-llama-3-70b", "meta/meta-llama-3-70b-instruct"]
14
+
15
+ model = None
16
+
17
+ if model_name in google_models:
18
+ model = GeminiModel(API_key="GOOGLE_API_KEY", model_name=model_name)
19
+ elif model_name in replicate_models:
20
+ model = ReplicateModel(API_key="REPLICATE_API_TOKEN", model_name=model_name)
21
+
22
+ return model
23
+
24
+
25
+ class ReplicateModel():
26
+ def __init__ (self, API_key:str, model_name:str = "meta/meta-llama-3-70b-instruct") -> None:
27
+ self.temperature = 0.7
28
+ self.model_name = model_name
29
+
30
+ def prompt_model(self,system_msg: str, user_msg:str) -> str:
31
+ """Prompt the Replicate model."""
32
+
33
+ system_instructions = f"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n{system_msg}<|eot_id|><|start_header_id|>user<|end_header_id|>"
34
+
35
+ input = {
36
+ "top_p": 0.1,
37
+ "min_tokens": 0,
38
+ "temperature": self.temperature,
39
+ "prompt": user_msg,
40
+ "prompt_template": system_instructions + "\n\n{prompt}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n",
41
+ }
42
+
43
+ output = replicate.run(self.model_name,input=input)
44
+
45
+ return "".join(output)
46
 
47
  class GeminiModel():
48
+ def __init__ (self, API_key:str, model_name:str = "gemini-1.0-pro") -> None:
49
  """"Initialize the Gemini model using an API key."""
50
  self.safety_settings = [
51
  {
 
69
  "threshold": "BLOCK_NONE",
70
  },
71
  ]
72
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
73
  self.model = genai.GenerativeModel(model_name)
74
 
75
+ def prompt_model(self,system_msg: str, user_msg:str) -> str:
76
  """Prompt the Gemini model."""
77
+ return self.model.generate_content(system_msg + "\n\n" + user_msg, safety_settings=self.safety_settings).text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
prompts.py CHANGED
@@ -1,117 +1,124 @@
1
- def prompt_describe_objective (objective, language:str = 'en') -> str:
2
- prompt = ""
 
3
 
4
  if language == 'es':
5
- prompt = prompt_describe_objective_spanish(objective)
6
  else:
7
- prompt = prompt_describe_objective_english(objective)
8
 
9
- return prompt
10
 
11
- def prompt_describe_objective_english (objective) -> str:
 
 
 
 
12
 
13
- prompt = "Please, provide an alternative way to narrate the following objective, using simple language: "
14
  first_component_class = objective[0].__class__.__name__
15
  second_component_class = objective[1].__class__.__name__
 
16
 
17
  if first_component_class == "Character" and second_component_class == "Location":
18
- prompt+= f'"You have to go to <{objective[1].name}>."'
19
  elif first_component_class == "Character" and second_component_class == "Item":
20
- prompt+= f'"<{objective[0].name}> has to get the item <{objective[1].name}>."'
21
  elif first_component_class == "Item" and second_component_class == "Location":
22
- prompt+= f'"You have to leave item <{objective[0].name}> in place <{objective[1].name}>."'
23
  elif first_component_class == "Character" and second_component_class == "Character":
24
- prompt+= f'"<{objective[0].name}> has to find <{objective[1].name}>."'
25
 
26
- prompt+="\nPut your generated narration between # characters. For example: # You have to get the <key> # or # You have to reach the <castle> #"
27
 
28
- return prompt
29
 
30
- def prompt_describe_objective_spanish (objective) -> str:
 
 
31
 
32
- prompt = "Por favor, dame una forma alternativa de narrar el siguiente objetivo, usando lenguaje simple: "
33
  first_component_class = objective[0].__class__.__name__
34
  second_component_class = objective[1].__class__.__name__
 
35
 
36
  if first_component_class == "Character" and second_component_class == "Location":
37
- prompt+= f'"Tienes que ir a <{objective[1].name}>."'
38
  elif first_component_class == "Character" and second_component_class == "Item":
39
- prompt+= f'"<{objective[0].name}> tiene que conseguir el objeto <{objective[1].name}>."'
40
  elif first_component_class == "Item" and second_component_class == "Location":
41
- prompt+= f'"Tienes que dejar el objeto <{objective[0].name}> en el lugar <{objective[1].name}>."'
42
  elif first_component_class == "Character" and second_component_class == "Character":
43
- prompt+= f'"<{objective[0].name}> tiene que encontrar a <{objective[1].name}>."'
44
-
45
- prompt+="\nPon tu narración generada entre caracteres #. Por ejemplo: # Tienes que conseguir la <llave> # o # Tienes que llegaral <Castillo> #"
46
 
47
- return prompt
48
 
49
- def prompt_narrate_current_scene (world_state: str, previous_narrations: 'list[str]', language: str = 'en', starting_scene: bool = False) -> str:
50
- prompt = ""
 
51
 
52
  if language == 'es':
53
- prompt = prompt_narrate_current_scene_spanish(world_state, previous_narrations, starting_scene)
54
  else:
55
- prompt = prompt_narrate_current_scene_english(world_state, previous_narrations, starting_scene)
56
 
57
 
58
- return prompt
59
 
60
- def prompt_narrate_current_scene_english (world_state: str, previous_narrations: 'list[str]', starting_scene: bool = False) -> str:
61
 
62
- prompt = "You are a storyteller. Take the following state of the world and narrate it in a few sentences. Be careful not to include details that contradict the current state of the world or that move the story forward. Also, try to use simple sentences and do not overuse poetic language.\n"
63
 
64
  if starting_scene:
65
- prompt += "\nTake into account that this is the first scene in the story: introduce the main character, creating a small background story and why that character is in that specific location.\n"
66
  elif len(previous_narrations)==0:
67
- prompt += "Take into account that the player already knows what the main character looks like, so do not mention anything about that. However, it is the first time the player visits this place, so make sure to describe it exhaustively."
68
  else:
69
- prompt += "Take into account that the player already knows what the main character looks like, so do not mention anything about that. Additionally, it is not the first time the player visits this place. Next I’ll give you some previous narrations of this same location (from oldest to newest) so you can be sure to not repeat the same details again:\n"
70
  for narration in previous_narrations:
71
- prompt+=f'- {narration}\n'
72
 
73
- prompt+= "\nRemember: you are talking to the player, describing what his or her character has and what he or she can see or feel."
74
 
75
- prompt +=f"""This is the state of the world at the moment:
76
  {world_state}
77
  """
78
 
79
- return prompt
80
 
81
- def prompt_narrate_current_scene_spanish (world_state: str, previous_narrations: 'list[str]', starting_scene: bool = False) -> str:
82
 
83
- prompt = f"""Eres un narrador. Toma el siguiente estado del mundo y nárralo en unas pocas oraciones. Ten cuidado de no incluir detalles que contradigan el estado del mundo actual, o que hagan avanzar la historia. Además, intenta usar oraciones simples, sin abusar del lenguaje poético."""
84
 
85
  if starting_scene:
86
- prompt += "\nTen en cuenta que esta es la primera escena en la historia narrada: presenta al personaje del jugador, creando un pequeño trasfondo y por qué este personaje está en ese lugar específicamente. Puede usar las pequeñas descripciones presentes en el estado del mundo. Es importante que menciones todos los componentes que hay en este lugar. Sin embargo, es mejor si no describes cada componente: basta con que los menciones con una mínima descripción poco específica. Es muy importante que nombres los lugares a los que puede acceder el jugador desde esta posición. \n"
87
  elif len(previous_narrations)==0:
88
- prompt += "Ten en cuenta que el jugador ya conoce a su personaje, y cómo se ve, así que no menciones nada sobre esto. Sin embargo, es la primera vez que el jugador visita este lugar, así que describelo. Es importante que menciones todos los componentes que hay en este lugar. Sin embargo, es mejor si no describes cada componente: basta con que los menciones con una mínima descripción poco específica. Es muy importante que nombres los lugares a los que puede acceder el jugador desde esta posición. \n"
89
  else:
90
- prompt += "Ten en cuenta que el jugador ya conoce a su personaje, y cómo se ve, así que no menciones nada sobre esto. Además, no es la primera vez que el jugador visita este lugar. A continuación te daré algunas narraciones previas de este mismo lugar (de la más antigua a la más nueva), así te puedes asegurar de no repetir los mismos detalles de nuevo:\n"
91
  for narration in previous_narrations:
92
- prompt+=f'- {narration}\n'
93
 
94
- prompt+= "\nRecuerda: le estás hablando al jugador, describiendo lo que su personaje tiene y lo que puede sentir o ver."
95
 
96
- prompt +=f"""Este es el estado del mundo en este momnto:
97
  {world_state}
98
  """
99
 
100
- return prompt
101
 
102
- def prompt_world_update (world_state: str, input: str, language: str = 'en') -> str:
103
- prompt = ""
 
104
 
105
  if language == 'es':
106
- prompt = prompt_world_update_spanish(world_state, input)
107
  else:
108
- prompt = prompt_world_update_english(world_state, input)
109
 
110
 
111
- return prompt
112
 
113
- def prompt_world_update_spanish (world_state: str, input: str) -> str:
114
- prompt = f"""Eres un narrador. Estás manejando un mundo ficticio, y el jugador puede interactuar con él. Siguiendo un formato específico, que voy a explicarte más abajo, tu tarea es encontrar los cambios en el mundo a raíz de las acciones del jugador. En específico, tendrás que encontrar qué objetos cambiaron de lugar, qué pasajes entre lugares se desbloquearon y si el jugador se movió de lugar.
115
 
116
  Aquí hay algunas aclaraciones:
117
  (A) Presta atención a a la descripción de los componentes y sus capacidades.
@@ -184,17 +191,17 @@ def prompt_world_update_spanish (world_state: str, input: str) -> str:
184
  - Moved object: None
185
  - Blocked passages now available: None
186
  - Your location changed: None
187
- # Respuesta a la pregunta del jugador #
188
 
189
 
190
- Ahora, expresa los cambios en el mundo siguiendo el formato pedido, teniendo en cuenta que el jugador ingresó esta entrada "{input}" a partir de este estado del mundo:
191
 
192
  {world_state}"""
193
 
194
- return prompt
195
 
196
- def prompt_world_update_english (world_state: str, input: str) -> str:
197
- prompt = f"""You are a storyteller. You are managing a fictional world, and the player can interact with it. Following a specific format, that I will specify below, your task is to find the changes in the world after the actions in the player input. Specifically, you will have to find what objects were moved, which previously blocked passages are now unblocked, and if the player moved to a new place.
198
 
199
  Here are some clarifications:
200
  (A) Pay attention to the description of the components and their capabilities.
@@ -267,11 +274,11 @@ def prompt_world_update_english (world_state: str, input: str) -> str:
267
  - Moved object: None
268
  - Blocked passages now available: None
269
  - Your location changed: None
270
- # Answer to the player's question #
271
 
272
 
273
- Now, give the changes in the world following the specified format, after this player input "{input}" on this world state:
274
 
275
  {world_state}"""
276
 
277
- return prompt
 
1
+ def prompt_describe_objective (objective, language:str = 'en'):
2
+ system_msg = ""
3
+ user_msg = ""
4
 
5
  if language == 'es':
6
+ system_msg, user_msg = prompt_describe_objective_spanish(objective)
7
  else:
8
+ system_msg, user_msg = prompt_describe_objective_english(objective)
9
 
10
+ return system_msg, user_msg
11
 
12
+ def prompt_describe_objective_english (objective):
13
+
14
+ system_msg = """You have to provide an alternative way to narrate the objective given to you. You should always use simple language.
15
+
16
+ Always put your generated narration between # characters. For example: # You have to get the <key> # or # You have to reach the <castle> #"""
17
 
 
18
  first_component_class = objective[0].__class__.__name__
19
  second_component_class = objective[1].__class__.__name__
20
+ user_msg = ""
21
 
22
  if first_component_class == "Character" and second_component_class == "Location":
23
+ user_msg = f'The objective to narrate in an alterative way is "You have to go to <{objective[1].name}>."'
24
  elif first_component_class == "Character" and second_component_class == "Item":
25
+ user_msg = f'The objective to narrate in an alterative way is "<{objective[0].name}> has to get the item <{objective[1].name}>."'
26
  elif first_component_class == "Item" and second_component_class == "Location":
27
+ user_msg = f'The objective to narrate in an alterative way is "You have to leave item <{objective[0].name}> in place <{objective[1].name}>."'
28
  elif first_component_class == "Character" and second_component_class == "Character":
29
+ user_msg = f'The objective to narrate in an alterative way is "<{objective[0].name}> has to find <{objective[1].name}>."'
30
 
31
+ return system_msg, user_msg
32
 
33
+ def prompt_describe_objective_spanish (objective):
34
 
35
+ system_msg = """Tienes que dar una forma alternativa de narrar el objetivo que se te dará. Siempre usa lenguaje simple.
36
+
37
+ Pon siempre tu narración generada entre caracteres #. Por ejemplo: # Tienes que conseguir la <llave> # o # Tienes que llegaral <Castillo> #"""
38
 
 
39
  first_component_class = objective[0].__class__.__name__
40
  second_component_class = objective[1].__class__.__name__
41
+ user_msg = ""
42
 
43
  if first_component_class == "Character" and second_component_class == "Location":
44
+ user_msg = f'El objetivo a decir de forma alternativa es "Tienes que ir a <{objective[1].name}>."'
45
  elif first_component_class == "Character" and second_component_class == "Item":
46
+ user_msg = f'El objetivo a decir de forma alternativa es "<{objective[0].name}> tiene que conseguir el objeto <{objective[1].name}>."'
47
  elif first_component_class == "Item" and second_component_class == "Location":
48
+ user_msg = f'El objetivo a decir de forma alternativa es "Tienes que dejar el objeto <{objective[0].name}> en el lugar <{objective[1].name}>."'
49
  elif first_component_class == "Character" and second_component_class == "Character":
50
+ user_msg = f'El objetivo a decir de forma alternativa es "<{objective[0].name}> tiene que encontrar a <{objective[1].name}>."'
 
 
51
 
52
+ return system_msg, user_msg
53
 
54
+ def prompt_narrate_current_scene (world_state: str, previous_narrations: 'list[str]', language: str = 'en', starting_scene: bool = False):
55
+ system_msg = ""
56
+ user_msg = ""
57
 
58
  if language == 'es':
59
+ system_msg, user_msg = prompt_narrate_current_scene_spanish(world_state, previous_narrations, starting_scene)
60
  else:
61
+ system_msg, user_msg = prompt_narrate_current_scene_english(world_state, previous_narrations, starting_scene)
62
 
63
 
64
+ return system_msg, user_msg
65
 
66
+ def prompt_narrate_current_scene_english (world_state: str, previous_narrations: 'list[str]', starting_scene: bool = False):
67
 
68
+ system_msg = "You are a storyteller. Take the state of the world given to you and narrate it in a few sentences. Be careful not to include details that contradict the current state of the world or that move the story forward. Also, try to use simple sentences and do not overuse poetic language"
69
 
70
  if starting_scene:
71
+ system_msg += "\nTake into account that this is the first scene in the story: introduce the main character, creating a small background story and why that character is in that specific location.\n"
72
  elif len(previous_narrations)==0:
73
+ system_msg += "Take into account that the player already knows what the main character looks like, so do not mention anything about that. However, it is the first time the player visits this place, so make sure to describe it exhaustively."
74
  else:
75
+ system_msg += "Take into account that the player already knows what the main character looks like, so do not mention anything about that. Additionally, it is not the first time the player visits this place. Next I’ll give you some previous narrations of this same location (from oldest to newest) so you can be sure to not repeat the same details again:\n"
76
  for narration in previous_narrations:
77
+ system_msg+=f'- {narration}\n'
78
 
79
+ system_msg+= "\nRemember: you are talking to the player, describing what his or her character has and what he or she can see or feel."
80
 
81
+ user_msg =f"""This is the state of the world at the moment:
82
  {world_state}
83
  """
84
 
85
+ return system_msg, user_msg
86
 
87
+ def prompt_narrate_current_scene_spanish (world_state: str, previous_narrations: 'list[str]', starting_scene: bool = False):
88
 
89
+ system_msg = f"""Eres un narrador. Toma el estado del mundo que se te de y nárralo en unas pocas oraciones. Ten cuidado de no incluir detalles que contradigan el estado del mundo actual, o que hagan avanzar la historia. Además, intenta usar oraciones simples, sin abusar del lenguaje poético."""
90
 
91
  if starting_scene:
92
+ system_msg += "\nTen en cuenta que esta es la primera escena en la historia narrada: presenta al personaje del jugador, creando un pequeño trasfondo y por qué este personaje está en ese lugar específicamente. Puede usar las pequeñas descripciones presentes en el estado del mundo. Es importante que menciones todos los componentes que hay en este lugar. Sin embargo, es mejor si no describes cada componente: basta con que los menciones con una mínima descripción poco específica. Es muy importante que nombres los lugares a los que puede acceder el jugador desde esta posición. \n"
93
  elif len(previous_narrations)==0:
94
+ system_msg += "Ten en cuenta que el jugador ya conoce a su personaje, y cómo se ve, así que no menciones nada sobre esto. Sin embargo, es la primera vez que el jugador visita este lugar, así que describelo. Es importante que menciones todos los componentes que hay en este lugar. Sin embargo, es mejor si no describes cada componente: basta con que los menciones con una mínima descripción poco específica. Es muy importante que nombres los lugares a los que puede acceder el jugador desde esta posición. \n"
95
  else:
96
+ system_msg += "Ten en cuenta que el jugador ya conoce a su personaje, y cómo se ve, así que no menciones nada sobre esto. Además, no es la primera vez que el jugador visita este lugar. A continuación te daré algunas narraciones previas de este mismo lugar (de la más antigua a la más nueva), así te puedes asegurar de no repetir los mismos detalles de nuevo:\n"
97
  for narration in previous_narrations:
98
+ system_msg+=f'- {narration}\n'
99
 
100
+ system_msg+= "\nRecuerda: le estás hablando al jugador, describiendo lo que su personaje tiene y lo que puede sentir o ver."
101
 
102
+ user_msg = f"""Este es el estado del mundo en este momento:
103
  {world_state}
104
  """
105
 
106
+ return system_msg, user_msg
107
 
108
+ def prompt_world_update (world_state: str, input: str, language: str = 'en'):
109
+ system_msg = ""
110
+ user_msg = ""
111
 
112
  if language == 'es':
113
+ system_msg, user_msg = prompt_world_update_spanish(world_state, input)
114
  else:
115
+ system_msg, user_msg = prompt_world_update_english(world_state, input)
116
 
117
 
118
+ return system_msg, user_msg
119
 
120
+ def prompt_world_update_spanish (world_state: str, input: str):
121
+ system_msg = f"""Eres un narrador. Estás manejando un mundo ficticio, y el jugador puede interactuar con él. Siguiendo un formato específico, que voy a explicarte más abajo, tu tarea es encontrar los cambios en el mundo a raíz de las acciones del jugador. En específico, tendrás que encontrar qué objetos cambiaron de lugar, qué pasajes entre lugares se desbloquearon y si el jugador se movió de lugar.
122
 
123
  Aquí hay algunas aclaraciones:
124
  (A) Presta atención a a la descripción de los componentes y sus capacidades.
 
191
  - Moved object: None
192
  - Blocked passages now available: None
193
  - Your location changed: None
194
+ # Respuesta a la pregunta del jugador #"""
195
 
196
 
197
+ user_msg = f"""Expresa los cambios en el mundo siguiendo el formato pedido, teniendo en cuenta que el jugador ingresó esta entrada "{input}" a partir de este estado del mundo:
198
 
199
  {world_state}"""
200
 
201
+ return system_msg, user_msg
202
 
203
+ def prompt_world_update_english (world_state: str, input: str):
204
+ system_msg = f"""You are a storyteller. You are managing a fictional world, and the player can interact with it. Following a specific format, that I will specify below, your task is to find the changes in the world after the actions in the player input. Specifically, you will have to find what objects were moved, which previously blocked passages are now unblocked, and if the player moved to a new place.
205
 
206
  Here are some clarifications:
207
  (A) Pay attention to the description of the components and their capabilities.
 
274
  - Moved object: None
275
  - Blocked passages now available: None
276
  - Your location changed: None
277
+ # Answer to the player's question #"""
278
 
279
 
280
+ user_msg = f"""Give the changes in the world following the specified format, after this player input "{input}" on this world state:
281
 
282
  {world_state}"""
283
 
284
+ return system_msg, user_msg