Skip to content

Commit fd008e5

Browse files
committed
Fix Gradio inference function in chat app
Gradio v5 changed required function signature for inference function from tuples of (human, ai) message to flat list of messages. This was not caught by the automated testing because AFAICT the Gradio python client doesn't provide a way to send multiple messages to create a conversation.
1 parent a56e0ab commit fd008e5

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

web-apps/chat/app.py

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -66,19 +66,27 @@ def inference(latest_message, history):
6666
global BACKEND_INITIALISED
6767

6868
try:
69+
context = []
6970
if INCLUDE_SYSTEM_PROMPT:
70-
context = [SystemMessage(content=settings.model_instruction)]
71+
context.append(SystemMessage(content=settings.model_instruction))
7172
else:
72-
context = []
73-
for i, (human, ai) in enumerate(history):
74-
if not INCLUDE_SYSTEM_PROMPT and i == 0:
75-
# Mimic system prompt by prepending it to first human message
76-
human = f"{settings.model_instruction}\n\n{human}"
77-
context.append(HumanMessage(content=human))
78-
context.append(AIMessage(content=(ai or "")))
73+
# Mimic system prompt by prepending it to first human message
74+
history[0]['content'] = f"{settings.model_instruction}\n\n{history[0]['content']}"
75+
76+
for message in history:
77+
role = message['role']
78+
content = message['content']
79+
if role == "user":
80+
context.append(HumanMessage(content=content))
81+
else:
82+
if role != "assistant":
83+
log.warn(f"Message role {role} converted to 'assistant'")
84+
context.append(AIMessage(content=(content or "")))
7985
context.append(HumanMessage(content=latest_message))
86+
8087
log.debug("Chat context: %s", context)
8188

89+
8290
response = ""
8391
for chunk in llm.stream(context):
8492
# If this is our first successful response from the backend
@@ -109,6 +117,7 @@ def inference(latest_message, history):
109117
raise gr.Error(ui_message)
110118

111119
except openai.APIConnectionError as err:
120+
log.info(err)
112121
if not BACKEND_INITIALISED:
113122
log.info("Backend API not yet ready")
114123
gr.Info(

0 commit comments

Comments
 (0)