Skip to content

Commit 7a021a0

Browse files
committed
2 parents def0032 + 8751b6b commit 7a021a0

4 files changed

Lines changed: 228 additions & 0 deletions

File tree

com/inbravo/llm/ollama_evaluate.py

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
# Copyright (c) Sebastian Raschka under Apache License 2.0 (see LICENSE.txt).
2+
# Source for "Build a Large Language Model From Scratch"
3+
# - https://www.manning.com/books/build-a-large-language-model-from-scratch
4+
# Code: https://github.com/rasbt/LLMs-from-scratch
5+
#
6+
# A minimal instruction finetuning file based on the code in chapter 7
7+
8+
import json
9+
import psutil
10+
from tqdm import tqdm
11+
import urllib.request
12+
13+
14+
def query_model(prompt, model="llama3", url="http://localhost:11434/api/chat"):
15+
# Create the data payload as a dictionary
16+
data = {
17+
"model": model,
18+
"messages": [
19+
{"role": "user", "content": prompt}
20+
],
21+
"options": { # Settings below are required for deterministic responses
22+
"seed": 123,
23+
"temperature": 0,
24+
"num_ctx": 2048
25+
}
26+
}
27+
28+
# Convert the dictionary to a JSON formatted string and encode it to bytes
29+
payload = json.dumps(data).encode("utf-8")
30+
31+
# Create a request object, setting the method to POST and adding necessary headers
32+
request = urllib.request.Request(url, data=payload, method="POST")
33+
request.add_header("Content-Type", "application/json")
34+
35+
# Send the request and capture the response
36+
response_data = ""
37+
with urllib.request.urlopen(request) as response:
38+
# Read and decode the response
39+
while True:
40+
line = response.readline().decode("utf-8")
41+
if not line:
42+
break
43+
response_json = json.loads(line)
44+
response_data += response_json["message"]["content"]
45+
46+
return response_data
47+
48+
49+
def check_if_running(process_name):
50+
running = False
51+
for proc in psutil.process_iter(["name"]):
52+
if process_name in proc.info["name"]:
53+
running = True
54+
break
55+
return running
56+
57+
58+
def format_input(entry):
59+
instruction_text = (
60+
f"Below is an instruction that describes a task. "
61+
f"Write a response that appropriately completes the request."
62+
f"\n\n### Instruction:\n{entry['instruction']}"
63+
)
64+
65+
input_text = f"\n\n### Input:\n{entry['input']}" if entry["input"] else ""
66+
67+
return instruction_text + input_text
68+
69+
70+
def main(file_path):
71+
ollama_running = check_if_running("ollama")
72+
73+
if not ollama_running:
74+
raise RuntimeError("Ollama not running. Launch ollama before proceeding.")
75+
print("Ollama running:", check_if_running("ollama"))
76+
77+
with open(file_path, "r") as file:
78+
test_data = json.load(file)
79+
80+
model = "llama3"
81+
scores = generate_model_scores(test_data, "model_response", model)
82+
print(f"Number of scores: {len(scores)} of {len(test_data)}")
83+
print(f"Average score: {sum(scores)/len(scores):.2f}\n")
84+
85+
86+
def generate_model_scores(json_data, json_key, model="llama3"):
87+
scores = []
88+
for entry in tqdm(json_data, desc="Scoring entries"):
89+
if entry[json_key] == "":
90+
scores.append(0)
91+
else:
92+
prompt = (
93+
f"Given the input `{format_input(entry)}` "
94+
f"and correct output `{entry['output']}`, "
95+
f"score the model response `{entry[json_key]}`"
96+
f" on a scale from 0 to 100, where 100 is the best score. "
97+
f"Respond with the integer number only."
98+
)
99+
score = query_model(prompt, model)
100+
try:
101+
scores.append(int(score))
102+
except ValueError:
103+
print(f"Could not convert score: {score}")
104+
continue
105+
106+
return scores
107+
108+
109+
if __name__ == "__main__":
110+
111+
import argparse
112+
113+
parser = argparse.ArgumentParser(
114+
description="Evaluate model responses with ollama"
115+
)
116+
parser.add_argument(
117+
"--file_path",
118+
required=True,
119+
help=(
120+
"The path to the test dataset `.json` file with the"
121+
" `'output'` and `'model_response'` keys"
122+
)
123+
)
124+
args = parser.parse_args()
125+
126+
main(file_path=args.file_path)

