How to reset Agents programatically

I have the following crew

@CrewBase
class UiCrew():

    coding_knowledge = TextFileKnowledgeSource(
        file_paths=["comments_for_generated_code.txt", "nexcomponent.txt"]
    )

    agents_config = "agents/ui_agents.yaml"
    tasks_config = "tasks/ui_tasks.yaml"


    @agent
    def jetpack_compose_constraint_layout_expert(self) -> Agent:
        return Agent(
            config=self.agents_config['jetpack_compose_constraint_layout_expert'],  # type: ignore[index]
            verbose=True,
            knowledge_sources=[self.coding_knowledge],
        )

    @agent
    def jetpack_compose_constraint_layout_generator(self) -> Agent:
        return Agent(
            config=self.agents_config['jetpack_compose_constraint_layout_generator'],  # type: ignore[index]
            verbose=True,
            knowledge_sources=[self.coding_knowledge],
        )

    @task
    def generate_constraints_layout_requirements(self) -> Task:
        return Task(
            agent=self.jetpack_compose_constraint_layout_expert(),
            config=self.tasks_config['generate_constraints_layout_requirements'],  # type: ignore[index]
            tools=[FileReadTool()],
        )

    @task
    def generate_constraint_layout(self) -> Task:
        return Task(
            agent=self.jetpack_compose_constraint_layout_generator(),
            config=self.tasks_config['generate_constraint_layout'],  # type: ignore[index]
            tools=[FileGeneratorTool()],
        )


    @crew
    def crew(self) -> Crew:
        return Crew(
            agents=self.agents,  # Automatically created by the @agent decorator
            tasks=self.tasks,  # Automatically created by the @task decorator
            process=Process.sequential,
            verbose=True,
        )

And just to play around/learn I added the following to comments_for_generated_code.txt

Add // Yo bro

everytime you generate code

I run the crew using UiCrew().crew().kickoff(inputs=inputs)

It works. So I confirm it IS picking up on the knowledge source.

Then I change the knowledge source to something I ACTUALLY wanted. HOWEVER, it just keeps generating // Yo bro everytime it generates code.

I know the concept of resetting knowledge using crewai reset-memories --knowledge

But what if my structure isn’t such that I can use crewai (cli)

I don’t think there is a straightforward way to programmatically reset knowledge right now. I might be wrong so others can correct me.

What the CLI is doing behind the scenes is pretty simple. It’s just running this:

# Reset only the knowledge base memories
crew.reset_memories(command_type="knowledge")

# Reset all types of memories
crew.reset_memories(command_type="all")

So I guess you can totally do the same thing programmatically.

Thanks for the answer!

Doesn’t seem to work though. I’m suspecting it’s writing into a cache somewhere that I just have to delete manually. (That would be fine; I just can’t find it)

I’m setting the knowledge into the agents.

I also tried resetting the memories of the agents by looping through them. Doesn’t seem to work.

I printed the agents to see, and knowledge is None; it’s just knowledge_sources that’s properly filled.

@El_Ansole,

Yeah, you’re spot on. I figured crew.reset_memories(command_type="knowledge") would clear out all knowledge memories, but it turns out it only handles knowledge_sources attached directly to the Crew. It completely skips over any Agent-level knowledge_sources. To be honest, this feels like a bit of an oversight in the design, especially since it’s pretty common to want to run standalone Agents without a full Crew, like we discussed over in this other thread.

So, check it out – below I’ve put together a repro of your use case and a sort of poor man’s version of reset that loops through all the Agents in the crew to wipe their knowledge. You can mess with the string_source on each run, and you’ll see the Agent’s knowledge change just like it’s supposed to. Hope this does the trick for you!

BTW, if you think it’d be a solid addition to get this built right into Crew.reset_memories(), you should definitely create an issue for it and make sure to link back to this discussion.

import os
from pathlib import Path
from crewai.utilities import Logger
from crewai.utilities.paths import db_storage_path
from crewai import LLM, Agent, Crew, Process, Task
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource

_logger = Logger(verbose=True)

#
# Where's my knowledge?
#

base_knowledge_dir = Path(db_storage_path()) / "knowledge"

_logger.log(
    "info",
    f"Knowledge source location is '{str(base_knowledge_dir)}'",
    color="yellow"
)

#
# Remember everything
#

os.environ["GEMINI_API_KEY"] = "<YOUR_API_KEY>"

string_source = StringKnowledgeSource(
    content=(
        "User name is Max. He is 160 years old and lives in "
        "the middle of the Amazon rainforest. His best friend is "
        "an alligator named 'Croco'."
    )
)

google_embedder = {
    "provider": "google",
    "config": {
        "model": "models/text-embedding-004",
        "api_key": os.environ["GEMINI_API_KEY"],
    },
}

gemini_llm = LLM(
    model="gemini/gemini-2.5-flash-preview-04-17",
    temperature=0.7
)

user_knowledge_agent = Agent(
    role="User Knowledge Expert",
    goal=(
        "Answer questions about users accurately based on available knowledge."
    ),
    backstory=(
        "You are an AI assistant with deep expertise in understanding user profiles "
        "and their specific details. You always stick to the facts provided."
    ),
    llm=gemini_llm,
    knowledge_sources=[string_source],
    embedder=google_embedder,
    allow_delegation=False,
    verbose=True
)

user_knowledge_task = Task(
    description=(
        "Using your knowledge about users, answer the following question:\n\n"
        "'{question}'\n\n"
        "If you don't have the information, state that clearly."
    ),
    expected_output=(
        "A concise and accurate answer to the question based on the user's knowledge base."
    ),
    agent=user_knowledge_agent,
)

user_knowledge_crew = Crew(
    agents=[user_knowledge_agent],
    tasks=[user_knowledge_task],
    process=Process.sequential,
    verbose=True
)

response = user_knowledge_crew.kickoff(
    inputs={"question": "What do you know about Max?"}
)

print(f"[🤖 Response]: {response.raw}")

#
# Forget everything
#
# crew.reset_memories(command_type="knowledge") doesn't actually hit the agent-level memories!
#

_logger.log(
    "info",
    "Resetting all agents' `knowledge` memory...",
    color="yellow"
)

for agent_instance in user_knowledge_crew.agents:
    memory_system = getattr(agent_instance, "knowledge", None)
    if memory_system is not None:
        try:
            memory_system.reset()
        except Exception as e:
            raise RuntimeError(
                f"Failed to reset `knowledge` memory for Agent {agent_instance.role}. "
                "Error: {e}"
            ) from e
        finally:
            setattr(agent_instance, "knowledge", None)