AmazonScience/SWE-PolyBench_Verified huggingface dataset:
Repository: microsoft/vscode (TypeScript)
Task: Bug Fix

Issue:
Powerline symbols should not be included in links
When using a powerline prompt:

![image](https://github.com/microsoft/vscode/assets/2193314/9a58da15-8354-4e7e-a74c-9da6633bd85a)

We should not be allowing the powerline symbols to be links (ctrl+hover):

![image](https://github.com/microsoft/vscode/assets/2193314/d8c7bec8-47cd-44ba-b798-968f4be0bd3a)

Running the open detected links command is the clearest way to see this:
 
![image](https://github.com/microsoft/vscode/assets/2193314/e8455eb2-a6d3-406f-9a7f-3b0ffa884865)



Discussion:

Patch:
diff --git a/src/vs/workbench/contrib/terminalContrib/links/browser/terminalWordLinkDetector.ts b/src/vs/workbench/contrib/terminalContrib/links/browser/terminalWordLinkDetector.ts
--- a/src/vs/workbench/contrib/terminalContrib/links/browser/terminalWordLinkDetector.ts
+++ b/src/vs/workbench/contrib/terminalContrib/links/browser/terminalWordLinkDetector.ts
@@ -127,6 +127,10 @@ export class TerminalWordLinkDetector extends Disposable implements ITerminalLin
 
 	private _refreshSeparatorCodes(): void {
 		const separators = this._configurationService.getValue<ITerminalConfiguration>(TERMINAL_CONFIG_SECTION).wordSeparators;
-		this._separatorRegex = new RegExp(`[${escapeRegExpCharacters(separators)}]`, 'g');
+		let powerlineSymbols = '';
+		for (let i = 0xe0b0; i <= 0xe0bf; i++) {
+			powerlineSymbols += String.fromCharCode(i);
+		}
+		this._separatorRegex = new RegExp(`[${escapeRegExpCharacters(separators)}${powerlineSymbols}]`, 'g');
 	}
 }


Test patch:
diff --git a/src/vs/workbench/contrib/terminalContrib/links/test/browser/terminalWordLinkDetector.test.ts b/src/vs/workbench/contrib/terminalContrib/links/test/browser/terminalWordLinkDetector.test.ts
--- a/src/vs/workbench/contrib/terminalContrib/links/test/browser/terminalWordLinkDetector.test.ts
+++ b/src/vs/workbench/contrib/terminalContrib/links/test/browser/terminalWordLinkDetector.test.ts
@@ -72,6 +72,14 @@ suite('Workbench - TerminalWordLinkDetector', () => {
 		});
 	});
 
