This repository was archived by the owner on Dec 11, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathconftest.py
More file actions
253 lines (200 loc) · 6.62 KB
/
Copy pathconftest.py
File metadata and controls
253 lines (200 loc) · 6.62 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
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"""File to define fixtures for Pytest"""
import json
import os
import random
import sys
from typing import Any, Dict, List
import pandas as pd
import pytest
from pydantic import BaseModel, Field
from notdiamond.callbacks import NDLLMBaseCallbackHandler
from notdiamond.llms.client import _NDClientTarget, _ndllm_factory
from notdiamond.llms.config import LLMConfig
from notdiamond.toolkit import CustomRouter
sys.path.append(os.path.join(os.path.dirname(__file__), "helpers"))
@pytest.fixture
def prompt():
return [
{
"role": "user",
"content": "Write me a song about goldfish on the moon",
}
]
@pytest.fixture
def openai_style_messages():
"""Fixture to create a Prompt Template"""
return [
{"role": "user", "content": "Hello, what's your name?"},
{"role": "assistant", "content": "My name is Isaac Asimov"},
{"role": "user", "content": "And what do you do?"},
]
@pytest.fixture
def llm_base_callback_handler():
"""Fixture to create a custom NDLLMBaseCallbackHandler"""
class CustomNDLLMBaseCallbackHandler(NDLLMBaseCallbackHandler):
def on_model_select(self, model_provider, model_name):
self.on_model_select_called = True
def on_latency_tracking(
self, session_id, model_provider, tokens_per_second
):
self.on_latency_tracking_called = True
def on_api_error(self, error_message):
self.on_api_error_called = True
def on_llm_start(
self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
):
self.on_llm_start_called = True
return CustomNDLLMBaseCallbackHandler()
@pytest.fixture
def tools_fixture():
"""Fixture that creates multiple tools"""
from langchain_core.tools import tool
@tool
def add_fct(a: int, b: int) -> int:
"""Adds a and b."""
return a + b
return [add_fct]
@pytest.fixture
def openai_tools_fixture():
"""Fixture that creates multiple tools"""
add_tool = {
"name": "add_fct",
"description": "Add two numbers",
"parameters": {
"type": "object",
"properties": {
"a": {"type": "integer", "description": "The first number"},
"b": {"type": "integer", "description": "The second number"},
},
"required": ["a", "b"],
},
}
return [add_tool]
@pytest.fixture
def get_stock_price_tool_fixture():
"""Fixture that creates a tool for getting stock prices."""
stock_tool = {
"name": "get_stock_price",
"description": "Get current stock price for a provided ticker symbol from Yahoo Finance using the yahooquery Python library.",
"parameters": {
"type": "object",
"properties": {"ticker": {"type": "string"}},
"required": ["ticker"],
"additionalProperties": False,
},
}
return [stock_tool]
@pytest.fixture
def response_model():
class Joke(BaseModel):
setup: str = Field(description="question to set up a joke")
punchline: str = Field(description="answer to resolve the joke")
return Joke
@pytest.fixture
def custom_router_task(path="tests/static/bbh_implicatures.json"):
with open(path) as f:
return json.load(f)
@pytest.fixture
def custom_router_dataset(custom_router_task):
inputs = []
for x in custom_router_task["examples"][:15]:
inputs.append(x["input"].strip())
llm_configs = [
"openai/gpt-3.5-turbo",
"anthropic/claude-3-haiku-20240307",
]
dataset = {}
for provider in llm_configs:
data = {
"query": inputs,
"response": inputs,
"score": [random.randrange(0, 10) for _ in inputs],
}
dataset[provider] = pd.DataFrame(data)
return dataset, "query", "response", "score"
@pytest.fixture
def custom_router_and_model_dataset(custom_router_task):
inputs = []
for x in custom_router_task["examples"][:15]:
inputs.append(x["input"].strip())
custom_model = LLMConfig(
provider="custom",
model="model",
is_custom=True,
context_length=100,
input_price=1,
output_price=2,
latency=0.1,
)
llm_configs = [
"openai/gpt-3.5-turbo",
"anthropic/claude-3-haiku-20240307",
custom_model,
]
dataset = {}
for provider in llm_configs:
data = {
"query": inputs,
"response": inputs,
"score": [random.randrange(0, 10) for _ in inputs],
}
dataset[provider] = pd.DataFrame(data)
return dataset, "query", "response", "score"
@pytest.fixture
def custom_router_pref_id(custom_router_dataset):
(
dataset,
prompt_column,
response_column,
score_column,
) = custom_router_dataset
custom_router = CustomRouter()
preference_id = custom_router.fit(
dataset=dataset,
prompt_column=prompt_column,
response_column=response_column,
score_column=score_column,
)
assert isinstance(preference_id, str)
return preference_id
@pytest.fixture
def nd_invoker_cls():
return _ndllm_factory(_NDClientTarget.INVOKER)
@pytest.fixture
def nd_router_cls():
return _ndllm_factory(_NDClientTarget.ROUTER)
def _redact_xtoken_response(response: Any) -> Any:
for key in ["x-token", "x-api-key"]:
if (
key in response["headers"]
and response["headers"][key] != "REDACTED"
):
response["headers"][key] = ["REDACTED"]
return response
def _before_record_request(request: Any) -> Any:
# fastapi example client
if "testserver" in request.uri:
print(f"Ignoring request URI: {request.uri}")
return None
# posthog keys
if request.body is not None:
body = json.loads(request.body)
for key in ["api_key", "x-api-key"]:
if key in body and body[key] != "REDACTED":
body[key] = "REDACTED"
request.body = json.dumps(body)
elif key in request.headers and request.headers[key] != "REDACTED":
request.headers[key] = "REDACTED"
return request
@pytest.fixture(scope="module")
def vcr_config():
record_mode = os.getenv("RECORD_MODE", "none")
return {
"filter_headers": ["authorization", "x-token"],
"allowed_hosts": ["testserver", "127.0.0.1"],
"before_record_response": _redact_xtoken_response,
"before_record_request": _before_record_request,
"ignore_localhost": True,
"record_mode": record_mode,
"decode_compressed_response": True,
}