#how do I convert responses into json?

1 messages · Page 1 of 1 (latest)

rigid rivet
#

how do i convert py 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_item_data(item_entry.get())}."} ], max_tokens=300, ) into a parsable json dict?

north breachBOT
#

Hi @rigid rivet. 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 from the OpenAI API into a JSON object, you can use the json module in Python. Here's how you can do it:

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_item_data(item_entry.get())}."}
        ],
        max_tokens=300,
    )
    response_json = json.loads(response.model_dump_json())
    return response_json

In this code, response.model_dump_json() is used to convert the response into a JSON formatted string. Then, json.loads() is used to parse this JSON string into a Python dictionary.

You can then access the data in the response by using the keys in the dictionary. For example, to get the content of the message generated by the model, you can use response_json['choices'][0]['message']['content'].

Please note that the model_dump_json() function is not directly mentioned in the provided knowledge sources. However, it is used in a similar context in the OpenAI Cookbook example (https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models#2-an-example-chat-completion-api-call) to convert the response into a JSON object.

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