[Python] Python String 1:1 to Custom Object

Discussão em 'Python' iniciado por Stack, Junho 4, 2025.

  1. Stack

    Stack Membro Participativo

    So, I am working with the Gemini API and I want to send a chat but the problem is, it is requiring a array of types.Content (Documentation: https://ai.google.dev/api/caching#Content) as "history".

    My Problem is: I have this array perfectly done but it is inside a string. (I have it in a string, to easily store it in my MongoDB db)

    It should look like this:

    history=[
    types.Content(role="user", parts=[types.Part(text="User-Question")]),
    types.Content(role="model", parts=[types.Part(text="AI-Answer")],)
    ]


    But what I have is this:

    history=[
    "types.Content(role='user', parts=[types.Part(text='User-Question')])",
    "types.Content(role='model', parts=[types.Part(text='AI-Answer')])"
    ]


    You get my Problem?

    I have tried to use eval(), literal_eval() and many other more solutions (i found on google).

    Edit: My eval try:

    for part in result["history"]:
    print(type(part), part)
    x = eval(part)


    Output:


    <class 'str'> types.Content(role='user', text='Erkläre kurz, was ein LLM ist.\n') unterminated string literal (detected at line 1) (<string>, line 1)
    ​

    Continue reading...

Compartilhe esta Página