Math via python code with a single agent

The point of this example is to illustrate that for agents that have an AgentExecutor (which most frameworks have apart from Autogen), the approach from MathChat can be done with a single agent, as the second conversation partner there just plays the role of an AgentExecutor.

Let’s install external dependencies for the example.

[ ]:
# install lunary if you need logging
%pip install lunary==1.1.5
[1]:
import os, sys
from pathlib import Path
from dotenv import load_dotenv

WORKING_DIR = Path(os.path.realpath("."))


try:
    from motleycrew import MotleyCrew
except ImportError:
    # if we are running this from source
    motleycrew_location = os.path.realpath( "..")
    sys.path.append(motleycrew_location)

from motleycrew import MotleyCrew
from motleycrew.agents.langchain import ReActToolCallingMotleyAgent
from motleycrew.tools.code import PythonREPLTool
from motleycrew.common import configure_logging
from motleycrew.tasks import SimpleTask

configure_logging(verbose=True)
load_dotenv()
[1]:
True
[2]:
"""Main function of running the example."""

repl_tool = PythonREPLTool()

# Define your agents with roles and goals
solver = ReActToolCallingMotleyAgent(
    prompt_prefix="""You are a high school math teacher with a passion for problem-solving.
To solve a math problem, you first reason about it, step by step, then generate the code to solve it exactly,
using sympy, then use the REPL tool to evaluate that code, and then
use the output to generate a human-readable solution in LaTeX format.
Don't use dashes to indicate bullet points, don't output any backticks, just the LaTeX""",
    verbose=True,
    tools=[repl_tool],
)

problems = [
    "If $725x + 727y = 1500$ and $729x+ 731y = 1508$, "
    "what are the values of $x$, $y$, and $x - y$ ?",
]

# Create tasks for your agents
crew = MotleyCrew()
task = SimpleTask(
    crew=crew,
    name="solve math problem",
    description=f"""Create a nice human-readable solution to the following problem:
    {problems[0]}""",
    additional_params={"expected_output": "human-readable solution in LaTeX format"},
    agent=solver,
)

# Get your crew to work!
crew.run()

display(task.output)
2025-03-29 19:00:38,805 - motleycrew - INFO - No db_path provided, creating temporary directory for database
2025-03-29 19:00:38,806 - motleycrew - INFO - Using Kuzu graph store with path: /var/folders/fv/tyhll76x0fn6l7j_q2nhvyg00000gn/T/tmpysqlaf1v/kuzu_db
2025-03-29 19:00:38,827 - motleycrew - INFO - Node table TaskNode does not exist in the database, creating
2025-03-29 19:00:38,832 - motleycrew - INFO - Property name not present in table for label TaskNode, creating
2025-03-29 19:00:38,833 - motleycrew - INFO - Property done not present in table for label TaskNode, creating
2025-03-29 19:00:38,834 - motleycrew - INFO - Node table SimpleTaskUnit does not exist in the database, creating
2025-03-29 19:00:38,836 - motleycrew - INFO - Property status not present in table for label SimpleTaskUnit, creating
2025-03-29 19:00:38,837 - motleycrew - INFO - Property output not present in table for label SimpleTaskUnit, creating
2025-03-29 19:00:38,837 - motleycrew - INFO - No known Cypher type matching annotation typing.Optional[typing.Any], will use JSON string
2025-03-29 19:00:38,837 - motleycrew - INFO - Property name not present in table for label SimpleTaskUnit, creating
2025-03-29 19:00:38,838 - motleycrew - INFO - Property prompt not present in table for label SimpleTaskUnit, creating
2025-03-29 19:00:38,838 - motleycrew - INFO - Property additional_params not present in table for label SimpleTaskUnit, creating
2025-03-29 19:00:38,838 - motleycrew - INFO - No known Cypher type matching annotation typing.Optional[dict[str, typing.Any]], will use JSON string
2025-03-29 19:00:38,839 - motleycrew - INFO - Relation table SimpleTaskUnit_belongs from SimpleTaskUnit to TaskNode does not exist in the database, creating
2025-03-29 19:00:38,840 - motleycrew - INFO - Inserting new node with label TaskNode: name='solve math problem' done=False
2025-03-29 19:00:38,843 - motleycrew - INFO - Node created OK
2025-03-29 19:00:38,845 - motleycrew - INFO - Relation table task_is_upstream from TaskNode to TaskNode does not exist in the database, creating
2025-03-29 19:00:38,855 - motleycrew - INFO - Available tasks: [SimpleTask(name=solve math problem, done=False)]
2025-03-29 19:00:38,857 - motleycrew - INFO - Processing task: SimpleTask(name=solve math problem, done=False)
2025-03-29 19:00:38,860 - motleycrew - INFO - Got a matching unit for task SimpleTask(name=solve math problem, done=False)
2025-03-29 19:00:38,860 - motleycrew - INFO - Processing unit: TaskUnit(status=pending)
2025-03-29 19:00:38,860 - motleycrew - INFO - Assigned unit TaskUnit(status=pending) to agent ReActToolCallingMotleyAgent(name=None), dispatching
2025-03-29 19:00:38,861 - motleycrew - INFO - Node TaskUnit(status=running) does not exist, creating
2025-03-29 19:00:38,861 - motleycrew - INFO - Inserting new node with label SimpleTaskUnit: TaskUnit(status=running)
2025-03-29 19:00:38,861 - motleycrew - INFO - No known Cypher type matching annotation typing.Optional[typing.Any], will use JSON string
2025-03-29 19:00:38,862 - motleycrew - INFO - No known Cypher type matching annotation typing.Optional[dict[str, typing.Any]], will use JSON string
2025-03-29 19:00:38,863 - motleycrew - INFO - Node created OK
2025-03-29 19:00:38,867 - motleycrew - INFO - Relation from TaskUnit(status=running) to name='solve math problem' done=False does not exist, creating
2025-03-29 19:00:38,918 - motleycrew - INFO - Creating relation SimpleTaskUnit_belongs from SimpleTaskUnit:0 to TaskNode:0
2025-03-29 19:00:38,938 - motleycrew - INFO - Relation created OK
2025-03-29 19:00:38,938 - motleycrew - WARNING - Lunary public key is not set, tracking will be disabled
2025-03-29 19:00:38,941 - motleycrew - INFO - Wrapping agent in RunnableWithMessageHistory


> Entering new AgentExecutor chain...
WARNING:langchain_experimental.utilities.python:Python REPL can execute arbitrary code. Use with caution.

Invoking: `python_repl` with `{'command': "from sympy import symbols, Eq, solve\n\n# Define the variables\nx, y = symbols('x y')\n\n# Define the equations\neq1 = Eq(725*x + 727*y, 1500)\neq2 = Eq(729*x + 731*y, 1508)\n\n# Solve the system of equations\nsolution = solve((eq1, eq2), (x, y))\n\n# Calculate x - y\nx_minus_y = solution[x] - solution[y]\n\nsolution, x_minus_y"}`
responded: Thought: To solve the system of linear equations given by \(725x + 727y = 1500\) and \(729x + 731y = 1508\), we can use the method of elimination or substitution. First, let's solve this system of equations using sympy to find the values of \(x\) and \(y\). Once we have these values, we can easily compute \(x - y\).

Let's proceed by setting up the equations in sympy and solving them.


Invoking: `python_repl` with `{'command': "from sympy import symbols, Eq, solve\n\n# Define the variables\nx, y = symbols('x y')\n\n# Define the equations\neq1 = Eq(725*x + 727*y, 1500)\neq2 = Eq(729*x + 731*y, 1508)\n\n# Solve the system of equations\nsolution = solve((eq1, eq2), (x, y))\n\n# Calculate x - y\nx_minus_y = solution[x] - solution[y]\n\nsolution, x_minus_y"}`
responded: Thought: It seems there was an issue with the previous execution. I will re-run the code to solve the system of equations and calculate \(x - y\).


