Skip to content

Commit

Permalink
Add lf.Template.raw_str and lf.Template.from_raw_str.
Browse files Browse the repository at this point in the history
This makes it easier for users to include raw strings in the prompt.

PiperOrigin-RevId: 676015977
  • Loading branch information
daiyip authored and langfun authors committed Sep 18, 2024
1 parent 67848eb commit 894610c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
10 changes: 10 additions & 0 deletions langfun/core/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,16 @@ def missing_vars(self) -> Set[str]:
"""Returns the missing variable names."""
return self.vars(closure=True, specified=False)

@classmethod
def raw_str(cls, text: str) -> str:
"""Returns a template string that preserve the text as original."""
return '{% raw %}' + text + '{% endraw %}'

@classmethod
def from_raw_str(cls, text: str) -> 'Template':
"""Returns a template that preserve the text as original."""
return cls(cls.raw_str(text), clean=False)

def render(
self,
*,
Expand Down
15 changes: 15 additions & 0 deletions langfun/core/template_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,21 @@ class Foo(component.Component):
self.assertEqual(d.z.render(), 'Bye, 1')
self.assertEqual(d.p.render(), 'Again Hello, 1')

def test_raw_text(self):
self.assertEqual(
Template(
'{{a}}' + Template.raw_str('\n{{d}}, {%x%}\n') + '{{b}}',
a='hi', b=1
).render().text,
'hi\n{{d}}, {%x%}\n1'
)

def test_from_raw_str(self):
self.assertEqual(
Template.from_raw_str('\n{{d}}, {%x%}\n').render().text,
'\n{{d}}, {%x%}\n'
)


class DefinitionTest(unittest.TestCase):

Expand Down

0 comments on commit 894610c

Please sign in to comment.