|
import os |
|
from langchain_openai import ChatOpenAI |
|
from langchain.prompts import PromptTemplate |
|
from langchain.chains import LLMChain |
|
|
|
|
|
|
|
api_key = os.getenv("OPENAI_API_KEY", "") |
|
if not api_key: |
|
raise EnvironmentError("OPENAI_API_KEY no definido. Configura este valor en Hugging Face -> Settings -> Secrets.") |
|
|
|
|
|
llm = ChatOpenAI( |
|
openai_api_key=api_key, |
|
temperature=0.7, |
|
model="gpt-4" |
|
) |
|
|
|
|
|
template = """ |
|
Eres un asistente de IA que orienta a los alumnos a ser mejores personas. Haz una haiku de 5 lineas sobre lo que te estan comentando. Da siempre la respuesta en Español. |
|
Texto:{texto} |
|
Respuesta: |
|
""" |
|
|
|
prompt = PromptTemplate( |
|
input_variables=["texto"], |
|
template=template |
|
) |
|
|
|
chain = LLMChain( |
|
llm=llm, |
|
prompt=prompt |
|
) |
|
|
|
def save_summary_to_file(summary_text, filename='results/OpenAI_response.txt'): |
|
try: |
|
os.makedirs(os.path.dirname(filename), exist_ok=True) |
|
with open(filename, 'w', encoding='utf-8') as file: |
|
file.write(summary_text) |
|
print(f"Resumen guardado en: {filename}") |
|
except Exception as e: |
|
print(f"Error al guardar el resumen: {e}") |
|
|
|
def read_text_from_file(filename): |
|
try: |
|
with open(filename, 'r', encoding='utf-8') as file: |
|
return file.read() |
|
except Exception as e: |
|
print(f"Error al leer el archivo {filename}: {e}") |
|
return "" |
|
|
|
def moni(archivo): |
|
texto_usuario = read_text_from_file(archivo) |
|
resultado = chain.run(texto=texto_usuario) |
|
print("Resultado generado por LLM:") |
|
print(resultado) |
|
save_summary_to_file(resultado) |
|
return resultado |
|
|
|
|