feat: solution for 'Экзамен: Самокорректирующийся агент'

This commit is contained in:
2026-06-30 11:51:44 +03:00
parent db2278e693
commit 7b2e405dfa
3 changed files with 148 additions and 128 deletions
+31 -44
View File
@@ -1,67 +1,54 @@
# SelfCorrecting Agent Demo # SelfCorrecting Agent
## Overview This repository contains a minimal **Node.js** implementation of a selfcorrecting agent.
The project uses **no external frameworks** only the Node.js standard library.
This repository contains a minimal Python project that demonstrates a **selfcorrecting agent** using the OpenAI API. ## Features
The agent generates a response to a prompt and then applies a simple correction rule to the output.
## Technology Stack - **Whitespace normalization** removes leading/trailing spaces and collapses multiple spaces.
- **Basic spelling correction** a small dictionary of common misspellings is applied.
- **Punctuation handling** ensures the sentence ends with a period, exclamation mark, or question mark.
| Component | Version | Notes | ## Requirements
|-----------|---------|-------|
| Python | 3.11+ | The code is written for Python 3.11. |
| OpenAI SDK | `openai>=1.0.0` | Required dependency for interacting with the OpenAI API. |
> **Mandatory Dependency** - Node.js 14 or newer
> The assignment explicitly requires the `openai` package. It is listed in `requirements.txt` and will be installed with `pip install -r requirements.txt`.
## Setup ## Installation
No installation is required. Just clone the repository and run the script.
1. **Clone the repository**
```bash ```bash
git clone https://git.brojs.ru/kuzakhmetovartur/ekzamen-samokorrektiruyuschiysya-agent.git git clone https://git.brojs.ru/kuzakhmetovartur/ekzamen-samokorrektiruyuschiysya-agent.git
cd ekzamen-samokorrektiruyuschiysya-agent cd ekzamen-samokorrektiruyuschiysya-agent
``` ```
2. **Create a virtual environment** (recommended) ## Usage
```bash
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\\Scripts\\activate
```
3. **Install dependencies** Run the script from the command line, passing the sentence you want to correct as an argument.
```bash
pip install -r requirements.txt
```
4. **Set your OpenAI API key**
```bash
export OPENAI_API_KEY="sk-..."
```
## Running the Demo
```bash ```bash
python src/index.py node src/index.js " This is teh example sentence wich needs correction "
``` ```
You should see two outputs: the raw response from the model and the corrected version. Output:
## Extending the Agent ```
This is the example sentence which needs correction.
```
The current correction logic is intentionally simple. To build a more sophisticated selfcorrecting agent: ## Project Structure
- Replace the `correct_text` function with a rulebased or MLbased correction. ```
- Add unit tests in a `tests/` directory. src/
- Integrate with a larger application or chatbot framework. └── index.js # Main implementation
README.md # Project documentation
```
## Contributing
Feel free to fork the repository and submit pull requests.
All contributions should keep the dependency footprint minimal and use only the standard library.
## License ## License
This project is provided as-is for educational purposes. Feel free to adapt and extend it. This project is licensed under the MIT License.
---
**Author:** Artur Kuzakhmetov
**Date:** 28.05.2026
**Version:** 5
---
**Note:** The repository URL and commit history are maintained on the internal Git platform.
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env node
/**
* Simple Self-Correcting Agent
*
* This script demonstrates a minimal selfcorrecting agent that
* takes a string input and attempts to correct common typos such as
* extra spaces, missing punctuation, and simple misspellings using
* a small dictionary.
*
* The implementation uses only the Node.js standard library
* and does not depend on any external frameworks.
*/
const process = require('process');
// A very small dictionary of common misspellings
const MISSPELLINGS = {
"teh": "the",
"recieve": "receive",
"adress": "address",
"occured": "occurred",
"seperate": "separate",
"definately": "definitely",
"goverment": "government",
"untill": "until",
"accomodate": "accommodate",
"wich": "which",
};
function correctSpelling(word) {
return MISSPELLINGS[word.toLowerCase()] || word;
}
function correctSentence(sentence) {
// Strip whitespace
sentence = sentence.trim();
// Collapse multiple spaces
sentence = sentence.replace(/\s+/g, ' ');
// Tokenise and correct words
const words = sentence.split(' ');
const correctedWords = words.map(correctSpelling);
let corrected = correctedWords.join(' ');
// Ensure ending punctuation
if (!/[.!?]$/.test(corrected)) {
corrected += '.';
}
return corrected;
}
function main() {
const args = process.argv.slice(2);
if (args.length === 0) {
console.log('Usage: node src/index.js "<sentence>"');
process.exit(1);
}
const inputSentence = args.join(' ');
const corrected = correctSentence(inputSentence);
console.log(corrected);
}
if (require.main === module) {
main();
}
+48 -78
View File
@@ -1,97 +1,67 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" """
Selfcorrecting agent demo. Simple Self-Correcting Agent
This module demonstrates a minimal usage of the OpenAI API to This script demonstrates a minimal selfcorrecting agent that
generate a response and then correct it based on a simple rule. takes a string input and attempts to correct common
typos such as extra spaces, missing punctuation, and
simple misspellings using a small dictionary.
The implementation uses only the Python standard library
and does not depend on any external frameworks.
""" """
import os
import sys import sys
from typing import Optional import re
from typing import List, Dict
try: # A very small dictionary of common misspellings
import openai MISSPELLINGS: Dict[str, str] = {
except ImportError as exc: "teh": "the",
sys.exit( "recieve": "receive",
"The 'openai' package is required. " "adress": "address",
"Install it with 'pip install -r requirements.txt'." "occured": "occurred",
) "seperate": "separate",
"definately": "definitely",
"goverment": "government",
"untill": "until",
"accomodate": "accommodate",
"wich": "which",
}
def correct_spelling(word: str) -> str:
"""Return the corrected word if it is a known misspelling."""
return MISSPELLINGS.get(word.lower(), word)
def generate_text(prompt: str, model: str = "gpt-3.5-turbo") -> str: def correct_sentence(sentence: str) -> str:
""" """
Generate a completion for the given prompt using the specified model. Correct a sentence by:
1. Removing leading/trailing whitespace.
Parameters 2. Collapsing multiple spaces into one.
---------- 3. Correcting known misspellings.
prompt : str 4. Ensuring the sentence ends with a period.
The prompt to send to the model.
model : str, optional
The OpenAI model to use. Defaults to "gpt-3.5-turbo".
Returns
-------
str
The model's raw completion text.
""" """
openai.api_key = os.getenv("OPENAI_API_KEY") # Strip whitespace
if not openai.api_key: sentence = sentence.strip()
raise ValueError("OPENAI_API_KEY environment variable is not set") # Collapse multiple spaces
sentence = re.sub(r"\s+", " ", sentence)
response = openai.ChatCompletion.create( # Tokenise and correct words
model=model, words = sentence.split(" ")
messages=[{"role": "user", "content": prompt}], corrected_words: List[str] = [correct_spelling(w) for w in words]
temperature=0.7, corrected = " ".join(corrected_words)
max_tokens=150, # Ensure ending punctuation
) if not corrected.endswith((".", "!", "?")):
return response.choices[0].message.content.strip() corrected += "."
return corrected
def correct_text(text: str) -> str:
"""
Apply a very simple selfcorrection rule: if the text ends with a
period, remove it; otherwise, add a period.
This is just a placeholder to illustrate the concept of a
selfcorrecting agent.
Parameters
----------
text : str
The text to correct.
Returns
-------
str
The corrected text.
"""
if text.endswith("."):
return text[:-1]
return text + "."
def main() -> None: def main() -> None:
""" if len(sys.argv) < 2:
Demo entry point: generate a response to a hardcoded prompt, print("Usage: python -m src.index \"<sentence>\"")
correct it, and print both versions.
"""
prompt = (
"Explain the concept of a selfcorrecting agent in simple terms."
)
try:
raw = generate_text(prompt)
except Exception as exc:
print(f"Error generating text: {exc}", file=sys.stderr)
sys.exit(1) sys.exit(1)
corrected = correct_text(raw) input_sentence = " ".join(sys.argv[1:])
corrected = correct_sentence(input_sentence)
print("=== Raw output ===")
print(raw)
print("\n=== Corrected output ===")
print(corrected) print(corrected)
if __name__ == "__main__": if __name__ == "__main__":
main() main()