Invoking: `python_repl` with `{'command': "from sympy import symbols, Eq, solve\n\n# Define the variables\nx, y = symbols('x y')\n\n# Define the equations\neq1 = Eq(725*x + 727*y, 1500)\neq2 = Eq(729*x + 731*y, 1508)\n\n# Solve the system of equations\nsolution = solve((eq1, eq2), (x, y))\n\n# Calculate x - y\nx_minus_y = solution[x] - solution[y]\n\nsolution, x_minus_y"}`
responded: Thought: I will re-run the code to solve the system of equations and calculate \(x - y\) as the previous attempt did not provide the output.


---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
Cell In[2], line 33
     23 task = SimpleTask(
     24     crew=crew,
     25     name="solve math problem",
   (...)
     29     agent=solver,
     30 )
     32 # Get your crew to work!
---> 33 crew.run()
     35 display(task.output)

File ~/motleycrew/motleycrew/crew/crew.py:51, in MotleyCrew.run(self)
     49 """Run the crew."""
     50 if self.async_backend == AsyncBackend.NONE:
---> 51     result = self._run_sync()
     52 elif self.async_backend == AsyncBackend.ASYNCIO:
     53     try:

File ~/motleycrew/motleycrew/crew/crew.py:186, in MotleyCrew._run_sync(self)
    183 logger.info("Available tasks: %s", available_tasks)
    185 for agent, task, unit in self._prepare_next_unit_for_dispatch(set()):
--> 186     result = agent.invoke(unit.as_dict())
    188     self._handle_task_unit_completion(
    189         task=task,
    190         unit=unit,
   (...)
    193         done_units=done_units,
    194     )
    196     did_something = True

File ~/motleycrew/motleycrew/agents/langchain/langchain.py:194, in LangchainMotleyAgent.invoke(self, input, config, **kwargs)
    189 config = self._prepare_config(config)
    190 prompt = self._prepare_for_invocation(
    191     input=input, prompt_as_messages=self.input_as_messages
    192 )
--> 194 output = self.agent.invoke({"input": prompt}, config, **kwargs)
    195 output = output.get("output")
    196 return output

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:5365, in RunnableBindingBase.invoke(self, input, config, **kwargs)
   5359 def invoke(
   5360     self,
   5361     input: Input,
   5362     config: Optional[RunnableConfig] = None,
   5363     **kwargs: Optional[Any],
   5364 ) -> Output:
-> 5365     return self.bound.invoke(
   5366         input,
   5367         self._merge_configs(config),
   5368         **{**self.kwargs, **kwargs},
   5369     )

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:5365, in RunnableBindingBase.invoke(self, input, config, **kwargs)
   5359 def invoke(
   5360     self,
   5361     input: Input,
   5362     config: Optional[RunnableConfig] = None,
   5363     **kwargs: Optional[Any],
   5364 ) -> Output:
-> 5365     return self.bound.invoke(
   5366         input,
   5367         self._merge_configs(config),
   5368         **{**self.kwargs, **kwargs},
   5369     )

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:3029, in RunnableSequence.invoke(self, input, config, **kwargs)
   3027             input = context.run(step.invoke, input, config, **kwargs)
   3028         else:
-> 3029             input = context.run(step.invoke, input, config)
   3030 # finish the root run
   3031 except BaseException as e:

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:5365, in RunnableBindingBase.invoke(self, input, config, **kwargs)
   5359 def invoke(
   5360     self,
   5361     input: Input,
   5362     config: Optional[RunnableConfig] = None,
   5363     **kwargs: Optional[Any],
   5364 ) -> Output:
-> 5365     return self.bound.invoke(
   5366         input,
   5367         self._merge_configs(config),
   5368         **{**self.kwargs, **kwargs},
   5369     )

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:4726, in RunnableLambda.invoke(self, input, config, **kwargs)
   4712 """Invoke this Runnable synchronously.
   4713
   4714 Args:
   (...)
   4723     TypeError: If the Runnable is a coroutine function.
   4724 """
   4725 if hasattr(self, "func"):
