xyz / Python Program to write code and execute Using LLM
avra121's picture
Create Python Program to write code and execute Using LLM
b031170 verified
Raw History Blame Contribute Delete
993 Bytes
!pip install -q transformers accelerate
import torch
from transformers import pipeline, GenerationConfig
import re
generator = pipeline(
"text-generation",
model="Qwen/Qwen2.5-Coder-1.5B-Instruct",
model_kwargs={"dtype": torch.float16},
device_map="auto"
)
gen_config = GenerationConfig(
max_new_tokens=512
)
def chat_with_coder(user_prompt):
prompt = f"""You are a Python coding assistant.
Write ONLY valid Python code inside ```python blocks. Do not explain.
Task: {user_prompt}
"""
output = generator(
prompt,
generation_config=gen_config
)
return output[0]["generated_text"]
task = input("Enter your coding task: ")
ai_response = chat_with_coder(task)
code_match = re.search(r"```python\n(.*?)```", ai_response, re.DOTALL)
if code_match:
code_to_run = code_match.group(1)
print("\n--- Generated Code ---\n")
print(code_to_run)
else:
print("Could not extract valid code.")
print("\nRaw Output:\n", ai_response)