File size: 1,412 Bytes
26d66c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
42
43
44
45
46
47
48
import os
from dotenv import load_dotenv, find_dotenv
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

class Chain():
    """
    Represents a chain for generating essays using a template and a language model.

    Args:
        template (str): The template to use for generating the essay.
        model (str, optional): The language model to use. Defaults to "gpt-4".

    Attributes:
        model (ChatOpenAI): The language model instance.
        template (str): The template used for generating the essay.

    Methods:
        invoke: Invokes the chain to generate an essay.

    """

    def __init__(self, template, model="gpt-4"):
        _ = load_dotenv(find_dotenv())
        self.model = ChatOpenAI(model=model)
        self.template = template

    def invoke(self, essay_topic, essay_text):
        """
        Invokes the chain to generate an essay.

        Args:
            essay_topic (str): The topic of the essay.
            essay_text (str): The text of the essay.

        Returns:
            str: The generated essay.

        """
        prompt = ChatPromptTemplate.from_template(self.template)
        output_parser = StrOutputParser()

        chain = prompt | self.model | output_parser

        return chain.invoke({"essay_topic": essay_topic, "essay_text": essay_text})