Hi,
I've been thinking about Leo as a more general information management
tool for a while - I keep being surprised by how useful it is, after 21
years of using the tool.
For anyone that's interested, I thought about using ChatGPT to help
with scripting custom extensions to do jobs that might be useful, one of
which is calling the OpenAI api itself to work on nodes. The following
code is what it came up with and I've been finding it quite useful.
Cheers,
Karthik
import leo.core.leoGlobals as g
from openai import OpenAI
# client = OpenAI()
# Set your OpenAI API key
client = OpenAI(api_key = "<YOUR KEY HERE>")
def summarize_and_reformat(content):
"""
Sends the given content to OpenAI to summarize and reformat it
using the updated API.
"""
try:
# OpenAI API request
response = client.chat.completions.create(
model="gpt-4o-mini", # Use "gpt-3.5-turbo" or "gpt-4"
based on your access
messages=[
{"role": "system", "content": "You are a helpful
assistant. Summarize and reformat the text you are given."},
{"role": "user", "content": content},
],
temperature=0.7,
max_tokens=2000, # Adjust as needed
)
# Extract and return the response
message = response.choices[0].message.content
g.es(f"Response from openai: {message}")
return message
except Exception as e:
g.es(f"Error while interacting with OpenAI: {e}", color="red")
return None
def process_node_with_openai(c, p):
"""
Summarizes and reformats the content of the current node and
creates a new sub-node with the result.
"""
# Get the current node's content
content = p.b.strip()
if not content:
g.es("The node is empty. Nothing to summarize.", color="red")
return
#
g.es(f"(content in the pane: {content}")
g.es("Sending content to OpenAI for summarization and
reformatting...", color="blue")
# Call the OpenAI function
summarized_content = summarize_and_reformat(content)
if summarized_content:
# Create a new sub-node with the summarized content
new_node = p.insertAsLastChild()
new_node.h = "Summarized and Reformatted Content"
new_node.b = summarized_content
g.es("New sub-node created with summarized and reformatted
text.", color="green")
else:
g.es("Failed to create sub-node. See error logs for details.",
color="red")
# Add the command to the Leo editor
def add_openai_command(c):
command_name = 'summarize-and-reformat'
c.k.registerCommand(command_name, lambda event:
process_node_with_openai(c, c.p))
g.es(f"Command '{command_name}' added to Leo.", color="green")
g.plugin_signon(__name__)
add_openai_command(c)