[Python] How to retrieve content from ChatCompletionMessage object with Python

Discussão em 'Python' iniciado por Stack, Maio 16, 2025.

  1. Stack

    Stack Membro Participativo

    if user_query: processed_result = consume_and_process()

    # Check if processed_result contains the 'content' field
    if isinstance(processed_result, str): # If processed_result is already just a string
    content = processed_result
    elif hasattr(processed_result, 'content'): # If processed_result is a ChatCompletionMessage object
    content = processed_result.content
    else:
    content = "Error: Failed to process query."

    #small test
    print(f"Processed result content: {content}") # This will print the content to the console

    return jsonify({
    "status": "success",
    "message": "Query sent to Kafka",
    "query": user_query,
    "processed_result": content # Only include the content field in the response
    }), 200
    else:
    return jsonify({
    "status": "error",
    "message": "No query received"
    }), 400

    I have this code that sent a user query to an LLM through an API and I do get a responce back looking like this :


    { "message": "Query sent to Kafka", "processed_result": "ChatCompletionMessage(content='Hello! How can I help you today?', role='assistant', function_call=None, tool_calls=None, refusal=None, annotations=[])", "query": "Hello ", "status": "success" }

    but i want to retrieve only the content part and can't figure out how to do so ...

    I tried .get method but didn't work because it only accpet a json object but i want it to accpet both json and json responces , i also tried many other ways but nothing worked . What i expect is something that accpets both types of responces and in this case of a user query i want it to give me back only the conet of the respince for exemple if i write 'hello' it answe r directly with 'hello ,,,'

    Continue reading...

Compartilhe esta Página