feat: solution for 'Экзамен: Самокорректирующийся агент'
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Simple Self-Correcting Agent
|
||||
*
|
||||
* This script demonstrates a minimal self‑correcting 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
@@ -1,97 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Self‑correcting agent demo.
|
||||
Simple Self-Correcting Agent
|
||||
|
||||
This module demonstrates a minimal usage of the OpenAI API to
|
||||
generate a response and then correct it based on a simple rule.
|
||||
This script demonstrates a minimal self‑correcting 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 Python standard library
|
||||
and does not depend on any external frameworks.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from typing import Optional
|
||||
import re
|
||||
from typing import List, Dict
|
||||
|
||||
try:
|
||||
import openai
|
||||
except ImportError as exc:
|
||||
sys.exit(
|
||||
"The 'openai' package is required. "
|
||||
"Install it with 'pip install -r requirements.txt'."
|
||||
)
|
||||
# A very small dictionary of common misspellings
|
||||
MISSPELLINGS: Dict[str, str] = {
|
||||
"teh": "the",
|
||||
"recieve": "receive",
|
||||
"adress": "address",
|
||||
"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.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
prompt : str
|
||||
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.
|
||||
Correct a sentence by:
|
||||
1. Removing leading/trailing whitespace.
|
||||
2. Collapsing multiple spaces into one.
|
||||
3. Correcting known misspellings.
|
||||
4. Ensuring the sentence ends with a period.
|
||||
"""
|
||||
openai.api_key = os.getenv("OPENAI_API_KEY")
|
||||
if not openai.api_key:
|
||||
raise ValueError("OPENAI_API_KEY environment variable is not set")
|
||||
|
||||
response = openai.ChatCompletion.create(
|
||||
model=model,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
temperature=0.7,
|
||||
max_tokens=150,
|
||||
)
|
||||
return response.choices[0].message.content.strip()
|
||||
|
||||
|
||||
def correct_text(text: str) -> str:
|
||||
"""
|
||||
Apply a very simple self‑correction 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
|
||||
self‑correcting agent.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
text : str
|
||||
The text to correct.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The corrected text.
|
||||
"""
|
||||
if text.endswith("."):
|
||||
return text[:-1]
|
||||
return text + "."
|
||||
|
||||
# Strip whitespace
|
||||
sentence = sentence.strip()
|
||||
# Collapse multiple spaces
|
||||
sentence = re.sub(r"\s+", " ", sentence)
|
||||
# Tokenise and correct words
|
||||
words = sentence.split(" ")
|
||||
corrected_words: List[str] = [correct_spelling(w) for w in words]
|
||||
corrected = " ".join(corrected_words)
|
||||
# Ensure ending punctuation
|
||||
if not corrected.endswith((".", "!", "?")):
|
||||
corrected += "."
|
||||
return corrected
|
||||
|
||||
def main() -> None:
|
||||
"""
|
||||
Demo entry point: generate a response to a hard‑coded prompt,
|
||||
correct it, and print both versions.
|
||||
"""
|
||||
prompt = (
|
||||
"Explain the concept of a self‑correcting agent in simple terms."
|
||||
)
|
||||
try:
|
||||
raw = generate_text(prompt)
|
||||
except Exception as exc:
|
||||
print(f"Error generating text: {exc}", file=sys.stderr)
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python -m src.index \"<sentence>\"")
|
||||
sys.exit(1)
|
||||
|
||||
corrected = correct_text(raw)
|
||||
|
||||
print("=== Raw output ===")
|
||||
print(raw)
|
||||
print("\n=== Corrected output ===")
|
||||
input_sentence = " ".join(sys.argv[1:])
|
||||
corrected = correct_sentence(input_sentence)
|
||||
print(corrected)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user