-> 4726     return self._call_with_config(
   4727         self._invoke,
   4728         input,
   4729         self._config(config, self.func),
   4730         **kwargs,
   4731     )
   4732 else:
   4733     msg = (
   4734         "Cannot invoke a coroutine function synchronously."
   4735         "Use `ainvoke` instead."
   4736     )

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:1927, in Runnable._call_with_config(self, func, input, config, run_type, serialized, **kwargs)
   1923     context = copy_context()
   1924     context.run(_set_config_context, child_config)
   1925     output = cast(
   1926         Output,
-> 1927         context.run(
   1928             call_func_with_variable_args,  # type: ignore[arg-type]
   1929             func,  # type: ignore[arg-type]
   1930             input,  # type: ignore[arg-type]
   1931             config,
   1932             run_manager,
   1933             **kwargs,
   1934         ),
   1935     )
   1936 except BaseException as e:
   1937     run_manager.on_chain_error(e)

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/config.py:396, in call_func_with_variable_args(func, input, config, run_manager, **kwargs)
    394 if run_manager is not None and accepts_run_manager(func):
    395     kwargs["run_manager"] = run_manager
--> 396 return func(input, **kwargs)

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:4591, in RunnableLambda._invoke(self, input, run_manager, config, **kwargs)
   4587         msg = (
   4588             f"Recursion limit reached when invoking {self} with input {input}."
   4589         )
   4590         raise RecursionError(msg)
-> 4591     output = output.invoke(
   4592         input,
   4593         patch_config(
   4594             config,
   4595             callbacks=run_manager.get_child(),
   4596             recursion_limit=recursion_limit - 1,
   4597         ),
   4598     )
   4599 return cast(Output, output)

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:5365, in RunnableBindingBase.invoke(self, input, config, **kwargs)
   5359 def invoke(
   5360     self,
   5361     input: Input,
   5362     config: Optional[RunnableConfig] = None,
   5363     **kwargs: Optional[Any],
   5364 ) -> Output:
-> 5365     return self.bound.invoke(
   5366         input,
   5367         self._merge_configs(config),
   5368         **{**self.kwargs, **kwargs},
   5369     )

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain/chains/base.py:170, in Chain.invoke(self, input, config, **kwargs)
    168 except BaseException as e:
    169     run_manager.on_chain_error(e)
--> 170     raise e
    171 run_manager.on_chain_end(outputs)
    173 if include_run_info:

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain/chains/base.py:160, in Chain.invoke(self, input, config, **kwargs)
    157 try:
    158     self._validate_inputs(inputs)
    159     outputs = (
--> 160         self._call(inputs, run_manager=run_manager)
    161         if new_arg_supported
    162         else self._call(inputs)
    163     )
    165     final_outputs: Dict[str, Any] = self.prep_outputs(
    166         inputs, outputs, return_only_outputs
    167     )
    168 except BaseException as e:

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain/agents/agent.py:1624, in AgentExecutor._call(self, inputs, run_manager)
   1622 # We now enter the agent loop (until it returns something).
   1623 while self._should_continue(iterations, time_elapsed):
-> 1624     next_step_output = self._take_next_step(
   1625         name_to_tool_map,
   1626         color_mapping,
   1627         inputs,
   1628         intermediate_steps,
   1629         run_manager=run_manager,
   1630     )
   1631     if isinstance(next_step_output, AgentFinish):
   1632         return self._return(
   1633             next_step_output, intermediate_steps, run_manager=run_manager
   1634         )

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain/agents/agent.py:1330, in AgentExecutor._take_next_step(self, name_to_tool_map, color_mapping, inputs, intermediate_steps, run_manager)
   1321 def _take_next_step(
   1322     self,
   1323     name_to_tool_map: Dict[str, BaseTool],
   (...)
   1327     run_manager: Optional[CallbackManagerForChainRun] = None,
   1328 ) -> Union[AgentFinish, List[Tuple[AgentAction, str]]]:
   1329     return self._consume_next_step(
-> 1330         [
   1331             a
   1332             for a in self._iter_next_step(
   1333                 name_to_tool_map,
   1334                 color_mapping,
   1335                 inputs,
   1336                 intermediate_steps,
   1337                 run_manager,
   1338             )
   1339         ]
   1340     )

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain/agents/agent.py:1330, in <listcomp>(.0)
   1321 def _take_next_step(
   1322     self,
   1323     name_to_tool_map: Dict[str, BaseTool],
   (...)
   1327     run_manager: Optional[CallbackManagerForChainRun] = None,
   1328 ) -> Union[AgentFinish, List[Tuple[AgentAction, str]]]:
   1329     return self._consume_next_step(
-> 1330         [
   1331             a
   1332             for a in self._iter_next_step(
   1333                 name_to_tool_map,
   1334                 color_mapping,
   1335                 inputs,
   1336                 intermediate_steps,
   1337                 run_manager,
   1338             )
   1339         ]
   1340     )

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain/agents/agent.py:1358, in AgentExecutor._iter_next_step(self, name_to_tool_map, color_mapping, inputs, intermediate_steps, run_manager)
   1355     intermediate_steps = self._prepare_intermediate_steps(intermediate_steps)
   1357     # Call the LLM to see what to do.
