File size: 2,451 Bytes
b064992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from MAIAI import Agent
from openai import OpenAI
import json

client = OpenAI()

class Task:
    def __init__(self, agent: Agent, goal: str, expected_output: str = ""):
        self.agent = agent
        self.goal = goal
        self.expected_output = expected_output
        
    def execute_clean(self):
            try:
                completion = client.chat.completions.create(
                    model=self.agent.model,
                    temperature=self.agent.temperature,
                    messages=[
                        {"role": "system", "content": f"{self.agent.role}"}, 
                        {"role": "user", "content": f"""{self.goal}"""}
                    ]
                )
                output = completion.choices[0].message.content
            except Exception as e:
                output = f"An error occurred: {str(e)}"
            return output
    
    def execute(self, response_type = ""):

        # Response in JSON
        if response_type == "json":
            completion = client.chat.completions.create(
            model=self.agent.model,
            temperature=self.agent.temperature,
            response_format={ "type": "json_object" },
            messages=[
                {"role": "system", "content": f"{self.agent.role}"}, 
                {"role": "user", "content": f"""You MUST give your response as json in following format: {self.expected_output}. 

                 {self.goal}"""}
                ]
            )

            try:
                output = completion.choices[0].message.content
                output = json.loads(output)

            except Exception as e:
                output = "Unable to load JSON file"
        
        # Normal response with no response type requirements
        else:    
            completion = client.chat.completions.create(
                model=self.agent.model,
                temperature=self.agent.temperature,
                messages=[
                    {"role": "system", "content": f"{self.agent.role}"}, 
                    {"role": "user", "content": f"""You MUST give your response as {self.expected_output}. 

                    {self.goal}"""}
                ]
            )

            try:
                output = completion.choices[0].message.content
            except Exception as e:
                output = None

        return output