File size: 993 Bytes
b031170 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | !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) |