-> 1358     output = self._action_agent.plan(
   1359         intermediate_steps,
   1360         callbacks=run_manager.get_child() if run_manager else None,
   1361         **inputs,
   1362     )
   1363 except OutputParserException as e:
   1364     if isinstance(self.handle_parsing_errors, bool):

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain/agents/agent.py:581, in RunnableMultiActionAgent.plan(self, intermediate_steps, callbacks, **kwargs)
    573 final_output: Any = None
    574 if self.stream_runnable:
    575     # Use streaming to make sure that the underlying LLM is invoked in a
    576     # streaming
   (...)
    579     # Because the response from the plan is not a generator, we need to
    580     # accumulate the output into final output and return that.
--> 581     for chunk in self.runnable.stream(inputs, config={"callbacks": callbacks}):
    582         if final_output is None:
    583             final_output = chunk

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:3414, in RunnableSequence.stream(self, input, config, **kwargs)
   3408 def stream(
   3409     self,
   3410     input: Input,
   3411     config: Optional[RunnableConfig] = None,
   3412     **kwargs: Optional[Any],
   3413 ) -> Iterator[Output]:
-> 3414     yield from self.transform(iter([input]), config, **kwargs)

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:3401, in RunnableSequence.transform(self, input, config, **kwargs)
   3395 def transform(
   3396     self,
   3397     input: Iterator[Input],
   3398     config: Optional[RunnableConfig] = None,
   3399     **kwargs: Optional[Any],
   3400 ) -> Iterator[Output]:
-> 3401     yield from self._transform_stream_with_config(
   3402         input,
   3403         self._transform,
   3404         patch_config(config, run_name=(config or {}).get("run_name") or self.name),
   3405         **kwargs,
   3406     )

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:2201, in Runnable._transform_stream_with_config(self, input, transformer, config, run_type, **kwargs)
   2199 try:
   2200     while True:
-> 2201         chunk: Output = context.run(next, iterator)  # type: ignore
   2202         yield chunk
   2203         if final_output_supported:

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:3364, in RunnableSequence._transform(self, input, run_manager, config, **kwargs)
   3361     else:
   3362         final_pipeline = step.transform(final_pipeline, config)
-> 3364 yield from final_pipeline

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:1414, in Runnable.transform(self, input, config, **kwargs)
   1411 final: Input
   1412 got_first_val = False
-> 1414 for ichunk in input:
   1415     # The default implementation of transform is to buffer input and
   1416     # then call stream.
   1417     # It'll attempt to gather all input into a single chunk using
   1418     # the `+` operator.
   1419     # If the input is not addable, then we'll assume that we can
   1420     # only operate on the last chunk,
   1421     # and we'll iterate until we get to the last chunk.
   1422     if not got_first_val:
   1423         final = ichunk

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:5572, in RunnableBindingBase.transform(self, input, config, **kwargs)
   5566 def transform(
   5567     self,
   5568     input: Iterator[Input],
   5569     config: Optional[RunnableConfig] = None,
   5570     **kwargs: Any,
   5571 ) -> Iterator[Output]:
-> 5572     yield from self.bound.transform(
   5573         input,
   5574         self._merge_configs(config),
   5575         **{**self.kwargs, **kwargs},
   5576     )

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:1432, in Runnable.transform(self, input, config, **kwargs)
   1429             final = ichunk
   1431 if got_first_val:
