Skip to content

Commit

Permalink
fix(dspy): Fix template.extract to be more robust
Browse files Browse the repository at this point in the history
  • Loading branch information
dat-boris committed Jun 2, 2024
1 parent 8e01bee commit 626e048
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
11 changes: 11 additions & 0 deletions dsp/templates/template_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,18 @@ def extract(

import dspy

# This should point at the first output field.
# So we can start truncating raw_pred from this point.
idx = min(idx, len(self.fields) - 1)

# Before that, truncate raw_pred to the output prefix - sometimes
# we see the input fields was also included in the completion.
# see test_predict.py:test_single_output_with_noise tests
next_field_name = "\n" + self.fields[idx].name
offset = raw_pred.find(next_field_name)
if offset >= 0:
raw_pred = raw_pred[offset + len(next_field_name):].strip()

while raw_pred != "" and idx < len(self.fields):
if idx < len(self.fields) - 1:
next_field_name = "\n" + self.fields[idx + 1].name
Expand Down
17 changes: 17 additions & 0 deletions tests/predict/test_predict.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,23 @@ def test_config_management():
assert "new_key" in config and config["new_key"] == "value"


def test_single_output():
program = Predict("question -> answer")
dspy.settings.configure(lm=DummyLM(["my answer"]))
results = program(question="What is 1+1?")
assert results.completions.answer[0] == "my answer"


def test_single_output_with_noise():
"""Sometimes we see question was also listed as an output."""
program = Predict("question -> answer")
dspy.settings.configure(lm=DummyLM([
"Question: What is 1+1?\nAnswer: my answer"
]))
results = program(question="What is 1+1?")
assert results.completions.answer[0] == "my answer"


def test_multi_output():
program = Predict("question -> answer", n=2)
dspy.settings.configure(lm=DummyLM(["my first answer", "my second answer"]))
Expand Down

0 comments on commit 626e048

Please sign in to comment.