Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

feat: enhance FewShotGenerator (#1896)

hallerite98bbe6a730d0
diff --git a/camel/datasets/__init__.py b/camel/datasets/__init__.py
index 96d9783e7..481452410 100644
--- a/camel/datasets/__init__.py
+++ b/camel/datasets/__init__.py
@@ -11,10 +11,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
-from .base_generator import (
- BaseGenerator,
- FewShotGenerator,
-)
+from .base_generator import BaseGenerator
+from .few_shot_generator import FewShotGenerator
from .models import DataPoint
from .static_dataset import StaticDataset
diff --git a/camel/datasets/base_generator.py b/camel/datasets/base_generator.py
index 6d013d715..de5aa75fb 100644
--- a/camel/datasets/base_generator.py
+++ b/camel/datasets/base_generator.py
@@ -15,22 +15,12 @@
import abc
import json
import random
-from datetime import datetime
from pathlib import Path
-from typing import (
- List,
- Union,
-)
+from typing import List, Union
-from pydantic import ValidationError
-
-from camel.agents import ChatAgent
from camel.logger import get_logger
-from camel.verifiers import BaseVerifier
-from camel.verifiers.models import VerifierInput
from .models import DataPoint
-from .static_dataset import StaticDataset
logger = get_logger(__name__)
@@ -126,210 +116,3 @@ class BaseGenerator(abc.ABC):
except IOError as e:
logger.error(f"Error writing to file {file_path}: {e}")
raise
-
-
-class FewShotGenerator(BaseGenerator):
- r"""A generator for creating synthetic datapoints using few-shot learning.
-
- This class leverages a seed dataset, an agent, and a verifier to generate
- new synthetic datapoints on demand through few-shot prompting.
- """
-
- def __init__(
- self,
- seed_dataset: StaticDataset,
- verifier: BaseVerifier,
- agent: ChatAgent,
- seed: int = 42,
- **kwargs,
- ):
- r"""Initialize the few-shot generator.
-
- Args:
- seed_dataset (StaticDataset): Validated static dataset to
- use for examples.
- verifier (BaseVerifier): Verifier to validate generated content.
- agent (ChatAgent): Agent to generate new datapoints.
- seed (int): Random seed for reproducibility. (default: :obj:`42`)
- **kwargs: Additional generator parameters.
- """
- super().__init__(seed=seed, **kwargs)
- self.seed_dataset = seed_dataset
- try:
- self._validate_seed_dataset()
- except Exception:
- raise RuntimeError("Seed Data does not follow Datapoint format")
- self.verifier = verifier
- self.agent = agent
-
- # TODO: Validate that seed dataset contains rationale
- def _validate_seed_dataset(self) -> None:
- pass
-
- def _construct_prompt(self, examples: List[DataPoint]) -> str:
- r"""Construct a prompt for generating new datapoints
- using a fixed sample of examples from the seed dataset.
-
- Args:
- examples (List[DataPoint]): Examples to include in the prompt.
-
- Returns:
- str: Formatted prompt with examples.
- """
- prompt = (
- "Generate a new datapoint similar to the following examples:\n\n"
- )
- for i, example in enumerate(examples, 1):
- prompt += f"Example {i}:\n"
- prompt += f"Question: {example.question}\n"
- if example.rationale is not None:
- prompt += f"Rationale: {example.rationale}\n"
- else:
- prompt += "Rationale: None\n"
- prompt += f"Final Answer: {example.final_answer}\n\n"
- prompt += "New datapoint:"
- return prompt
-
- async def generate_new(
- self,
- n: int,
- max_retries: int = 10,
- num_examples: int = 3,
- **kwargs,
- ) -> List[DataPoint]:
- r"""Generates and validates `n` new datapoints through
- few-shot prompting, with a retry limit.
-
- Steps:
- 1. Samples examples from the seed dataset.
- 2. Constructs a prompt using the selected examples.
- 3. Uses an agent to generate a new datapoint,
- consisting of a question and code to solve the question.
- 4. Executes code using a verifier to get pseudo ground truth.
- 5. Stores valid datapoints in memory.
-
- Args:
- n (int): Number of valid datapoints to generate.
- max_retries (int): Maximum number of retries before stopping.
- (default: :obj:`10`)
- num_examples (int): Number of examples to sample from the
- seed dataset for few shot prompting.
- (default: :obj:`3`)
- **kwargs: Additional generation parameters.
-
- Returns:
- List[DataPoint]: A list of newly generated valid datapoints.
-
- Raises:
- TypeError: If the agent's output is not a dictionary (or does not
- match the expected format).
- KeyError: If required keys are missing from the response.
- AttributeError: If the verifier response lacks attributes.
- ValidationError: If a datapoint fails schema validation.
- RuntimeError: If retries are exhausted before `n` valid datapoints
- are generated.
-
- Notes:
- - Retries on validation failures until `n` valid datapoints exist
- or `max_retries` is reached, whichever comes first.
- - If retries are exhausted before reaching `n`, a `RuntimeError`
- is raised.
- - Metadata includes a timestamp for tracking datapoint creation.
- """
- valid_data_points: List[DataPoint] = []
- retries = 0
-
- while len(valid_data_points) < n and retries < max_retries:
- try:
- examples = [
- self.seed_dataset.sample() for _ in range(num_examples)
- ]
- prompt = self._construct_prompt(examples)
-
- try:
- agent_output = (
- self.agent.step(prompt, response_format=DataPoint)
- .msgs[0]
- .parsed
- )
- if not isinstance(agent_output, dict):
- raise TypeError("Agent output must be a dictionary")
- if "question" not in agent_output:
- raise KeyError(
- "Missing 'question' in agent"
- f"output {agent_output}"
- )
- if "rationale" not in agent_output:
- raise KeyError(
- "Missing 'rationale' in agent"
- f"output {agent_output}"
- )
- except (TypeError, KeyError) as e:
- logger.warning(
- f"Agent output issue: {e}, retrying... "
- f"({retries + 1}/{max_retries})"
- )
- retries += 1
- continue
-
- rationale = agent_output.get("rationale")
-
- if not isinstance(rationale, str):
- raise TypeError(f"Rationale {rationale} is not a string.")
-
- try:
- verifier_response = await self.verifier.verify(
- VerifierInput(
- llm_response=rationale,
- ground_truth=None,
- )
- )
- if not verifier_response or not verifier_response.result:
- raise ValueError(
- "Verifier unsuccessful, response: "
- f"{verifier_response}"
- )
- except (ValueError, AttributeError) as e:
- logger.warning(
- f"Verifier issue: {e}, "
- f"retrying... ({retries + 1}/{max_retries})"
- )
- retries += 1
- continue
-
- try:
- new_datapoint = DataPoint(
- question=agent_output["question"],
- rationale=rationale,
- final_answer=verifier_response.result,
- metadata={
- "synthetic": str(True),
- "created": datetime.now().isoformat(),
- "generator": "few_shot",
- },
- )
- except ValidationError as e:
- logger.warning(
- f"Datapoint validation failed: {e}, "
- f"retrying... ({retries + 1}/{max_retries})"
- )
- retries += 1
- continue
-
- valid_data_points.append(new_datapoint)
-
- except Exception as e:
- logger.warning(
- f"Unexpected error: {e}, retrying..."
- f" ({retries + 1}/{max_retries})"
- )
- retries += 1
-
- if len(valid_data_points) < n:
- raise RuntimeError(
- f"Failed to generate {n} valid datapoints "
- f"after {max_retries} retries."
- )
-
- self._data.extend(valid_data_points)
- return valid_data_points
diff --git a/camel/datasets/few_shot_generator.py b/camel/datasets/few_shot_generator.py
new file mode 100644
index 000000000..fbe44f558
--- /dev/null
+++ b/camel/datasets/few_shot_generator.py
@@ -0,0 +1,261 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+
+import asyncio
+from datetime import datetime
+from typing import List
+
+from pydantic import ValidationError
+
+from camel.agents import ChatAgent
+from camel.logger import get_logger
+from camel.models.base_model import BaseModelBackend
+from camel.verifiers import BaseVerifier
+from camel.verifiers.models import VerifierInput
+
+from .base_generator import BaseGenerator
+from .models import DataPoint
+from .static_dataset import StaticDataset
+
+logger = get_logger(__name__)
+
+SYSTEM_PROMPT = """**You are an advanced data generation assistant.**
+Your goal is to generate high-quality synthetic data points based on
+provided examples. Your output must be well-structured,
+logically sound, and formatted correctly.
+
+**Instructions:**
+1. **Follow the Structure**
+ Each data point must include:
+ - **Question**: A clear, well-formed query.
+ - **Rationale**: A step-by-step, executable reasoning process ending
+ with `print(final_answer)`.
+ - **Final Answer**: The correct, concise result.
+
+2. **Ensure Logical Consistency**
+ - The `rationale` must be code that runs correctly.
+ - The `final_answer` should match the printed output.
+
+3. **Output Format (Strict)**
+```
+Question: [Generated question]
+Rationale: [Code that solves the question, ending in a print statement,
+outputting the answer.]
+Final Answer: [The Final Answer]
+
+**Now, generate a new data point based on the given examples.**
+"""
+
+
+class FewShotGenerator(BaseGenerator):
+ r"""A generator for creating synthetic datapoints using few-shot learning.
+
+ This class leverages a seed dataset, an agent, and a verifier to generate
+ new synthetic datapoints on demand through few-shot prompting.
+ """
+
+ def __init__(
+ self,
+ seed_dataset: StaticDataset,
+ verifier: BaseVerifier,
+ model: BaseModelBackend,
+ seed: int = 42,
+ **kwargs,
+ ):
+ r"""Initialize the few-shot generator.
+
+ Args:
+ seed_dataset (StaticDataset): Validated static dataset to
+ use for examples.
+ verifier (BaseVerifier): Verifier to validate generated content.
+ model (BaseModelBackend): The underlying LLM that the generating
+ agent will be initiated with.
+ seed (int): Random seed for reproducibility. (default: :obj:`42`)
+ **kwargs: Additional generator parameters.
+ """
+ super().__init__(seed=seed, **kwargs)
+ self.seed_dataset = seed_dataset
+ try:
+ self._validate_seed_dataset()
+ except Exception:
+ raise RuntimeError("Seed Data does not follow Datapoint format")
+ self.verifier = verifier
+ self.agent = ChatAgent(system_message=SYSTEM_PROMPT, model=model)
+
+ # TODO: Validate that seed dataset contains rationale
+ def _validate_seed_dataset(self) -> None:
+ pass
+
+ def _construct_prompt(self, examples: List[DataPoint]) -> str:
+ r"""Construct a prompt for generating new datapoints
+ using a fixed sample of examples from the seed dataset.
+
+ Args:
+ examples (List[DataPoint]): Examples to include in the prompt.
+
+ Returns:
+ str: Formatted prompt with examples.
+ """
+ prompt = (
+ "Generate a new datapoint similar to the following examples:\n\n"
+ )
+ for i, example in enumerate(examples, 1):
+ prompt += f"Example {i}:\n"
+ prompt += f"Question: {example.question}\n"
+ if example.rationale is not None:
+ prompt += f"Rationale: {example.rationale}\n"
+ else:
+ prompt += "Rationale: None\n"
+ prompt += f"Final Answer: {example.final_answer}\n\n"
+ prompt += "New datapoint:"
+ return prompt
+
+ async def generate_new(
+ self,
+ n: int,
+ max_retries: int = 10,
+ num_examples: int = 3,
+ **kwargs,
+ ) -> List[DataPoint]:
+ r"""Generates and validates `n` new datapoints through
+ few-shot prompting, with a retry limit.
+
+ Steps:
+ 1. Samples examples from the seed dataset.
+ 2. Constructs a prompt using the selected examples.
+ 3. Uses an agent to generate a new datapoint,
+ consisting of a question and code to solve the question.
+ 4. Executes code using a verifier to get pseudo ground truth.
+ 5. Stores valid datapoints in memory.
+
+ Args:
+ n (int): Number of valid datapoints to generate.
+ max_retries (int): Maximum number of retries before stopping.
+ (default: :obj:`10`)
+ num_examples (int): Number of examples to sample from the
+ seed dataset for few shot prompting.
+ (default: :obj:`3`)
+ **kwargs: Additional generation parameters.
+
+ Returns:
+ List[DataPoint]: A list of newly generated valid datapoints.
+
+ Raises:
+ TypeError: If the agent's output is not a dictionary (or does not
+ match the expected format).
+ KeyError: If required keys are missing from the response.
+ AttributeError: If the verifier response lacks attributes.
+ ValidationError: If a datapoint fails schema validation.
+ RuntimeError: If retries are exhausted before `n` valid datapoints
+ are generated.
+
+ Notes:
+ - Retries on validation failures until `n` valid datapoints exist
+ or `max_retries` is reached, whichever comes first.
+ - If retries are exhausted before reaching `n`, a `RuntimeError`
+ is raised.
+ - Metadata includes a timestamp for tracking datapoint creation.
+ """
+ valid_data_points: List[DataPoint] = []
+ retries = 0
+
+ while len(valid_data_points) < n and retries < max_retries:
+ try:
+ examples = [
+ self.seed_dataset.sample() for _ in range(num_examples)
+ ]
+ prompt = self._construct_prompt(examples)
+
+ try:
+ agent_output = (
+ self.agent.step(prompt, response_format=DataPoint)
+ .msgs[0]
+ .parsed
+ )
+
+ assert isinstance(agent_output, DataPoint)
+
+ self.agent.reset()
+
+ except (TypeError, KeyError) as e:
+ logger.warning(
+ f"Agent output issue: {e}, retrying... "
+ f"({retries + 1}/{max_retries})"
+ )
+ retries += 1
+ continue
+
+ rationale = agent_output.rationale
+
+ if not isinstance(rationale, str):
+ raise TypeError(f"Rationale {rationale} is not a string.")
+
+ try:
+ verifier_response = await self.verifier.verify(
+ VerifierInput(
+ llm_response=rationale,
+ ground_truth=None,
+ )
+ )
+ if not verifier_response or not verifier_response.result:
+ raise ValueError(
+ "Verifier unsuccessful, response: "
+ f"{verifier_response}"
+ )
+ except (ValueError, AttributeError) as e:
+ logger.warning(
+ f"Verifier issue: {e}, "
+ f"retrying... ({retries + 1}/{max_retries})"
+ )
+ retries += 1
+ continue
+
+ try:
+ new_datapoint = DataPoint(
+ question=agent_output.question,
+ rationale=rationale,
+ final_answer=verifier_response.result,
+ metadata={
+ "synthetic": str(True),
+ "created": datetime.now().isoformat(),
+ "generator": "few_shot",
+ },
+ )
+ except ValidationError as e:
+ logger.warning(
+ f"Datapoint validation failed: {e}, "
+ f"retrying... ({retries + 1}/{max_retries})"
+ )
+ retries += 1
+ continue
+
+ valid_data_points.append(new_datapoint)
+
+ except Exception as e:
+ logger.warning(
+ f"Unexpected error: {e}, retrying..."
+ f" ({retries + 1}/{max_retries})"
+ )
+ retries += 1
+
+ if len(valid_data_points) < n:
+ raise RuntimeError(
+ f"Failed to generate {n} valid datapoints "
+ f"after {max_retries} retries."
+ )
+
+ # Thread-safe way to extend the data list
+ async with asyncio.Lock():
+ self._data.extend(valid_data_points)
+ return valid_data_points
diff --git a/examples/dataset/few_shot_generator.py b/examples/dataset/few_shot_generator.py
new file mode 100644
index 000000000..dff711036
--- /dev/null
+++ b/examples/dataset/few_shot_generator.py
@@ -0,0 +1,93 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+
+import asyncio
+from pathlib import Path
+
+from dotenv import load_dotenv
+
+from camel.configs import ChatGPTConfig
+from camel.datasets import FewShotGenerator, StaticDataset
+from camel.logger import get_logger
+from camel.models import ModelFactory
+from camel.types import ModelPlatformType, ModelType
+from camel.verifiers import PythonVerifier
+
+logger = get_logger(__name__)
+
+verifier = PythonVerifier(required_packages=["sympy"])
+asyncio.run(verifier.setup())
+
+raw_data2 = [
+ {
+ "question": "Evaluate the limit as x approaches 0 of (sin(3*x) - 3*x) / x**3.", # noqa: E501
+ "final_answer": "-9/2",
+ "rationale": '''from sympy import symbols, limit, sin
+x = symbols('x')
+expr = (sin(3*x) - 3*x) / x**3
+result = limit(expr, x, 0)
+print(result)''',
+ },
+ {
+ "question": "Evaluate the definite integral of (1 - x**2)**3 from x = 0 to x = 1.", # noqa: E501
+ "final_answer": "16/35",
+ "rationale": '''from sympy import symbols, integrate
+x = symbols('x')
+expr = (1 - x**2)**3
+result = integrate(expr, (x, 0, 1))
+print(result)''',
+ },
+ {
+ "question": "Evaluate the limit as n approaches infinity of n*(sqrt(n**2 + 1) - n).", # noqa: E501
+ "final_answer": "1/2",
+ "rationale": '''from sympy import symbols, limit, sqrt
+n = symbols('n', positive=True)
+expr = n*(sqrt(n**2 + 1) - n)
+result = limit(expr, n, float("inf"))
+print(result)''',
+ },
+ {
+ "question": "Compute the sum of the series sum from n = 1 to 50 of 1/(n*(n+1)).", # noqa: E501
+ "final_answer": "50/51",
+ "rationale": '''from sympy import symbols, summation
+n = symbols('n', positive=True, integer=True)
+expr = 1/(n*(n+1))
+result = summation(expr, (n, 1, 50))
+print(result)''',
+ },
+]
+
+seed_dataset = StaticDataset(raw_data2)
+
+
+load_dotenv()
+
+
+model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4O_MINI,
+ model_config_dict=ChatGPTConfig().as_dict(),
+)
+generator = FewShotGenerator(
+ seed_dataset=seed_dataset, verifier=verifier, model=model
+)
+
+new_data = asyncio.run(generator.generate_new(n=2, max_retries=5))
+
+for dp in new_data:
+ print(dp)
+
+generator.save_to_jsonl(Path("generated_data.jsonl"))
+
+asyncio.run(verifier.cleanup())
diff --git a/examples/dataset/generative_dataset.py b/examples/dataset/generative_dataset.py
deleted file mode 100644
index b306f70a2..000000000
--- a/examples/dataset/generative_dataset.py
+++ /dev/null
@@ -1,84 +0,0 @@
-# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
-
-import asyncio
-from pathlib import Path
-from typing import ClassVar
-
-from camel.datasets import FewShotGenerator, StaticDataset
-from camel.logger import get_logger
-from camel.verifiers import PythonVerifier
-
-logger = get_logger(__name__)
-
-
-seed_data = [
- {
- "question": "What is 2 + 2?",
- "rationale": "result = 2 + 2\nprint(result)",
- "final_answer": "4",
- },
- {
- "question": "What is 10 / 2?",
- "rationale": "result = 10 / 2\nprint(result)",
- "final_answer": "5.0",
- },
-]
-
-
-class MockChatAgent:
- def step(self, prompt, response_format):
- """Simulates LLM response with executable Python rationale."""
-
- class MockResponse:
- msgs: ClassVar = [
- type(
- "MockMessage",
- (),
- {
- "parsed": {
- "question": "What is 3 * 3?",
- "rationale": "result = 3 * 3\nprint(result)",
- }
- },
- )
- ]
-
- return MockResponse()
-
-
-async def main():
- seed_dataset = StaticDataset(data=seed_data)
-
- verifier = PythonVerifier(required_packages=["numpy"])
- await verifier.setup()
-
- agent = MockChatAgent()
-
- generator = FewShotGenerator(
- seed_dataset=seed_dataset, verifier=verifier, agent=agent
- )
-
- new_data = await generator.generate_new(n=2)
-
- for dp in new_data:
- print(dp)
-
- generator.save_to_jsonl(Path("generated_data.jsonl"))
-
- await verifier.cleanup()
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/test/datasets/test_base_dataset.py b/test/datasets/test_base_dataset.py
index c84e8adb5..dcce0669b 100644
--- a/test/datasets/test_base_dataset.py
+++ b/test/datasets/test_base_dataset.py
@@ -27,6 +27,7 @@ from camel.datasets import (
FewShotGenerator,
StaticDataset,
)
+from camel.models.stub_model import StubModel
# ruff: noqa: RUF001
@@ -1041,10 +1042,11 @@ async def test_few_shot_generator():
mock_agent.step.return_value = MagicMock(
msgs=[
MagicMock(
- parsed={
- 'question': 'Generated Question',
- 'rationale': 'Generated Rationale',
- }
+ parsed=DataPoint(
+ question='Generated Question',
+ rationale='Generated Rationale',
+ final_answer="final",
+ ),
)
]
)
@@ -1053,9 +1055,11 @@ async def test_few_shot_generator():
dataset = FewShotGenerator(
seed_dataset=mock_static_dataset,
verifier=mock_verifier,
- agent=mock_agent,
+ model=StubModel("Stub"),
)
+ dataset.agent = mock_agent
+
# Test generate_new method
await dataset.generate_new(2)
@@ -1091,13 +1095,15 @@ async def test_generate_new():
]
mock_agent = MagicMock()
+ mock_agent.reset = MagicMock()
mock_agent.step.return_value = MagicMock(
msgs=[
MagicMock(
- parsed={
- 'question': 'Generated Question',
- 'rationale': 'Generated Rationale',
- }
+ parsed=DataPoint(
+ question="Generated Question",
+ rationale="Generated Rationale",
+ final_answer="Generated Answer",
+ )
)
]
)
@@ -1105,10 +1111,11 @@ async def test_generate_new():
MagicMock(
msgs=[
MagicMock(
- parsed={
- "question": "What is 5 + 6?",
- "rationale": "print(5 + 6)",
- }
+ parsed=DataPoint(
+ question="What is 5 + 6?",
+ rationale="print(5 + 6)",
+ final_answer="11",
+ )
)
]
),
@@ -1116,20 +1123,22 @@ async def test_generate_new():
MagicMock(
msgs=[
MagicMock(
- parsed={
- "question": "What is 3 + 5?",
- "rationale": "print(2 + )",
- }
+ parsed=DataPoint(
+ question="What is 3 + 5?",
+ rationale="print(2 + )", # Syntax error
+ final_answer="None", # No valid answer
+ )
)
]
),
MagicMock(
msgs=[
MagicMock(
- parsed={
- "question": "What is 7 + 8?",
- "rationale": "print(7 + 8)",
- }
+ parsed=DataPoint(
+ question="What is 7 + 8?",
+ rationale="print(7 + 8)",
+ final_answer="15",
+ )
)
]
),
@@ -1139,9 +1148,11 @@ async def test_generate_new():
dataset = FewShotGenerator(
seed_dataset=mock_static_dataset,
verifier=mock_verifier,
- agent=mock_agent,
+ model=StubModel("Stub"),
)
+ dataset.agent = mock_agent
+
new_datapoints = await dataset.generate_new(2)
assert (
@@ -1201,15 +1212,17 @@ async def test_generate_new_with_max_retries():
# Set up mock agent with specific output sequence
mock_agent = MagicMock()
+ mock_agent.reset.return_value = None # Ensures it does nothing
mock_agent.step.side_effect = [
# Correct
MagicMock(
msgs=[
MagicMock(
- parsed={
- "question": "What is 3 + 4?",
- "rationale": "print(3 + 4)",
- }
+ parsed=DataPoint(
+ question="What is 3 + 4?",
+ rationale="print(3 + 4)",
+ final_answer="7",
+ )
)
]
),
@@ -1217,10 +1230,11 @@ async def test_generate_new_with_max_retries():
MagicMock(
msgs=[
MagicMock(
- parsed={
- "question": "What is 5 + 6?",
- "rationale": "print(5 + )",
- }
+ parsed=DataPoint(
+ question="What is 5 + 6?",
+ rationale="print(5 + )", # Syntax error
+ final_answer="None", # No valid answer
+ )
)
]
),
@@ -1228,10 +1242,11 @@ async def test_generate_new_with_max_retries():
MagicMock(
msgs=[
MagicMock(
- parsed={
- "question": "What is 7 + 8?",
- "rationale": "print(7 + )",
- }
+ parsed=DataPoint(
+ question="What is 7 + 8?",
+ rationale="print(7 + )", # Syntax error
+ final_answer="None",
+ )
)
]
),
@@ -1239,10 +1254,11 @@ async def test_generate_new_with_max_retries():
MagicMock(
msgs=[
MagicMock(
- parsed={
- "question": "What is 9 + 10?",
- "rationale": "print(9 + )",
- }
+ parsed=DataPoint(
+ question="What is 9 + 10?",
+ rationale="print(9 + )", # Syntax error
+ final_answer="None",
+ )
)
]
),
@@ -1250,21 +1266,24 @@ async def test_generate_new_with_max_retries():
MagicMock(
msgs=[
MagicMock(
- parsed={
- "question": "What is 11 + 12?",
- "rationale": "print(11 + 12)",
- }
+ parsed=DataPoint(
+ question="What is 11 + 12?",
+ rationale="print(11 + 12)",
+ final_answer="23",
+ )
)
]
),
]
+ model = StubModel("OpenAI")
+
dataset = FewShotGenerator(
- seed_dataset=mock_static_dataset,
- verifier=mock_verifier,
- agent=mock_agent,
+ seed_dataset=mock_static_dataset, verifier=mock_verifier, model=model
)
+ dataset.agent = mock_agent
+
# Expect RuntimeError due to insufficient valid
# datapoints within retry limit
with pytest.raises(
@@ -1322,14 +1341,19 @@ async def test_few_shot_generator_save_to_jsonl(tmp_path):
)
]
)
+ mock_agent.reset = MagicMock()
+
+ model = StubModel("OpenAI")
# Create FewShotGenerator with mocks
dataset = FewShotGenerator(
seed_dataset=mock_static_dataset,
verifier=mock_verifier,
- agent=mock_agent,
+ model=model,
)
+ dataset.agent = mock_agent
+
# Mock data
dataset._data = [
DataPoint(