Skip to content

Message History is not working with redis. #2664

@shubhajit-chowdhury

Description

@shubhajit-chowdhury

Initial Checks

Description

I am using Redis to store the message history. However, it is not working. I have double-checked the message_history variable and it's loading properly. Please help to fix it.

Example Code

def save_history(key: str, messages: Any) -> None:
    redis_client.set(key, json.dumps(to_jsonable_python(messages)))

def load_history(key: str) -> Any:
    history_raw = redis_client.get(key)
    if not history_raw:
        return None
    
    # Ensure always string before parsing
    if isinstance(history_raw, bytes):
        history_raw = history_raw.decode("utf-8")

    history_json = json.loads(history_raw)
    return ModelMessagesTypeAdapter.validate_python(history_json)

@app.post("/api/query_agent")
async def query_agent(request: QueryRequest):

    message_history = load_history("message_history")
    print(type(message_history))

    # Run agent
    result = await research_agent.run(
        f'Act as an expert director who answers questions and tries to solve business problems. '
        f'Answer the question: "{request.query}". Make sure to hold yourself from rushing. '
        f'Slow down, think and answer. Always deliver high quality + value answers. '
        f'Always double check before giving the answer. Only return the answer. '
        f'Nothing more than that. Do not show any thinking text or any other text '
        f'You have access to your previous conversations. '
        f'Use them to answer the question if needed. If you do not know the answer',
        message_history=message_history
    )

    save_history("message_history", result.all_messages())
    
    return {"received_data": result.output}

Python, Pydantic AI & LLM client version

I am using latest version of pydantic ai and python version: 3.11.5
As LLM I am using google gemini models.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions