aboutsummaryrefslogtreecommitdiff
path: root/llm.py
blob: 834a1a919c1c4757dc1c090623eed0f49c34fc7a (plain)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#!/bin/python3
import os
from pathlib import Path
from openai import OpenAI
from typing import Optional
import argparse
import re
import subprocess
import readline
import json
from actions import *

import logging
logger = logging.getLogger(__name__)
logging.basicConfig(filename="thoughts.log",
                    level=logging.INFO)

client = OpenAI(api_key = os.environ["AALTO_LLM_KEY"],
                base_url = "https://llm-gateway.k8s.aalto.fi/api/v1")

def direct_query(query: str):
    logger.info(f"send: {query}")
    res = client.responses.create(model = "RedHatAI/gemma-4-31B-it-FP8-Dynamic",
                                  input = query)
    logger.info(f"receive: {res.output_text}")
    return res.output_text

# def reason_query(input):
#     # TODO some models may natively support reasoning
    
#     reasoning = direct_query(input + ({"role": "system",
#                                        "content": "Reason about the user's query step by step.\n\nAn answer will be generated based on your analysis."},))

#     summary = direct_query(input + ({"role": "assistant", "content": reasoning},
#                                     {"role": "system",
#                                      "content": "Formulate your previous reasoning as a concise answer to the user."}))

#     return summary

# # kinda funky
# # def flexible_query(input):
   
# #     reasoning_required = direct_query(input[-1:] + ({"role": "system", "content": "Does answering the user's question require reasoning? (y|N)"},))
# #     if reasoning_required == 'y':
# #         return reason_query(input)
# #     else:
# #         return direct_query(input)

    
def chat(content, state = (), query_method = direct_query, role = "user"):
    
    state = state + ({"role": role, "content": content},)
    
    response = query_method(state)

    state = state + ({"role": "assistant", "content": response},)
    
    return (response, state)


def path_checked(path: Path, cwd = Path.cwd()) -> Optional[Path]:
    """Resolves `path`, returning `None` if it's not a subdirectory of `cwd`."""
    path = path.resolve()
    cwd = cwd.resolve()
    return path if path.is_relative_to(cwd) else None


def inner_query_agent(actions: list, query: str, state = ()):

    state = state + ({"role": "user", "content": query},)

    (res, state) = chat(f"Based on the current state, what should you do next?\n"
                        "Respond JSON indicating an action, or respond in natural language if you are finished.",
                        state)

    # Replace all fenced JSON blocks

    replacements = []
    for m in re.finditer(r"```json\s*(.*?)\s*```", res, re.DOTALL):
        json_str = m.group(1)
        try:
            action = json.loads(json_str)
        except json.JSONDecodeError:
            continue

        for f in actions:
            result_json = f(action)
            if result_json is not None:
                replacements.append((m.start(), m.end(), action["action"]))
                break

    replaced_res = ""
    i = 0
    for (start, end, action) in replacements:
        replaced_res += res[i:start] + f"[performed '{action}']\n"
        i = end
    replaced_res += res[i:]

    if len(replacements) > 0:
        (res, state) = inner_query_agent(actions, json.dumps(result_json), state)
        return (replaced_res + "\n\n" + res, state)
    else:
        return (replaced_res, state)


def query_agent(query: str, state = ()):

    actions = [ls, read, write, tldr]

    state = state + ({"role": "system",
                      "content": f"""You are an autonomous coding agent that can help with programming tasks.
You can explore repositories, read files, search for information, and make changes to code.

You have access to the following actions, which you should embed in JSON markdown blocks "```json ACTION ```" in your responses.
{'\n'.join(map(lambda f: '* ' + f.__doc__, actions))}

Once you are finished with your task, give a response with none of the above JSON commands.
"""},)

    state = state + ({"role": "system", "content": "Analyze the following user-given task and break it down into steps."},)

    return inner_query_agent(actions, query, state)
    

def main():

    state = ()

    while True:
        
        query = input("> ").strip()

        (response, state) = query_agent(query, state)
        
        print(response)
        

if __name__ == "__main__":
    main()