-> 1432     yield from self.stream(final, config, **kwargs)

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py:428, in BaseChatModel.stream(self, input, config, stop, **kwargs)
    425     self.rate_limiter.acquire(blocking=True)
    427 try:
--> 428     for chunk in self._stream(messages, stop=stop, **kwargs):
    429         if chunk.message.id is None:
    430             chunk.message.id = f"run-{run_manager.run_id}"

File ~/motleycrew/.venv/lib/python3.11/site-packages/langchain_openai/chat_models/base.py:760, in BaseChatOpenAI._stream(self, messages, stop, run_manager, **kwargs)
    758 with context_manager as response:
    759     is_first_chunk = True
--> 760     for chunk in response:
    761         if not isinstance(chunk, dict):
    762             chunk = chunk.model_dump()

File ~/motleycrew/.venv/lib/python3.11/site-packages/openai/_streaming.py:46, in Stream.__iter__(self)
     45 def __iter__(self) -> Iterator[_T]:
---> 46     for item in self._iterator:
     47         yield item

File ~/motleycrew/.venv/lib/python3.11/site-packages/openai/_streaming.py:58, in Stream.__stream__(self)
     55 process_data = self._client._process_response_data
     56 iterator = self._iter_events()
---> 58 for sse in iterator:
     59     if sse.data.startswith("[DONE]"):
     60         break

File ~/motleycrew/.venv/lib/python3.11/site-packages/openai/_streaming.py:50, in Stream._iter_events(self)
     49 def _iter_events(self) -> Iterator[ServerSentEvent]:
---> 50     yield from self._decoder.iter_bytes(self.response.iter_bytes())

