#Convert response to JSON

1 messages · Page 1 of 1 (latest)

errant vessel
#
def run_ai():
    response = client.chat.completions.create(
        model=choose_model(model=model_selector_entry.get()),
        messages=[
          {"role": "system", "content": f"{instructions}"},
          {"role": "user", "content": f"The json data is {get_summoning_eye_data(item_entry.get())}."}
        ],
        max_tokens=300,
    )
    print(response.choices[0].message.content)
    print(f"Runtime was: {calculate_runtime()} ms.")
    print(f"JSON Data:\n{...}")```

how would I convert `response` into actual json, and not ChatCompletion?
coarse skiffBOT
#

Hi @errant vessel. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To convert the response object into actual JSON, you can use the json module in Python. Specifically, you can use the json.dumps() function, which serializes Python objects into a JSON formatted string.

Here's how you can modify your run_ai function to print the response as JSON:

import json

def run_ai():
    response = client.chat.completions.create(
        model=choose_model(model=model_selector_entry.get()),
        messages=[
          {"role": "system", "content": f"{instructions}"},
          {"role": "user", "content": f"The json data is {get_summoning_eye_data(item_entry.get())}."}
        ],
        max_tokens=300,
    )
    json_response = json.dumps(response.choices[0].message.content)
    print(json_response)
    print(f"Runtime was: {calculate_runtime()} ms.")
    print(f"JSON Data:\n{...}")

In this code, json.dumps(response.choices[0].message.content) converts the response.choices[0].message.content object into a JSON formatted string.

Please note that the json.dumps() function only works with data that can be serialized into JSON. If response.choices[0].message.content contains data types that are not serializable (like custom Python objects), you may need to write additional code to handle those data types.

Also, remember to handle any exceptions that might occur during the conversion process. For example, if the response content is not a valid JSON, json.dumps() will raise a TypeError. You can use a try-except block to handle such exceptions and prevent your program from crashing.

For more information, you can refer to the Python json module documentation: https://docs.python.org/3/library/json.html

#

@errant vessel kapa.ai is still learning and improving, please let us know how it did by reacting below

errant vessel
#

@coarse skiff not quite. im looking for the json response, an example of it is in the json provided

{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1677652288,
  "model": "gpt-3.5-turbo-0125",
  "system_fingerprint": "fp_44709d6fcb",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "\n\nHello there, how may I assist you today?",
    },
    "logprobs": null,
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 12,
    "total_tokens": 21
  }
}```
coarse skiffBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The response object returned by the client.chat.completions.create() method is an instance of the ChatCompletion class, which includes various properties such as id, object, created, model, choices, and usage.

If you want to convert this response object into a JSON string that matches the format of the example you provided, you can use the .__dict__ method to convert the response object into a dictionary, and then use json.dumps() to convert that dictionary into a JSON string.

Here's how you can modify your run_ai function to do this:

import json

def run_ai():
    response = client.chat.completions.create(
        model=choose_model(model=model_selector_entry.get()),
        messages=[
          {{"role": "system", "content": f"{{instructions}}"}},
          {{"role": "user", "content": f"The json data is {{get_summoning_eye_data(item_entry.get())}}."}}
        ],
        max_tokens=300,
    )
    json_response = json.dumps(response.__dict__)
    print(json_response)
    print(f"Runtime was: {{calculate_runtime()}} ms.")
    print(f"JSON Data:\n{{...}}")

In this code, response.__dict__ converts the response object into a dictionary, and json.dumps(response.__dict__) converts that dictionary into a JSON formatted string.

Please note that this will only work if all the properties of the response object (and any nested objects) can be serialized into JSON. If there are any non-serializable properties, you may need to write additional code to handle those.

For more information, you can refer to the Python json module documentation: https://docs.python.org/3/library/json.html

#

@errant vessel kapa.ai is still learning and improving, please let us know how it did by reacting below

errant vessel
#

TypeError: Object of type Choice is not JSON serializable @coarse skiff

coarse skiffBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The error message "TypeError: Object of type Choice is not JSON serializable" means that Python's json module is trying to convert an object of type Choice into JSON, but it doesn't know how to do it. This is because the json module can only serialize basic data types by default, such as: dict, list, str, int, float, bool, None.

In the context of OpenAI's API, a Choice object is part of the response from a chat completion and contains the message generated by the model. To serialize this Choice object into JSON, you need to convert it into a serializable format (like a dictionary) first.

Here's an example of how you can modify your run_ai function to do this:

import json

def run_ai():
    response = client.chat.completions.create(
        model=choose_model(model=model_selector_entry.get()),
        messages=[
          {{"role": "system", "content": f"{{instructions}}"}},
          {{"role": "user", "content": f"The json data is {{get_summoning_eye_data(item_entry.get())}}."}}
        ],
        max_tokens=300,
    )
    response_dict = response.__dict__
    response_dict["choices"] = [choice.__dict__ for choice in response_dict["choices"]]
    json_response = json.dumps(response_dict)
    print(json_response)
    print(f"Runtime was: {{calculate_runtime()}} ms.")
    print(f"JSON Data:\n{{...}}")

In this code, response.__dict__ converts the response object into a dictionary. Then, [choice.__dict__ for choice in response_dict["choices"]] converts each Choice object in the choices list into a dictionary. Finally, json.dumps(response_dict) converts the modified response_dict dictionary into a JSON formatted string.

#

Please note that this will only work if all the properties of the response object, the Choice objects, and any nested objects can be serialized into JSON. If there are any non-serializable properties, you may need to write additional code to handle those.

For more information, you can refer to the Python json module documentation: https://docs.python.org/3/library/json.html

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: