Skip to content

Commit 39c0ae7

Browse files
committed
code review
1 parent ce93eda commit 39c0ae7

2 files changed

Lines changed: 44 additions & 22 deletions

File tree

langfuse/model.py

Lines changed: 41 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import re
44
from abc import ABC, abstractmethod
5+
from collections.abc import Iterable
56
from typing import Any, Dict, List, Literal, Optional, Tuple, TypedDict, Union
67

78
from langfuse.api.resources.commons.types.dataset import (
@@ -296,7 +297,7 @@ def __init__(self, prompt: Prompt_Chat, is_fallback: bool = False):
296297
self.prompt: List[ChatMessageWithPlaceholdersDict] = []
297298

298299
for p in prompt.prompt:
299-
if hasattr(p, "type") and hasattr(p, "name"):
300+
if hasattr(p, "type") and hasattr(p, "name") and p.type == "placeholder":
300301
self.prompt.append(
301302
ChatMessageWithPlaceholdersDict_Placeholder(
302303
type="placeholder",
@@ -313,16 +314,21 @@ def __init__(self, prompt: Prompt_Chat, is_fallback: bool = False):
313314
)
314315

315316
def compile(self, **kwargs) -> List[ChatMessageDict]:
316-
return [
317-
ChatMessageDict(
318-
content=TemplateParser.compile_template(
319-
chat_message["content"], kwargs
320-
),
321-
role=chat_message["role"],
322-
)
323-
for chat_message in self.prompt
324-
if chat_message["type"] == "message"
325-
]
317+
compiled_messages: List[ChatMessageDict] = []
318+
for chat_message in self.prompt:
319+
if chat_message["type"] == "message":
320+
compiled_messages.append(
321+
ChatMessageDict(
322+
content=TemplateParser.compile_template(
323+
chat_message["content"], kwargs
324+
),
325+
role=chat_message["role"],
326+
)
327+
)
328+
elif chat_message["type"] == "placeholder":
329+
placeholder_in_compile_error = f"Called compile on chat client with placeholder: {chat_message['name']}. Please use compile_with_placeholders instead."
330+
raise ValueError(placeholder_in_compile_error)
331+
return compiled_messages
326332

327333
@property
328334
def variables(self) -> List[str]:
@@ -342,22 +348,29 @@ def __eq__(self, other):
342348
and len(self.prompt) == len(other.prompt)
343349
and all(
344350
# chatmessage equality
345-
(m1["type"] == "message" and m2["type"] == "message"
346-
and m1["role"] == m2["role"] and m1["content"] == m2["content"])
351+
(
352+
m1["type"] == "message"
353+
and m2["type"] == "message"
354+
and m1["role"] == m2["role"]
355+
and m1["content"] == m2["content"]
356+
)
347357
or
348358
# placeholder equality
349-
(m1["type"] == "placeholder" and m2["type"] == "placeholder"
350-
and m1["name"] == m2["name"])
359+
(
360+
m1["type"] == "placeholder"
361+
and m2["type"] == "placeholder"
362+
and m1["name"] == m2["name"]
363+
)
351364
for m1, m2 in zip(self.prompt, other.prompt)
352365
)
353366
and self.config == other.config
354367
)
355368

356369
return False
357370

358-
def compileWithPlaceholders(
371+
def compile_with_placeholders(
359372
self,
360-
variables: Dict[str, Any],
373+
variables: Dict[str, str],
361374
placeholders: Dict[str, List[ChatMessageDict]],
362375
) -> List[ChatMessageDict]:
363376
"""Compile chat prompt by first replacing placeholders, then expanding variables.
@@ -374,7 +387,17 @@ def compileWithPlaceholders(
374387
# Subsitute the placeholders for their supplied ChatMessages
375388
for item in self.prompt:
376389
if item["type"] == "placeholder" and item["name"] in placeholders:
377-
messages_with_placeholders_replaced.extend(placeholders[item["name"]])
390+
if (
391+
isinstance(placeholders[item["name"]], Iterable)
392+
and len(placeholders[item["name"]]) > 0
393+
):
394+
messages_with_placeholders_replaced.extend(
395+
placeholders[item["name"]]
396+
)
397+
else:
398+
raise ValueError(
399+
f"The provided placeholder: {item['name']} is empty"
400+
)
378401
elif item["type"] == "message":
379402
messages_with_placeholders_replaced.append(
380403
ChatMessageDict(
@@ -393,7 +416,6 @@ def compileWithPlaceholders(
393416
role=chat_message["role"],
394417
)
395418
for chat_message in messages_with_placeholders_replaced
396-
if "role" in chat_message and "content" in chat_message
397419
]
398420

399421
def get_langchain_prompt(self, **kwargs):

tests/test_prompt.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ def test_create_chat_prompt_with_placeholders():
109109

110110
second_prompt_client = langfuse.get_prompt(prompt_name, type="chat")
111111

112-
messages = second_prompt_client.compileWithPlaceholders(
112+
messages = second_prompt_client.compile_with_placeholders(
113113
variables={"role": "helpful", "task": "coding"},
114114
placeholders={
115115
"history": [
@@ -269,7 +269,7 @@ def test_get_prompt_with_placeholders():
269269
def test_compile_with_placeholders(
270270
variables, placeholders, expected_len, expected_contents
271271
):
272-
"""Test compileWithPlaceholders with different variable/placeholder combinations."""
272+
"""Test compile_with_placeholders with different variable/placeholder combinations."""
273273
from langfuse.api.resources.prompts import Prompt_Chat
274274
from langfuse.model import ChatPromptClient
275275

@@ -287,7 +287,7 @@ def test_compile_with_placeholders(
287287
],
288288
)
289289

290-
result = ChatPromptClient(mock_prompt).compileWithPlaceholders(
290+
result = ChatPromptClient(mock_prompt).compile_with_placeholders(
291291
variables, placeholders
292292
)
293293

0 commit comments

Comments
 (0)