# How to reset Agents programatically

**URL:** <https://community.crewai.com/t/how-to-reset-agents-programatically/5724>\
**Category:** General\
**Created:** [May 9, 2025, 9:29am UTC](https://community.crewai.com/t/how-to-reset-agents-programatically/5724 "2025-05-09T09:29:30Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![El\_Ansole](https://sea1.discourse-cdn.com/flex025/user_avatar/community.crewai.com/el_ansole/32/3616_2.png) [@El\_Ansole](https://community.crewai.com/u/El_Ansole)\
**Post date:** [May 9, 2025, 9:29am UTC](https://community.crewai.com/t/how-to-reset-agents-programatically/5724/1 "2025-05-09T09:29:30Z")

</div>

I have the following crew

```auto
@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`

```auto
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)

---

<div class="post-metadata">

**Author:** ![zinyando](https://sea1.discourse-cdn.com/flex025/user_avatar/community.crewai.com/zinyando/32/4435_2.png) [@zinyando](https://community.crewai.com/u/zinyando)\
**Post date:** [May 9, 2025, 10:55am UTC](https://community.crewai.com/t/how-to-reset-agents-programatically/5724/2 "2025-05-09T10:55:11Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![maxmoura](https://sea1.discourse-cdn.com/flex025/user_avatar/community.crewai.com/maxmoura/32/4206_2.png) [@maxmoura](https://community.crewai.com/u/maxmoura)\
**Post date:** [May 9, 2025, 12:59pm UTC](https://community.crewai.com/t/how-to-reset-agents-programatically/5724/3 "2025-05-09T12:59:38Z")

</div>

What the [CLI is doing behind the scenes](https://github.com/crewAIInc/crewAI/blob/main/src/crewai/cli/reset_memories_command.py#L8) is pretty simple. It’s just running this:

```python
# 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.

---

<div class="post-metadata">

**Author:** ![El\_Ansole](https://sea1.discourse-cdn.com/flex025/user_avatar/community.crewai.com/el_ansole/32/3616_2.png) [@El\_Ansole](https://community.crewai.com/u/El_Ansole)\
**Post date:** [May 13, 2025, 2:11am UTC](https://community.crewai.com/t/how-to-reset-agents-programatically/5724/4 "2025-05-13T02:11:12Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![maxmoura](https://sea1.discourse-cdn.com/flex025/user_avatar/community.crewai.com/maxmoura/32/4206_2.png) [@maxmoura](https://community.crewai.com/u/maxmoura)\
**Post date:** [May 13, 2025, 2:14pm UTC](https://community.crewai.com/t/how-to-reset-agents-programatically/5724/5 "2025-05-13T14:14:39Z")

</div>

> [@El\_Ansole](#):
>
> Thanks for the answer!
> 
> Doesn’t seem to work though.

@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 `Agent`s without a full `Crew`, like we discussed over in [this other thread](https://community.crewai.com/t/run-only-one-agent-in-a-crew/2757/6).

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 `Agent`s 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](https://github.com/crewAIInc/crewAI/issues) for it and make sure to link back to this discussion.

```python
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)

```

---

<div class="post-metadata">

**Author:** ![Gregg\_Casey](https://sea1.discourse-cdn.com/flex025/user_avatar/community.crewai.com/gregg_casey/32/4226_2.png) [@Gregg\_Casey](https://community.crewai.com/u/Gregg_Casey)\
**Post date:** [August 4, 2025, 9:54pm UTC](https://community.crewai.com/t/how-to-reset-agents-programatically/5724/6 "2025-08-04T21:54:13Z")

</div>

reset\_memories doesn’t work for “all” either. If you call it like this:  
chatbot\_crew.reset\_memories(‘all’)  
result = chatbot\_crew.kickoff(inputs)

You get errors like:  
ERROR:root:Error during short\_term search: ‘NoneType’ object has no attribute ‘query’  
ERROR:root:Error during entities search: ‘NoneType’ object has no attribute ‘query’

ERROR:root:Error during short\_term save: ‘NoneType’ object has no attribute ‘add’

ERROR:root:Error during entities save: ‘NoneType’ object has no attribute ‘add’

ERROR:root:Error during entities save: ‘NoneType’ object has no attribute ‘add’

ERROR:root:Error during entities save: ‘NoneType’ object has no attribute ‘add’

ERROR:root:Error during entities save: ‘NoneType’ object has no attribute ‘add’
