Skip to content

Commit 6a4eafd

Browse files
committed
Factor build_chat_context out to function
1 parent 10b90f7 commit 6a4eafd

File tree

1 file changed

+25
-18
lines changed

1 file changed

+25
-18
lines changed

web-apps/chat/app.py

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -61,30 +61,37 @@ class PossibleSystemPromptException(Exception):
6161
streaming=True,
6262
)
6363

64+
def build_chat_context(latest_message, history):
65+
"""
66+
Build the chat context from the latest message and history.
67+
"""
68+
context = []
69+
if INCLUDE_SYSTEM_PROMPT:
70+
context.append(SystemMessage(content=settings.model_instruction))
71+
else:
72+
# Mimic system prompt by prepending it to first human message
73+
history[0]['content'] = f"{settings.model_instruction}\n\n{history[0]['content']}"
74+
75+
for message in history:
76+
role = message['role']
77+
content = message['content']
78+
if role == "user":
79+
context.append(HumanMessage(content=content))
80+
else:
81+
if role != "assistant":
82+
log.warn(f"Message role {role} converted to 'assistant'")
83+
context.append(AIMessage(content=(content or "")))
84+
context.append(HumanMessage(content=latest_message))
85+
return context
86+
87+
6488
def inference(latest_message, history):
6589
# Allow mutating global variable
6690
global BACKEND_INITIALISED
6791
log.debug("Inference request received with history: %s", history)
6892

6993
try:
70-
context = []
71-
if INCLUDE_SYSTEM_PROMPT:
72-
context.append(SystemMessage(content=settings.model_instruction))
73-
else:
74-
# Mimic system prompt by prepending it to first human message
75-
history[0]['content'] = f"{settings.model_instruction}\n\n{history[0]['content']}"
76-
77-
for message in history:
78-
role = message['role']
79-
content = message['content']
80-
if role == "user":
81-
context.append(HumanMessage(content=content))
82-
else:
83-
if role != "assistant":
84-
log.warn(f"Message role {role} converted to 'assistant'")
85-
context.append(AIMessage(content=(content or "")))
86-
context.append(HumanMessage(content=latest_message))
87-
94+
context = build_chat_context(latest_message, history)
8895
log.debug("Chat context: %s", context)
8996

9097
response = ""

0 commit comments

Comments
 (0)