com/inbravo/modules/mod.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
This module provides an example of a Python script with a constant, a function, and a class.
3+
"""
4+
5+
QUOTE = "If Comrade Napoleon says it, it must be right."
6+
NUMBERS = [100, 200, 300]
7+
8+
def print_argument(argument):
9+
"""
10+
Prints the provided argument.
11+
"""
12+
print(f'argument = {argument}')
13+
14+
class ExampleClass:
15+
"""
16+
Example class with two public methods.
17+
"""
18+
19+
def method_one(self):
20+
"""
21+
First example method.
22+
"""
23+
return "Method one executed."
24+
25+
def method_two(self):
26+
"""
27+
Second example method.
28+
"""
29+
return "Method two executed."

com/inbravo/modules/mod_test.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# trunk-ignore-all(black)
2+
"""This module demonstrates importing and printing constants from another module."""
3+
4+
# Importing specific constants instead of the entire module
5+
from mod import NUMBERS, QUOTE
6+
7+
# You can also import everything using '*', but it's not recommended
8+
# '*' will place the names of all objects from module into the local symbol table, with the exception of any that begin with the underscore (_) character.
9+
print(QUOTE)
10+
print(NUMBERS)
11+
print("-----")
12+
13+
# Importing the entire module
14+
import mod
15+
16+
print(mod.QUOTE)
17+
print(mod.NUMBERS)
18+
print("-----")
19+
20+
# Importing the class from the module
21+
from mod import ExampleClass
22+
23+
example_instance = ExampleClass()
24+
print(example_instance.method_one())
25+
print(example_instance.method_two())
26+
print("-----")
27+
28+
# Importing the entire module and using the class
29+
import mod
30+
31+
example_instance2 = mod.ExampleClass()
32+
print(example_instance2.method_one())
33+
print(example_instance2.method_two())
34+
print("-----")
35+
36+
# Importing the function from the module
37+
from mod import print_argument
38+
39+
print_argument("Hello from mod_test.py")
40+
print("-----")
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from selenium import webdriver
2+
from selenium.webdriver.common.by import By
3+
from selenium.webdriver.support.ui import WebDriverWait
4+
from selenium.webdriver.support import expected_conditions as EC
5+
import time
6+
7+
# Initialize the WebDriver (Make sure you have the appropriate WebDriver for your browser)
8+
driver = webdriver.Chrome() # You can use Firefox, Edge, etc., by replacing `Chrome` with the desired browser.
9+
10+
try:
11+
# Open the web page
12+
driver.get("https://providencejournal.com/story/sports/high-school/2025/09/15/vote-for-providence-journal-week-1-high-school-football-player-of-the-week-2025-rhode-island-mvp/86151823007/") # Replace with the URL of the web page you want to access.
13+
14+
# Wait for the page to load and locate the radio button
15+
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, "radio_button_name")))
16+
17+
# Select the radio button (replace 'radio_button_name' with the actual name or ID of the radio button)
18+
radio_button = driver.find_element(By.NAME, "radio_button_name")
19+
radio_button.click()
20+
21+
# Wait for the submit button to be clickable
22+
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, "submit_button_name")))
23+
24+
# Click the submit button (replace 'submit_button_name' with the actual name or ID of the submit button)
25+
submit_button = driver.find_element(By.NAME, "submit_button_name")
26+
submit_button.click()
27+
28+
# Optionally, wait for the next page to load or for a confirmation message
29+
time.sleep(5) # Adjust the sleep time as needed.
30+
31+
finally:
32+
# Close the browser
33+
driver.quit()

0 commit comments

Comments
 (0)