Skip to main content

Research Assistant

Transform your Truffle Agent into a powerful research companion by leveraging Perplexity search, stateful history, and dynamic tool exposure.

What you'll learn:

  1. Scaffold a new Truffle app
  2. Create a Perplexity-powered research tool
  3. Conditionally expose tools with predicates
  4. Persist and view research history
  5. Save history to a local file
  6. (Optional) Organize tools into groups
  7. Build & deploy your app

πŸ“‚ 1. Init​

truffle init

This creates:

  • app.py (your main Python file)
  • manifest.json (metadata & example prompts)
  • requirements.txt (dependencies)

🦴 2. Outline​

Edit app.py:

import truffle

class ResearchAssistant:
def __init__(self):
self.client = truffle.TruffleClient()
self.research_history = []

if __name__ == "__main__":
truffle.run(ResearchAssistant())
  • self.client connects you to Truffle's backend
  • self.research_history holds past queries & answers

πŸ” 3. Add the Research Tool​

Add this method to your class:

@truffle.tool(
description="Perform web research using Perplexity",
icon="magnifyingglass"
)
@truffle.args(query="Topic or question to research")
def research(self, query: str) -> str:
"""Searches Perplexity and stores the result."""
self.client.tool_update("πŸš€ Starting research…")
response = self.client.perplexity_search(query=query, model="sonar-pro")
self.client.tool_update("βœ… Research complete.")
self.research_history.append({"query": query, "answer": response})
return response
  • @truffle.tool registers it as a callable tool
  • @truffle.args documents the parameter
  • tool_update() shows live status in the client
Tool Return Values

When your tool method returns a string, that text is passed directly back into the conversation as the tool's output. The LLM sees this output in its context window, so you can use the return value to:

  • Provide a concise summary or formatted data
  • Include extra guidance or links for the model's next step
  • Shape the follow-up responses by controlling exactly what the model "knows"

Think of your return value as the bridge between your Python code and the model's next inference: whatever you return becomes part of the Agent's "memory" for that turn.


πŸ—„οΈ 4. Conditional Tool Exposure with Predicates​

Predicates let you control exactly which tools your Agent sees at runtime. Instead of a fixed list, you can write any Python function that returns True or False, and Docusaurus will only expose the tool when your logic allows it. This means you can:

  • Show or hide tools based on internal state (e.g. only after you've run a search)
  • React to environment variables, config flags, or user roles
  • Build arbitrarily complex visibility rules to keep your UI clean and context-aware
def _has_history(self) -> bool:
"""Return True only if we've recorded at least one research result."""
return len(self.research_history) > 0

@truffle.tool(
description="Display past research history",
icon="list.bullet.clipboard",
predicate=_has_history # only appear when _has_history() returns True
)
def view_history(self) -> str:
"""Returns a formatted list of past queries & answers."""
if not self.research_history:
return "No research history recorded yet."
lines = [
f"{i+1}. '{e['query']}' β†’ {e['answer'][:100]}…"
for i, e in enumerate(self.research_history)
]
return "**Research History**\n\n" + "\n".join(lines)

This pattern scales to any condition: feature flags, user permissions, external API health checks, or even time-based rules. By combining predicates with your tools, you build flexible, self-aware agents that only surface the right capabilities at the right moment.


πŸ’Ύ 5. Save History to a File​

Add a file-save tool:

@truffle.tool(
description="Save research history to a local file",
icon="doc.text.below.ecg",
predicate=_has_history
)
@truffle.args(filename="Filename (e.g., 'research_notes.txt')")
def save_history(self, filename: str) -> str:
content = self.view_history()
with open(filename, "w", encoding="utf-8") as f:
f.write(content)
self.client.tool_update(f"Saved history as {filename}")
return f"History saved to {filename}"

🧹 6. Organize Tools with Groups (Optional)​

Group related tools under a common heading:

@truffle.group("History Tools")
# Apply this decorator to view_history and save_history

βš™οΈ 7. Configure manifest.json​

Open manifest.json and update:

{
"example_prompts": [
"Research the latest AI breakthroughs",
"Show my previous research on renewable energy"
]
}

Good example prompts help the Agent automatically pick your app when users ask similar questions.


πŸš€ 8. Build & Deploy​

  1. Ensure requirements.txt lists truffle-sdk (and any other libs).

  2. Package your app:

    truffle build
  3. Upload to hardware or cloud:

    truffle upload

πŸŽ‰ 9. Try It Out​

Launch the Truffle Client, choose ResearchAssistant, and ask:

"What are recent advances in renewable energy?"

Your Agent will invoke your research tool, show live updates, and return a concise answer.