+	suite('should ignore powerline symbols', () => {
+		for (let i = 0xe0b0; i <= 0xe0bf; i++) {
+			test(`\\u${i.toString(16)}`, async () => {
+				await assertLink(`${String.fromCharCode(i)}foo${String.fromCharCode(i)}`, [{ range: [[2, 1], [4, 1]], text: 'foo' }]);
+			});
+		}
+	});
+
 	// These are failing - the link's start x is 1 px too far to the right bc it starts
 	// with a wide character, which the terminalLinkHelper currently doesn't account for
 	test.skip('should support wide characters', async () => {
Repository: mui/material-ui (TypeScript)
Task: Bug Fix

Issue:
MenuItem doesn't respect focusVisibleClassName
Related to #10976. 

The changes in #10976 work awesome for the `Switch`, however it looks like the `MenuItem`'s `focusVisibleClassName` prop doesn't work as expected. Passing a `focusVisibleClassName` to the item works great from a typing perspective, but they don't seem to be applied to the `ListItem` correctly.

Example: https://codesandbox.io/s/5638ox58n 


Discussion:
@ianschmitz Correct, we need to merge the classnames in
https://github.com/mui-org/material-ui/blob/e99f23e85f9f0241a08165b435cd4d51f696ac12/packages/material-ui/src/ListItem/ListItem.js#L108

Patch:
diff --git a/packages/material-ui/src/ListItem/ListItem.js b/packages/material-ui/src/ListItem/ListItem.js
--- a/packages/material-ui/src/ListItem/ListItem.js
+++ b/packages/material-ui/src/ListItem/ListItem.js
@@ -78,6 +78,7 @@ class ListItem extends React.Component {
       disabled,
       disableGutters,
       divider,
+      focusVisibleClassName,
       ...other
     } = this.props;
 
@@ -105,7 +106,10 @@ class ListItem extends React.Component {
 
     if (button) {
       componentProps.component = componentProp || 'div';
-      componentProps.focusVisibleClassName = classes.focusVisible;
+      componentProps.focusVisibleClassName = classNames(
+        classes.focusVisible,
+        focusVisibleClassName,
+      );
       Component = ButtonBase;
     }
 
@@ -186,6 +190,10 @@ ListItem.propTypes = {
    * If `true`, a 1px light border is added to the bottom of the list item.
    */
   divider: PropTypes.bool,
+  /**
+   * @ignore
+   */
+  focusVisibleClassName: PropTypes.string,
 };
 
 ListItem.defaultProps = {


Test patch:
diff --git a/packages/material-ui/src/ListItem/ListItem.test.js b/packages/material-ui/src/ListItem/ListItem.test.js
--- a/packages/material-ui/src/ListItem/ListItem.test.js
+++ b/packages/material-ui/src/ListItem/ListItem.test.js
@@ -158,4 +158,15 @@ describe('<ListItem />', () => {
       assert.strictEqual(wrapper.hasClass('bubu'), true);
     });
   });
+
+  describe('prop: focusVisibleClassName', () => {
+    it('should merge the class names', () => {
+      const wrapper = shallow(<ListItem button focusVisibleClassName="focusVisibleClassName" />);
+      assert.strictEqual(wrapper.props().component, 'div');
+      assert.strictEqual(
+        wrapper.props().focusVisibleClassName,
+        `${classes.focusVisible} focusVisibleClassName`,
+      );
+    });
+  });
 });
Repository: mui/material-ui (TypeScript)
Task: Bug Fix

Issue:
Cannot convert undefined or null to object
After a migration to the 3.6.1 version and when I open a Modal. I have the following error:

