1616from guardrails .utils .safe_get import safe_get_with_brackets
1717from guardrails .validators import LowerCase
1818
19- # Set mock OpenAI API key
20- os .environ ["OPENAI_API_KEY" ] = "sk-xxxxxxxxxxxxxx"
21-
2219expected_raw_output = '{"statement": "I am DOING well, and I HOPE you aRe too."}'
2320expected_fix_output = json .dumps (
2421 {"statement" : "i am doing well, and i hope you are too." }, indent = 4
2926expected_filter_refrain_output = json .dumps ({}, indent = 4 )
3027
3128
29+ class Delta :
30+ content : str
31+
32+ def __init__ (self , content ):
33+ self .content = content
34+
35+
36+ class Choice :
37+ text : str
38+ finish_reason : str
39+ index : int
40+ delta : Delta
41+
42+ def __init__ (self , text , delta , finish_reason , index = 0 ):
43+ self .index = index
44+ self .delta = delta
45+ self .text = text
46+ self .finish_reason = finish_reason
47+
48+
49+ class MockOpenAIV1ChunkResponse :
50+ choices : list
51+ model : str
52+
53+ def __init__ (self , choices , model ):
54+ self .choices = choices
55+ self .model = model
56+
57+
3258def mock_openai_completion_create ():
3359 # Returns a generator
3460 chunks = [
@@ -41,10 +67,22 @@ def mock_openai_completion_create():
4167
4268 def gen ():
4369 for chunk in chunks :
44- yield {
45- "choices" : [{"text" : chunk , "finish_reason" : None }],
46- "model" : "OpenAI model name" ,
47- }
70+ if OPENAI_VERSION .startswith ("0" ):
71+ yield {
72+ "choices" : [{"text" : chunk , "finish_reason" : None }],
73+ "model" : "OpenAI model name" ,
74+ }
75+ else :
76+ yield MockOpenAIV1ChunkResponse (
77+ choices = [
78+ Choice (
79+ text = chunk ,
80+ delta = Delta (content = "" ),
81+ finish_reason = None ,
82+ )
83+ ],
84+ model = "OpenAI model name" ,
85+ )
4886
4987 return gen ()
5088
@@ -61,15 +99,27 @@ def mock_openai_chat_completion_create():
6199
62100 def gen ():
63101 for chunk in chunks :
64- yield {
65- "choices" : [
66- {
67- "index" : 0 ,
68- "delta" : {"content" : chunk },
69- "finish_reason" : None ,
70- }
71- ]
72- }
102+ if OPENAI_VERSION .startswith ("0" ):
103+ yield {
104+ "choices" : [
105+ {
106+ "index" : 0 ,
107+ "delta" : {"content" : chunk },
108+ "finish_reason" : None ,
109+ }
110+ ]
111+ }
112+ else :
113+ yield MockOpenAIV1ChunkResponse (
114+ choices = [
115+ Choice (
116+ text = "" ,
117+ delta = Delta (content = chunk ),
118+ finish_reason = None ,
119+ )
120+ ],
121+ model = "OpenAI model name" ,
122+ )
73123
74124 return gen ()
75125
0 commit comments