-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
91 lines (61 loc) · 2.23 KB
/
Copy pathmodel.py
File metadata and controls
91 lines (61 loc) · 2.23 KB
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
# %%
from dotenv import load_dotenv
import dspy
import google.generativeai as genai
load_dotenv() # take environment variables from .env.
import os
key = os.getenv("GEMINI_API_KEY")
gemini = dspy.Google("models/gemini-1.5-flash-latest", api_key=key)
dspy.settings.configure(lm=gemini)
dataset = []
import json
with open("data.json", "r") as f:
data = json.load(f)
for d in data:
dataset.append(
dspy.Example(
project_1=d["project_1"],
project_2=d["project_2"],
should_investigate=d["investigate"],
).with_inputs("project_1", "project_2")
)
# %%
class ShouldInvestigate(dspy.Signature):
"""Decide whether two projects are similar enough to investigate plagiarism."""
project_1 = dspy.InputField(desc="The first project.")
project_2 = dspy.InputField(desc="The second project.")
answer = dspy.OutputField(
desc="Whether the projects should be investigated. One of 'yes' or 'no'."
)
cot = dspy.ChainOfThought(ShouldInvestigate)
sample = dataset[0]
pred = cot(project_1=sample.project_1, project_2=sample.project_2)
class fs(dspy.Module):
def __init__(self, num_passages=3):
super().__init__()
# self.retrieve = dspy.Retrieve(k=num_passages)
self.generate_answer = dspy.ChainOfThought(ShouldInvestigate)
def forward(self, project_1, project_2):
prediction = self.generate_answer(project_1=project_1, project_2=project_2)
return dspy.Prediction(
project_1=project_1, project_2=project_2, answer=prediction.answer
)
if __name__ == "__main__":
from dspy.teleprompt import BootstrapFewShot
def validate_answer(example, prediction, trace=None):
return example.should_investigate == prediction.answer.lower()
optimizer = BootstrapFewShot(metric=validate_answer)
optimizer.max_errors = 1
optimized_cot = optimizer.compile(fs(), trainset=dataset)
# %%
from dspy.evaluate import Evaluate
evaluate = Evaluate(
metric=validate_answer,
devset=dataset,
num_threads=1,
display_progress=True,
display_table=10,
)
evaluate(optimized_cot)
optimized_cot.save("optimized_cot.json")
# %%