![errorlog](https://user-images.githubusercontent.com/9904165/49368135-411eff80-f6ee-11e8-9d46-c547c0872e1a.png)

`data.style is undefined`

![error](https://user-images.githubusercontent.com/9904165/49368051-1765d880-f6ee-11e8-8e1d-3c60d5674208.png)

I think wee need to check if `data.style` exists or not (?)
 
- [x] This is not a v0.x issue. <!-- (v0.x is no longer maintained) -->
- [x] I have searched the [issues](https://github.com/mui-org/material-ui/issues) of this repository and believe that this is not a duplicate.

## Your Environment 🌎

| Tech         | Version |
|--------------|---------|
| Material-UI  | v3.6.1  |
| React        |    16.6.3     |
| Browser      |         |
| TypeScript   |         |
| etc.         |         |



Discussion:

Patch:
diff --git a/packages/material-ui/src/Modal/ModalManager.js b/packages/material-ui/src/Modal/ModalManager.js
--- a/packages/material-ui/src/Modal/ModalManager.js
+++ b/packages/material-ui/src/Modal/ModalManager.js
@@ -50,9 +50,12 @@ function setContainerStyle(data) {
 }
 
 function removeContainerStyle(data) {
-  Object.keys(data.style).forEach(key => {
-    data.container.style[key] = data.style[key];
-  });
+  // The modal might be closed before it had the chance to be mounted in the DOM.
+  if (data.style) {
+    Object.keys(data.style).forEach(key => {
+      data.container.style[key] = data.style[key];
+    });
+  }
 
   const fixedNodes = ownerDocument(data.container).querySelectorAll('.mui-fixed');
   for (let i = 0; i < fixedNodes.length; i += 1) {


Test patch:
diff --git a/packages/material-ui/src/Modal/Modal.test.js b/packages/material-ui/src/Modal/Modal.test.js
--- a/packages/material-ui/src/Modal/Modal.test.js
+++ b/packages/material-ui/src/Modal/Modal.test.js
@@ -541,4 +541,27 @@ describe('<Modal />', () => {
       assert.strictEqual(document.body.style.overflow, '');
     });
   });
+
+  it('should support open abort', () => {
+    class TestCase extends React.Component {
+      state = {
+        open: true,
+      };
+
+      componentDidMount() {
+        this.setState({
+          open: false,
+        });
+      }
+
+      render() {
+        return (
+          <Modal open={this.state.open}>
+            <div>Hello</div>
+          </Modal>
+        );
+      }
+    }
+    mount(<TestCase />);
+  });
 });
Repository: mui/material-ui (TypeScript)
Task: Bug Fix

Issue:
Regression: <Select native id="my-id"> No Longer Has an Id
The "id" prop is ignored for \<Select\>'s that have the "native" prop set.

At some point in the past (maybe a few versions ago) this use to work.

- [x] The issue is present in the latest release.
- [x] I have searched the [issues](https://github.com/mui-org/material-ui/issues) of this repository and believe that this is not a duplicate.

## Steps to Reproduce 🕹

1. Go to: https://codesandbox.io/s/create-react-app-u2uwe
2. In the console run `document.getElementById('select-id')`. Nothing will match showing the id isn't set.



Discussion:

Patch:
diff --git a/packages/material-ui/src/Select/Select.js b/packages/material-ui/src/Select/Select.js
--- a/packages/material-ui/src/Select/Select.js
+++ b/packages/material-ui/src/Select/Select.js
@@ -69,7 +69,7 @@ const Select = React.forwardRef(function Select(props, ref) {
       type: undefined, // We render a select. We can ignore the type provided by the `Input`.
       multiple,
       ...(native
-        ? {}
+        ? { id }
         : {
             autoWidth,
             displayEmpty,


Test patch:
diff --git a/packages/material-ui/src/Select/Select.test.js b/packages/material-ui/src/Select/Select.test.js
--- a/packages/material-ui/src/Select/Select.test.js
+++ b/packages/material-ui/src/Select/Select.test.js
@@ -867,4 +867,23 @@ describe('<Select />', () => {
       expect(getByRole('button')).to.have.attribute('id', 'mui-component-select-foo');
     });
   });
+
+  describe('prop: native', () => {
+    it('renders a <select />', () => {
+      const { container } = render(<Select native />);
+
+      expect(container.querySelector('select')).not.to.be.null;
+    });
+
+    it('can be labelled with a <label />', () => {
+      const { getByLabelText } = render(
+        <React.Fragment>
+          <label htmlFor="select">A select</label>
+          <Select id="select" native />
+        </React.Fragment>,
+      );
+
+      expect(getByLabelText('A select')).to.have.property('tagName', 'SELECT');
+    });
+  });
 });
Repository: mui/material-ui (TypeScript)
Task: Feature

Issue:
[Autocomplete] Don't close the popup when Ctrl/Shift clicks
In an Autocomplete component that contains the `multiple` prop, it would be a great feature to have a ctrl click functionality. E.g. simply clicking with the mouse should select a single item. Only when ctrl+click is used the popup shouldn't close, allowing to select more options.


Discussion:

Patch:
diff --git a/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js b/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js
--- a/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js
+++ b/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js
@@ -563,7 +563,7 @@ export default function useAutocomplete(props) {
     resetInputValue(event, newValue);
 
     handleValue(event, newValue, reason, { option });
-    if (!disableCloseOnSelect) {
+    if (!disableCloseOnSelect && !event.ctrlKey && !event.metaKey) {
       handleClose(event, reason);
     }
 


Test patch:
diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js
--- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js
+++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js
@@ -834,6 +834,40 @@ describe('<Autocomplete />', () => {
       expect(handleClose.callCount).to.equal(1);
     });
 
+    it('does not close the popup when option selected if Control is pressed', () => {
+      const handleClose = spy();
+      const { getAllByRole } = render(
+        <Autocomplete
+          {...defaultProps}
+          onClose={handleClose}
+          open
+          options={['one', 'two']}
+          renderInput={(params) => <TextField {...params} autoFocus />}
+        />,
+      );
+
+      const options = getAllByRole('option');
+      fireEvent.click(options[0], { ctrlKey: true });
+      expect(handleClose.callCount).to.equal(0);
+    });
+
+    it('does not close the popup when option selected if Meta is pressed', () => {
+      const handleClose = spy();
+      const { getAllByRole } = render(
+        <Autocomplete
+          {...defaultProps}
+          onClose={handleClose}
+          open
+          options={['one', 'two']}
+          renderInput={(params) => <TextField {...params} autoFocus />}
+        />,
+      );
+
+      const options = getAllByRole('option');
+      fireEvent.click(options[0], { metaKey: true });
+      expect(handleClose.callCount).to.equal(0);
+    });
+
     it('moves focus to the first option on ArrowDown', () => {
       const { getAllByRole, getByRole } = render(
         <Autocomplete
Repository: mui/material-ui (TypeScript)
Task: Bug Fix

Issue:
[TreeView] Scroll jump bug
When Tree View has a larger height than the window height, clicking Tree Items first jumps the position of the item to the top and then on the second click toggles. See the video, please. 

A similar thing happens in the last items too - it just positions the element to the bottom and it is really hard to click it then.

Items in the middle seem fine. 

Official doc examples have the same problem.

https://user-images.githubusercontent.com/7082560/102820418-84cc2b00-43d5-11eb-94fb-f7019d355366.mov

### Versions

v5.0.0-alpha.20


Discussion:

Patch:
diff --git a/packages/material-ui-lab/src/TreeItem/TreeItem.js b/packages/material-ui-lab/src/TreeItem/TreeItem.js
--- a/packages/material-ui-lab/src/TreeItem/TreeItem.js
+++ b/packages/material-ui-lab/src/TreeItem/TreeItem.js
@@ -223,7 +223,7 @@ const TreeItem = React.forwardRef(function TreeItem(props, ref) {
   function handleFocus(event) {
     // DOM focus stays on the tree which manages focus with aria-activedescendant
     if (event.target === event.currentTarget) {
-      ownerDocument(event.target).getElementById(treeId).focus();
+      ownerDocument(event.target).getElementById(treeId).focus({ preventScroll: true });
     }
 
     const unfocusable = !disabledItemsFocusable && disabled;


Test patch:
diff --git a/packages/material-ui-lab/src/TreeItem/TreeItem.test.js b/packages/material-ui-lab/src/TreeItem/TreeItem.test.js
--- a/packages/material-ui-lab/src/TreeItem/TreeItem.test.js
+++ b/packages/material-ui-lab/src/TreeItem/TreeItem.test.js
@@ -414,6 +414,22 @@ describe('<TreeItem />', () => {
 
         expect(getByTestId('parent')).toHaveVirtualFocus();
       });
+
+      it('should focus on tree with scroll prevented', () => {
+        const { getByRole, getByTestId } = render(
+          <TreeView>
+            <TreeItem nodeId="1" label="one" data-testid="one" />
+            <TreeItem nodeId="2" label="two" data-testid="two" />
+          </TreeView>,
+        );
+        const focus = spy(getByRole('tree'), 'focus');
+
+        act(() => {
+          getByTestId('one').focus();
+        });
+
+        expect(focus.calledOnceWithExactly({ preventScroll: true })).to.equals(true);
+      });
     });
 
     describe('Navigation', () => {
Repository: huggingface/transformers (Python)
Task: Bug Fix

Issue:
`Trainer.train(resume_from_checkpoint=False)` is causing an exception
Since `resume_from_checkpoint` can be `str` and `bool` it should be possible to pass `False` to it.
But when `resume_from_checkpoint` is `False` it causes an exception here:

https://github.com/huggingface/transformers/blob/3d4b3bc3fd77e0e48e2364464ea90379f13bcf37/src/transformers/trainer.py#L1049-L1050

```text
E       TypeError: expected str, bytes or os.PathLike object, not bool
```

The most simple solution would be to do this at the beginning of the `train` function:

```python
resume_from_checkpoint = None if not resume_from_checkpoint else resume_from_checkpoint
```

If wanted I can provide a PR.


Discussion:
That seems like the right fix indeed. Please go ahead with a PR, thanks! :-)

Patch:
diff --git a/src/transformers/trainer.py b/src/transformers/trainer.py
--- a/src/transformers/trainer.py
+++ b/src/transformers/trainer.py
@@ -1005,6 +1005,7 @@ def train(
             kwargs:
                 Additional keyword arguments used to hide deprecated arguments
         """
+        resume_from_checkpoint = None if not resume_from_checkpoint else resume_from_checkpoint
 
         # memory metrics - must set up as early as possible
         self._memory_tracker.start()


Test patch:
diff --git a/tests/test_trainer.py b/tests/test_trainer.py
--- a/tests/test_trainer.py
+++ b/tests/test_trainer.py
@@ -827,6 +827,20 @@ def test_resume_training_with_randomness(self):
         self.assertAlmostEqual(a, a1, delta=1e-8)
         self.assertAlmostEqual(b, b1, delta=1e-8)
 
+    # regression for this issue: https://github.com/huggingface/transformers/issues/12970
+    def test_training_with_resume_from_checkpoint_flase(self):
+        train_dataset = RegressionDataset(length=128)
+        eval_dataset = RegressionDataset()
+
+        config = RegressionModelConfig(a=0, b=2)
+        model = RegressionRandomPreTrainedModel(config)
+
+        tmp_dir = self.get_auto_remove_tmp_dir()
+        args = RegressionTrainingArguments(tmp_dir, save_steps=5, learning_rate=0.1)
+        trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset)
+
+        trainer.train(resume_from_checkpoint=False)
+
     @require_torch_up_to_2_gpus
     def test_resume_training_with_gradient_accumulation(self):
         # This test will fail for more than 2 GPUs since the batch size will get bigger and with the number of
Repository: huggingface/transformers (Python)
Task: Bug Fix

Issue:
OSError: /home/datascience/huggingface does not appear to have a file named preprocessor_config.json. Checkout 'https://huggingface.co//home/datascience/huggingface/None' for available files.
### System Info

import transformers
transformers.__version__

'4.31.0'

### Who can help?

_No response_

### Information

- [ ] The official example scripts
- [ ] My own modified scripts

### Tasks

- [ ] An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)
- [ ] My own task or dataset (give details below)

### Reproduction
![image](https://github.com/huggingface/transformers/assets/25996703/6e26deb4-237b-473a-8874-164a4d134ea8)

```python
segmenter = pipeline(task="image-segmentation", model="facebook/detr-resnet-50-panoptic", revision="fc15262")
segmenter.save_pretrained("./huggingface")


from transformers import pipeline
task = 'image-segmentation'
model_dir="./huggingface"
model = pipeline(task, model = model_dir)

OSError: /home/datascience/huggingface does not appear to have a file named preprocessor_config.json. Checkout 'https://huggingface.co//home/datascience/huggingface/None' for available files.
```

### Expected behavior

no bug


Discussion:
Hey! Thanks for reporting! Yep I thing we should make sure the `image_processor`is also saved! Would you like to open a PR? 🤗 

Patch:
diff --git a/src/transformers/pipelines/base.py b/src/transformers/pipelines/base.py
--- a/src/transformers/pipelines/base.py
+++ b/src/transformers/pipelines/base.py
@@ -872,6 +872,9 @@ def save_pretrained(self, save_directory: str, safe_serialization: bool = False)
         if self.feature_extractor is not None:
             self.feature_extractor.save_pretrained(save_directory)
 
+        if self.image_processor is not None:
+            self.image_processor.save_pretrained(save_directory)
+
         if self.modelcard is not None:
             self.modelcard.save_pretrained(save_directory)
 


Test patch:
diff --git a/tests/pipelines/test_pipelines_image_segmentation.py b/tests/pipelines/test_pipelines_image_segmentation.py
--- a/tests/pipelines/test_pipelines_image_segmentation.py
+++ b/tests/pipelines/test_pipelines_image_segmentation.py
@@ -13,6 +13,7 @@
 # limitations under the License.
 
 import hashlib
+import tempfile
 import unittest
 from typing import Dict
 
@@ -714,3 +715,17 @@ def test_oneformer(self):
                 },
             ],
         )
+
+    def test_save_load(self):
+        model_id = "hf-internal-testing/tiny-detr-mobilenetsv3-panoptic"
+
+        model = AutoModelForImageSegmentation.from_pretrained(model_id)
+        image_processor = AutoImageProcessor.from_pretrained(model_id)
+        image_segmenter = pipeline(
+            task="image-segmentation",
+            model=model,
+            image_processor=image_processor,
+        )
+        with tempfile.TemporaryDirectory() as tmpdirname:
+            image_segmenter.save_pretrained(tmpdirname)
+            pipeline(task="image-segmentation", model=tmpdirname)
Repository: huggingface/transformers (Python)
Task: Bug Fix

Issue:
`center_crop` outputs wrong sized array if provided with odd-numbered dimensions smaller than requested crop size
### System Info

transformers 4.40.1, python 3.12

### Who can help?

@amyeroberts 

### Information

- [ ] The official example scripts
- [X] My own modified scripts

### Tasks

- [ ] An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)
- [X] My own task or dataset (give details below)

### Reproduction

```
from transformers.image_transforms import center_crop
import numpy as np
small_even = np.ones((3,4,4))
small_odd = np.ones((3,3,3))
big_even = np.ones((3,10,10))
big_odd = np.ones((3,11,11))
print([center_crop(x, (8,8)).shape for x in [small_even, big_even, big_odd, small_odd]])
```

Result:
```
[(3, 8, 8), (3, 8, 8), (3, 8, 8), (3, 7, 7)]
```

### Expected behavior

All arrays should be cropped to the requested size of (8,8). However, odd-numbered dimensions that are smaller than the crop size and require padding result in an unexpected off-by-one output size.


Discussion:
I believe the issue is more accurately caused by odd-numbered difference between original size and new size. Rounding up rather than down when calculating the padding fixes the above test cases.

Patch:
diff --git a/src/transformers/image_transforms.py b/src/transformers/image_transforms.py
--- a/src/transformers/image_transforms.py
+++ b/src/transformers/image_transforms.py
@@ -14,6 +14,7 @@
 # limitations under the License.
 
 import warnings
+from math import ceil
 from typing import Iterable, List, Optional, Tuple, Union
 
 import numpy as np
@@ -483,9 +484,9 @@ def center_crop(
     new_image = np.zeros_like(image, shape=new_shape)
 
     # If the image is too small, pad it with zeros
-    top_pad = (new_height - orig_height) // 2
+    top_pad = ceil((new_height - orig_height) / 2)
     bottom_pad = top_pad + orig_height
-    left_pad = (new_width - orig_width) // 2
+    left_pad = ceil((new_width - orig_width) / 2)
     right_pad = left_pad + orig_width
     new_image[..., top_pad:bottom_pad, left_pad:right_pad] = image
 


Test patch:
diff --git a/tests/test_image_transforms.py b/tests/test_image_transforms.py
--- a/tests/test_image_transforms.py
+++ b/tests/test_image_transforms.py
@@ -369,6 +369,10 @@ def test_center_crop(self):
         self.assertEqual(cropped_image.shape, (300, 260, 3))
         self.assertTrue(np.allclose(cropped_image, expected_image))
 
+        # Test that odd numbered padding requirement still leads to correct output dimensions
+        cropped_image = center_crop(image, (300, 259), data_format="channels_last")
+        self.assertEqual(cropped_image.shape, (300, 259, 3))
+
         # Test image with 4 channels is cropped correctly
         image = np.random.randint(0, 256, (224, 224, 4))
         expected_image = image[52:172, 82:142, :]
Repository: langchain-ai/langchain (Python)
Task: Bug Fix

Issue:
Terminal tool gives `ValueError: Could not parse LLM output:` when there is a new libe before action string.
While playing with the LLaMA models I noticed what parse exception was thrown even output looked good.

### Screenshot
![Screenshot_20230422_220902](https://user-images.githubusercontent.com/10456471/233808267-0f6f872a-f7b4-4154-b38c-ad2dcade7820.png)

For curious one the prompt I used was:
```python
agent({"input":"""
There is a file in `~/.bashrc.d/` directory containing openai api key.
Can you find that key?
"""})
```



Discussion:
I have a fix. Will create PR shortly.

Patch:
diff --git a/langchain/agents/mrkl/output_parser.py b/langchain/agents/mrkl/output_parser.py
--- a/langchain/agents/mrkl/output_parser.py
+++ b/langchain/agents/mrkl/output_parser.py
@@ -18,7 +18,9 @@ def parse(self, text: str) -> Union[AgentAction, AgentFinish]:
                 {"output": text.split(FINAL_ANSWER_ACTION)[-1].strip()}, text
             )
         # \s matches against tab/newline/whitespace
-        regex = r"Action\s*\d*\s*:(.*?)\nAction\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)"
+        regex = (
+            r"Action\s*\d*\s*:[\s]*(.*?)[\s]*Action\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)"
+        )
         match = re.search(regex, text, re.DOTALL)
         if not match:
             raise OutputParserException(f"Could not parse LLM output: `{text}`")


Test patch:
diff --git a/tests/unit_tests/agents/test_mrkl.py b/tests/unit_tests/agents/test_mrkl.py
--- a/tests/unit_tests/agents/test_mrkl.py
+++ b/tests/unit_tests/agents/test_mrkl.py
@@ -50,6 +50,27 @@ def test_get_action_and_input_newline() -> None:
     assert action_input == "```\nimport unittest\n\nunittest.main()\n```"
 
 
+def test_get_action_and_input_newline_after_keyword() -> None:
+    """Test getting an action and action input from the text
+    when there is a new line before the action
+    (after the keywords "Action:" and "Action Input:")
+    """
+    llm_output = """
+    I can use the `ls` command to list the contents of the directory \
+    and `grep` to search for the specific file.
+
+    Action:
+    Terminal
+
+    Action Input:
+    ls -l ~/.bashrc.d/
+    """
+
+    action, action_input = get_action_and_input(llm_output)
+    assert action == "Terminal"
+    assert action_input == "ls -l ~/.bashrc.d/\n"
+
+
 def test_get_final_answer() -> None:
     """Test getting final answer."""
     llm_output = (
Repository: keras-team/keras (Python)
Task: Bug Fix

Issue:
Numpy Ops function nonzero(x) appers to be missing check for symbolic tensors
In updating  code from Keras 2 to 3, we noticed that nonzero function continues to throw errors for use of KerasTensor in TF functions, even when run though tf.keras.ops

Digging into the source, it appears that this function does not receive the check for any_symbolic_tensors(), and thus no instantiation of the NonZero() class. In turn failing when used with a KerasTensor

https://github.com/keras-team/keras/blob/42a1535ed7d3d75711a11d295f58a2dc9a59fdae/keras/ops/numpy.py#L3976


Discussion:

Patch:
diff --git a/keras/ops/numpy.py b/keras/ops/numpy.py
--- a/keras/ops/numpy.py
+++ b/keras/ops/numpy.py
@@ -3992,6 +3992,9 @@ class Nonzero(Operation):
     def call(self, x):
         return backend.numpy.nonzero(x)
 
+    def compute_output_spec(self, x):
+        return KerasTensor([None] * len(x.shape))
+
 
 @keras_export(["keras.ops.nonzero", "keras.ops.numpy.nonzero"])
 def nonzero(x):
@@ -4003,6 +4006,8 @@ def nonzero(x):
     Returns:
         Indices of elements that are non-zero.
     """
+    if any_symbolic_tensors((x,)):
+        return Nonzero().symbolic_call(x)
     return backend.numpy.nonzero(x)
 
 


Test patch:
diff --git a/keras/ops/numpy_test.py b/keras/ops/numpy_test.py
--- a/keras/ops/numpy_test.py
+++ b/keras/ops/numpy_test.py
@@ -1311,6 +1311,10 @@ def test_ndim(self):
         x = KerasTensor((None, 3))
         self.assertEqual(knp.ndim(x).shape, (2,))
 
+    def test_nonzero(self):
+        x = KerasTensor((None, 5, 6))
+        self.assertEqual(knp.nonzero(x).shape, (None, None, None))
+
     def test_ones_like(self):
         x = KerasTensor((None, 3))
         self.assertEqual(knp.ones_like(x).shape, (None, 3))
Repository: keras-team/keras (Python)
Task: Bug Fix

Issue:
Unable to export reloaded model
Saving and reloading model makes it impossible to export it as a SavedModel artifact. 
Reloaded model has shapes defined as lists while export function expect tuples. 
Casting the shape to tuple in this particular place resolves the issue, but there may be other errors related to this in other places, though.

Steps to reproduce:

1) Make a subclassed model (maybe reproducible with Functional too?)
2) Save the model as `.keras`
3) Reload `.keras`
4) Try to `model.export()` on your reloaded model

Here's the notebook with the same steps for your convenience:
https://colab.research.google.com/drive/1oO4JxoYK4I4UO0VdyYPAlCQY9fT1pYlw


Discussion:

Patch:
diff --git a/keras/src/export/export_lib.py b/keras/src/export/export_lib.py
--- a/keras/src/export/export_lib.py
+++ b/keras/src/export/export_lib.py
@@ -654,13 +654,18 @@ def make_tensor_spec(structure):
         # into plain Python structures because they don't work with jax2tf/JAX.
         if isinstance(structure, dict):
             return {k: make_tensor_spec(v) for k, v in structure.items()}
-        if isinstance(structure, (list, tuple)):
+        elif isinstance(structure, tuple):
             if all(isinstance(d, (int, type(None))) for d in structure):
                 return tf.TensorSpec(
                     shape=(None,) + structure[1:], dtype=model.input_dtype
                 )
-            result = [make_tensor_spec(v) for v in structure]
-            return tuple(result) if isinstance(structure, tuple) else result
+            return tuple(make_tensor_spec(v) for v in structure)
+        elif isinstance(structure, list):
+            if all(isinstance(d, (int, type(None))) for d in structure):
+                return tf.TensorSpec(
+                    shape=[None] + structure[1:], dtype=model.input_dtype
+                )
+            return [make_tensor_spec(v) for v in structure]
         else:
             raise ValueError(
                 f"Unsupported type {type(structure)} for {structure}"


Test patch:
diff --git a/keras/src/export/export_lib_test.py b/keras/src/export/export_lib_test.py
--- a/keras/src/export/export_lib_test.py
+++ b/keras/src/export/export_lib_test.py
@@ -196,6 +196,22 @@ def call(self, inputs):
         )
         revived_model.serve(bigger_input)
 
+        # Test with keras.saving_lib
+        temp_filepath = os.path.join(
+            self.get_temp_dir(), "exported_model.keras"
+        )
+        saving_lib.save_model(model, temp_filepath)
+        revived_model = saving_lib.load_model(
+            temp_filepath,
+            {
+                "TupleModel": TupleModel,
+                "ArrayModel": ArrayModel,
+                "DictModel": DictModel,
+            },
+        )
+        self.assertAllClose(ref_output, revived_model(ref_input))
+        export_lib.export_model(revived_model, self.get_temp_dir())
+
     def test_model_with_multiple_inputs(self):
 
         class TwoInputsModel(models.Model):