File ~/motleycrew/.venv/lib/python3.11/site-packages/openai/_streaming.py:280, in SSEDecoder.iter_bytes(self, iterator)
    278 def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]:
    279     """Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
--> 280     for chunk in self._iter_chunks(iterator):
    281         # Split before decoding so splitlines() only uses \r and \n
    282         for raw_line in chunk.splitlines():
    283             line = raw_line.decode("utf-8")

File ~/motleycrew/.venv/lib/python3.11/site-packages/openai/_streaming.py:291, in SSEDecoder._iter_chunks(self, iterator)
    289 """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks"""
    290 data = b""
--> 291 for chunk in iterator:
    292     for line in chunk.splitlines(keepends=True):
    293         data += line

File ~/motleycrew/.venv/lib/python3.11/site-packages/httpx/_models.py:897, in Response.iter_bytes(self, chunk_size)
    895 chunker = ByteChunker(chunk_size=chunk_size)
    896 with request_context(request=self._request):
--> 897     for raw_bytes in self.iter_raw():
    898         decoded = decoder.decode(raw_bytes)
    899         for chunk in chunker.decode(decoded):

File ~/motleycrew/.venv/lib/python3.11/site-packages/httpx/_models.py:951, in Response.iter_raw(self, chunk_size)
    948 chunker = ByteChunker(chunk_size=chunk_size)
    950 with request_context(request=self._request):
--> 951     for raw_stream_bytes in self.stream:
    952         self._num_bytes_downloaded += len(raw_stream_bytes)
    953         for chunk in chunker.decode(raw_stream_bytes):

File ~/motleycrew/.venv/lib/python3.11/site-packages/httpx/_client.py:153, in BoundSyncStream.__iter__(self)
    152 def __iter__(self) -> typing.Iterator[bytes]:
--> 153     for chunk in self._stream:
    154         yield chunk

File ~/motleycrew/.venv/lib/python3.11/site-packages/httpx/_transports/default.py:127, in ResponseStream.__iter__(self)
    125 def __iter__(self) -> typing.Iterator[bytes]:
    126     with map_httpcore_exceptions():
--> 127         for part in self._httpcore_stream:
    128             yield part

File ~/motleycrew/.venv/lib/python3.11/site-packages/httpcore/_sync/connection_pool.py:407, in PoolByteStream.__iter__(self)
    405 except BaseException as exc:
    406     self.close()
--> 407     raise exc from None

File ~/motleycrew/.venv/lib/python3.11/site-packages/httpcore/_sync/connection_pool.py:403, in PoolByteStream.__iter__(self)
    401 def __iter__(self) -> typing.Iterator[bytes]:
    402     try:
--> 403         for part in self._stream:
    404             yield part
    405     except BaseException as exc:

File ~/motleycrew/.venv/lib/python3.11/site-packages/httpcore/_sync/http11.py:342, in HTTP11ConnectionByteStream.__iter__(self)
    340 with ShieldCancellation():
    341     self.close()
--> 342 raise exc

File ~/motleycrew/.venv/lib/python3.11/site-packages/httpcore/_sync/http11.py:334, in HTTP11ConnectionByteStream.__iter__(self)
    332 try:
    333     with Trace("receive_response_body", logger, self._request, kwargs):
--> 334         for chunk in self._connection._receive_response_body(**kwargs):
    335             yield chunk
    336 except BaseException as exc:
    337     # If we get an exception while streaming the response,
    338     # we want to close the response (and possibly the connection)
    339     # before raising that exception.

File ~/motleycrew/.venv/lib/python3.11/site-packages/httpcore/_sync/http11.py:203, in HTTP11Connection._receive_response_body(self, request)
    200 timeout = timeouts.get("read", None)
    202 while True:
--> 203     event = self._receive_event(timeout=timeout)
    204     if isinstance(event, h11.Data):
    205         yield bytes(event.data)

File ~/motleycrew/.venv/lib/python3.11/site-packages/httpcore/_sync/http11.py:217, in HTTP11Connection._receive_event(self, timeout)
    214     event = self._h11_state.next_event()
    216 if event is h11.NEED_DATA:
--> 217     data = self._network_stream.read(
    218         self.READ_NUM_BYTES, timeout=timeout
    219     )
    221     # If we feed this case through h11 we'll raise an exception like:
    222     #
    223     #     httpcore.RemoteProtocolError: can't handle event type
   (...)
    227     # perspective. Instead we handle this case distinctly and treat
    228     # it as a ConnectError.
    229     if data == b"" and self._h11_state.their_state == h11.SEND_RESPONSE:

File ~/motleycrew/.venv/lib/python3.11/site-packages/httpcore/_backends/sync.py:128, in SyncStream.read(self, max_bytes, timeout)
    126 with map_exceptions(exc_map):
    127     self._sock.settimeout(timeout)
--> 128     return self._sock.recv(max_bytes)

File /opt/homebrew/Cellar/python@3.11/3.11.11/Frameworks/Python.framework/Versions/3.11/lib/python3.11/ssl.py:1295, in SSLSocket.recv(self, buflen, flags)
   1291     if flags != 0:
   1292         raise ValueError(
   1293             "non-zero flags not allowed in calls to recv() on %s" %
   1294             self.__class__)
-> 1295     return self.read(buflen)
   1296 else:
   1297     return super().recv(buflen, flags)

File /opt/homebrew/Cellar/python@3.11/3.11.11/Frameworks/Python.framework/Versions/3.11/lib/python3.11/ssl.py:1168, in SSLSocket.read(self, len, buffer)
   1166         return self._sslobj.read(len, buffer)
   1167     else:
-> 1168         return self._sslobj.read(len)
   1169 except SSLError as x:
   1170     if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:

KeyboardInterrupt:
[3]:
from IPython.display import display, Math, Latex
display(Latex(task.output))
To solve the system of equations given by:
1. \( 725x + 727y = 1500 \)
2. \( 729x + 731y = 1508 \)
We first subtract the first equation from the second to eliminate \( y \), resulting in:
\[ 4x + 4y = 8 \]
which simplifies to:
\[ x + y = 2 \]
Using this in conjunction with the first equation, we substitute \( y = 2 - x \) into \( 725x + 727y = 1500 \) to get:
\[ 725x + 727(2 - x) = 1500 \]
Solving this equation gives \( x = -23 \).
Substituting \( x = -23 \) back into \( x + y = 2 \), we find:
\[ -23 + y = 2 \]
\[ y = 25 \]
Thus, the values are:
\[ x = -23, \quad y = 25, \quad x - y = -23 - 25 = -48 \]
Therefore, \( x = -23 \), \( y = 25 \), and \( x - y = -48 \).
[ ]:
final_result = task.output