1
+ import re
1
2
from typing import List , Optional
2
3
4
+ from fastapi_sqlalchemy import db
5
+
6
+ from models .agent import AgentModel
3
7
from typings .agent import AgentWithConfigsOutput
8
+ from utils .agent import convert_model_to_response
4
9
5
10
6
11
class SystemMessageBuilder :
@@ -24,6 +29,7 @@ def build(self) -> str:
24
29
context = self .build_pre_retrieved_context (self .pre_retrieved_context )
25
30
26
31
result = f"{ base_system_message } { role } { description } { goals } { instructions } { constraints } { context } "
32
+ result = self .replace_templates (result )
27
33
return result
28
34
29
35
def build_base_system_message (self , text : str ) -> str :
@@ -80,3 +86,53 @@ def build_pre_retrieved_context(self, text: str):
80
86
result = "CONTEXT DATA: \n " f"{ text } \n "
81
87
82
88
return result
89
+
90
+ def replace_templates (self , text : str ) -> str :
91
+ # This pattern will match strings like {{agent.sales.greeting}} and {{greeting}}
92
+ pattern = re .compile (
93
+ r"\{\{(agent\.(?P<agent_name>[\w\s]+?)\.)?(?P<field_name>\w+)(\[(?P<index>\d+)\])?\}\}"
94
+ )
95
+
96
+ def replace_match (match ):
97
+ agent_name = match .group ("agent_name" )
98
+ field_name = match .group ("field_name" )
99
+ index = match .group ("index" )
100
+
101
+ if agent_name :
102
+ # Fetch agent by name
103
+ agent = AgentModel .get_agent_by_name (
104
+ db .session , self .agent .account_id , agent_name
105
+ )
106
+ agent_data = convert_model_to_response (agent )
107
+ source_data = (
108
+ agent_data .agent
109
+ if hasattr (agent_data .agent , field_name )
110
+ else agent_data .configs
111
+ )
112
+ else :
113
+ # Use current agent if no agent name is provided
114
+ source_data = (
115
+ self .agent if hasattr (self .agent , field_name ) else self .configs
116
+ )
117
+
118
+ if not source_data :
119
+ return match .group (
120
+ 0
121
+ ) # Return the original text if agent or property not found
122
+
123
+ # Retrieve the field value
124
+ value = getattr (source_data , field_name , "Unknown field" )
125
+ if index and isinstance (value , list ):
126
+ try :
127
+ value = value [int (index )]
128
+ except IndexError :
129
+ value = "Index out of range"
130
+ elif isinstance (value , list ):
131
+ # Format the list for display
132
+ value = f"{ field_name .upper ()} : \n " + "\n " .join (
133
+ f"- { item } " for item in value
134
+ )
135
+
136
+ return str (value )
137
+
138
+ return pattern .sub (replace_match , text )
0 commit comments