MCPcopy Create free account
hub / github.com/OpenPipe/OpenPipe / get_chat_completion_json

Function get_chat_completion_json

client-libs/python/openpipe/shared.py:102–142  ·  view source on GitHub ↗

Converts a ChatCompletion object into a JSON object. Handles arrays and selectively includes None values for specified fields. Args: - completion (ChatCompletion): The ChatCompletion object to convert. Returns: - Dict: A JSON object representing the ChatCompletion object.

(completion: ChatCompletion)

Source from the content-addressed store, hash-verified

100
101
102def get_chat_completion_json(completion: ChatCompletion) -> Dict:
103 """
104 Converts a ChatCompletion object into a JSON object.
105 Handles arrays and selectively includes None values for specified fields.
106
107 Args:
108 - completion (ChatCompletion): The ChatCompletion object to convert.
109
110 Returns:
111 - Dict: A JSON object representing the ChatCompletion object.
112 """
113
114 include_null_fields = {
115 "content"
116 } # Set of fields to include even if they have None value
117
118 def serialize(data: Any) -> Union[Dict, List]:
119 """
120 Custom serializer function for objects, arrays, and other types.
121 Excludes fields with None values unless specified.
122 """
123 if isinstance(data, list) or isinstance(data, tuple):
124 # Recursively process each element in the list or tuple
125 return [serialize(item) for item in data]
126
127 if hasattr(data, "__dict__"):
128 # Otherwise, use the __dict__ method to get attributes
129 data = data.__dict__
130 # Filter out None values, except for specified fields
131 return {
132 key: serialize(value)
133 if isinstance(value, (list, tuple, Dict))
134 else value
135 for key, value in data.items()
136 if value is not None or key in include_null_fields
137 }
138
139 return data
140
141 # Serialize the object and then load it back as a dictionary
142 return json.loads(json.dumps(completion, default=serialize, indent=4))

Callers 4

_genMethod · 0.85
createMethod · 0.85
_genMethod · 0.85
createMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected