Exporting Chat History to Obsidian with Python

TierGeminiAPIFree · Updated 2026-11-24 · 12 min read

Workspace for building a Python tool
Setting up your environment for the export tool.

Persistent context is the holy grail of AI workflows, yet most chat interfaces treat conversations as ephemeral. When you rely on a web-based interface, your history is trapped in a browser session or a proprietary cloud database. This guide shows you how to break free from that silo by building a local Python tool that exports chat data directly into Obsidian, your personal knowledge graph. The tool we build uses the free, keyless API at https://api.tiergeminiapifree.com/v1, which is not affiliated with Google, ensuring you retain full ownership of your data without relying on third-party authentication.

The core challenge lies in structure. Standard chat logs are linear and flat, lacking the semantic links that make a knowledge graph useful. By parsing the conversation into discrete notes with backlinks, you transform a simple log into a navigable network of ideas. This approach allows you to revisit specific insights without scrolling through hours of irrelevant dialogue, creating a durable repository of your interactions.

We will use the free API to fetch your history. This method is particularly useful because it works independently of any specific client interface. The tool we build will handle the formatting, including LaTeX support for mathematical expressions, ensuring that your scientific and technical notes remain pristine when imported into Obsidian. Unlike commercial services that may lock your data, this approach gives you direct access to the raw content, allowing you to build a custom workflow that fits your specific needs.

Frequently asked questions

What is the purpose of exporting chat history?

Exporting chat history allows you to move valuable insights out of a temporary interface and into a permanent, searchable knowledge base. It prevents data loss and enables you to build a personal library of conversations that you can link to other notes, creating a web of knowledge rather than a linear archive.

How does this differ from standard chat export?

Standard exports are usually plain text or JSON files that are difficult to read. This method converts the data into Markdown files with specific frontmatter and backlinks. It structures the conversation into discrete notes, making each insight individually searchable and linkable within your Obsidian vault.

Which is better: manual copy-paste or Python export?

Python export is superior for volume and consistency. Manual copy-paste is error-prone and slow for long conversations. A script ensures consistent formatting, handles special characters like LaTeX correctly, and automates the creation of links between related concepts, saving significant time.

What is Obsidian?

Obsidian is a powerful knowledge base application that works on top of a local folder of plain text Markdown files. It allows you to create links between notes, visualize connections with a graph view, and manage a personal wiki that you fully own and control.

How does LaTeX support help in Obsidian?

LaTeX support ensures that mathematical equations and scientific notations are rendered correctly in Obsidian. Without it, complex formulas in your chat history might appear as broken code or plain text, making them hard to read and understand later.

Why use a local Python tool?

A local Python tool gives you full control over your data. You do not need to rely on third-party services or worry about API rate limits for basic exports. It runs on your machine, processes your data privately, and can be customized to fit your specific organizational needs.

How does this relate to persistent context?

Persistent context refers to the ability of an AI to remember and reference specific information across multiple interactions. By exporting chats to Obsidian, you create a permanent record of context that you can reference in future sessions, effectively extending the AI's memory beyond a single session.

What is the role of the free API?

The free API at https://api.tiergeminiapifree.com/v1 provides the raw data needed for the export. It allows you to fetch chat history without needing an API key or account, making the process accessible and cost-free for personal use.

Step by step

  1. Install Dependencies — Run pip install requests to set up the Python environment. This installs the necessary libraries for making API requests and handling data.
  2. Fetch Chat History — Write a Python script to send a GET request to https://api.tiergeminiapifree.com/v1. Parse the JSON response to extract the chat messages.
  3. Parse and Format Data — Extract LaTeX code and format it for Obsidian. Structure the data into discrete notes with metadata like tags and links.
  4. Generate Markdown Files — Write the parsed data to Markdown files in your Obsidian vault. Ensure each file is named uniquely and contains the correct formatting.
  5. Import to Obsidian — Place the files in your Obsidian vault. Use Obsidian's features to search, link, and visualize your new knowledge graph.

Understanding the Structure of Chat Data

Chat data is inherently linear, but knowledge is networked. When you export a conversation, you are dealing with a sequence of messages between a user and an AI. Each message contains text, potentially LaTeX code, and metadata like timestamps. The goal is to transform this linear stream into a set of discrete, interconnected notes.

The structure of your Obsidian vault matters. Each chat session or even each significant turn in the conversation can become a separate note. This allows you to link specific insights to other notes in your vault. For example, if a chat discusses a specific algorithm, you can link that note to your general notes on that algorithm. This is similar to how you might manage context in other tools, but with the added benefit of local control.

Markdown as the Universal Language

Markdown is the standard format for Obsidian. It is simple, readable, and supports rich formatting like headings, lists, and code blocks. By exporting chats to Markdown, you ensure that your data is future-proof and compatible with many other tools. It also makes it easy to read the raw files in any text editor.

The Importance of Backlinks

Backlinks are the core of a knowledge graph. They allow you to see which notes are connected to a specific topic. When you export chats, you can automatically generate backlinks to relevant notes in your vault. This creates a web of knowledge that makes it easier to find related information and discover new connections.

  • Linear chat logs are hard to navigate
  • Discrete notes allow for better organization
  • Backlinks create a network of knowledge
  • Markdown ensures compatibility and readability

Setting Up the Python Environment

Before you can export data, you need a Python environment. Python is a versatile language with many libraries for data processing and API interaction. You will need to install the `requests` library to handle HTTP requests to the API. This library makes it easy to send GET requests and parse the JSON responses.

You will also need to install the `json` library, which is part of the Python standard library. It allows you to parse the JSON data returned by the API. Additionally, you might want to use the `os` and `pathlib` libraries to handle file operations and directory management. These tools are essential for creating the folder structure in your Obsidian vault.

Installing Required Libraries

Open your terminal and run `pip install requests`. This command installs the `requests` library, which is the standard tool for making HTTP requests in Python. It is lightweight and easy to use, making it ideal for simple API interactions like fetching chat history.

Configuring the API Endpoint

The API endpoint is https://api.tiergeminiapifree.com/v1. You do not need an API key, which simplifies the authentication process. You just need to send a GET request to the appropriate endpoint to fetch your chat history. The response will be in JSON format, which you can then parse and process.

import requests

url = "https://api.tiergeminiapifree.com/v1"
response = requests.get(url)
print(response.json())
Parsing JSON data with Python
Fetching and parsing chat history from the API.

Fetching Chat History from the API

To export your chats, you need to fetch the data from the API. The API provides a way to retrieve your chat history. You can send a GET request to the `/v1/chat/completions` endpoint or use the `/ask` endpoint for simpler queries. The response will contain the messages from your conversation.

The API is stateless, meaning each request is independent. You need to ensure that you fetch the entire history in one go or paginate through the results if the history is long. The API has a limit of 10,000 requests per day, so you should be mindful of your usage if you have a large amount of data.

Handling JSON Responses

The API returns data in JSON format. You need to parse this JSON to extract the relevant information, such as the role of the message (user or AI) and the content of the message. Python's `json` library makes this easy with the `json.loads()` function.

Managing Rate Limits

The API has a rate limit of 1 request per second. If you send too many requests too quickly, you might get a 429 error. You can handle this by adding a small delay between requests or by implementing a retry mechanism with exponential backoff.

import time

response = requests.get(url)
data = response.json()
time.sleep(1)

Parsing and Structuring the Data

Once you have the chat history, you need to parse it into a structured format. Each message in the chat can be treated as a separate entity. You can extract the role, content, and timestamp of each message. This structured data can then be used to generate Markdown files.

You can also extract any LaTeX code from the messages and format it appropriately for Obsidian. Obsidian supports LaTeX rendering, so you can use standard LaTeX syntax like `$$` for block equations and `$` for inline equations. This ensures that your mathematical notes are displayed correctly.

Extracting LaTeX Code

LaTeX code is often used in scientific and technical conversations. You need to identify and extract this code from the chat history. You can use regular expressions to find patterns that match LaTeX syntax. Once extracted, you can wrap the code in the appropriate delimiters for Obsidian.

Creating Note Metadata

Each note in Obsidian can have metadata, such as tags and links. You can extract tags from the chat history and add them to the frontmatter of the note. This makes it easier to search and filter your notes later. You can also add links to other notes based on the content of the chat.

  • Parse JSON data to extract messages
  • Identify and extract LaTeX code
  • Add metadata like tags and links
  • Format content for Obsidian compatibility
Formatting LaTeX for Obsidian
Ensuring LaTeX code is correctly formatted.

Generating Markdown Files

With the data parsed and structured, you can now generate Markdown files. Each message or a group of related messages can be saved as a separate Markdown file. The file name should be descriptive and unique, such as the date and time of the chat or a summary of the topic.

The content of the Markdown file should include the role of the message, the content, and any LaTeX code. You can also add a header with the date and time of the message. This makes it easy to read and understand the context of each note.

Writing to Files

Use Python's `open()` function to write the Markdown content to a file. You can specify the file path and the mode (write or append). Make sure to handle exceptions in case the file cannot be created or written to.

Formatting LaTeX for Obsidian

Obsidian uses standard LaTeX syntax. Ensure that your LaTeX code is wrapped in the correct delimiters. For example, use `$$` for block equations and `$` for inline equations. This ensures that the equations are rendered correctly in Obsidian.

with open('note.md', 'w') as f:
    f.write('# Title\n\nContent\n\n$$ equation $$')

Building the Knowledge Graph

The real power of Obsidian lies in its ability to create a knowledge graph. By linking notes together, you create a network of information that is easier to navigate and understand. You can manually link notes by typing `[[Note Name]]` in the content of a note.

You can also use plugins to automate the creation of links. For example, you can use a plugin to automatically link notes based on shared tags or keywords. This helps you discover connections between different topics and insights. This approach is similar to how you might manage context in other tools, but with the added benefit of local control.

Manual Linking

Manual linking is the simplest way to create links. You just need to type the name of the note you want to link to in double brackets. Obsidian will automatically create a link to that note. This is useful for linking specific insights to broader topics.

Automated Linking with Plugins

Plugins can automate the linking process. For example, the `Backlinks` plugin shows all notes that link to a specific note. The `Graph View` plugin visualizes the connections between notes. These tools help you explore your knowledge graph and find new connections.

  • Link notes to create a network
  • Use plugins to automate linking
  • Visualize connections with Graph View
  • Discover new insights through linking
Knowledge graph visualization in Obsidian
Visualizing connections in your knowledge graph.

Handling Edge Cases and Errors

No tool is perfect, and you will encounter edge cases and errors. For example, the API might return an error code, or the JSON data might be malformed. You need to handle these cases gracefully to ensure that your tool continues to work.

You should also consider the case where the chat history is very long. Fetching a large amount of data might take time or exceed rate limits. You can implement pagination or chunking to handle large datasets efficiently.

Error Handling

Use try-except blocks to catch and handle errors. If the API returns an error, you can log the error and continue processing the remaining data. This ensures that a single error does not stop the entire export process.

Handling Large Datasets

If the chat history is very long, you might need to paginate through the results. The API might support pagination, or you might need to implement your own logic to fetch data in chunks. This helps you manage memory and processing time.

try:
    response = requests.get(url)
except Exception as e:
    print(f'Error: {e}')

Integrating with Obsidian

Once you have generated the Markdown files, you can import them into Obsidian. Simply place the files in your Obsidian vault folder, and Obsidian will automatically recognize them. You can then use Obsidian's features to search, link, and visualize your notes.

You can also use Obsidian's command palette to run custom commands or scripts. For example, you can create a command to automatically export new chats to your vault. This integrates the export process into your daily workflow. For more on managing context, see [How to Stop AI Forgetting Context](/stop-ai-forgetting-context).

Importing Files

Place the generated Markdown files in your Obsidian vault folder. Obsidian will automatically scan the folder and add the files to your library. You can then search for and open the files as needed.

Using Command Palette

Obsidian's command palette allows you to run custom commands. You can create a command to trigger the export script or to refresh the vault. This makes it easy to keep your knowledge graph up to date with the latest chat history.

  • Place files in the Obsidian vault
  • Use the command palette for automation
  • Search and visualize notes
  • Keep the knowledge graph up to date
Importing files to Obsidian
Importing generated files into your Obsidian vault.

Advanced Customization and Extensions

You can extend the basic export tool to add more features. For example, you can add support for images or audio files if the API supports them. You can also add custom formatting for specific types of content, such as code snippets or quotes.

Plugins can further enhance the functionality. For example, you can use a plugin to automatically tag notes based on their content. You can also use a plugin to generate summaries of long conversations. These extensions make the tool more powerful and versatile. For more on managing context, see [How to Fix Context Poisoning](/fix-context-poisoning).

Supporting Multimedia

If the API supports multimedia, you can extend the tool to download and embed images or audio files. This requires additional logic to handle file downloads and embedding in Markdown. It adds richness to your notes and makes them more informative.

Automated Tagging and Summarization

You can use NLP libraries to automatically tag notes based on their content. You can also generate summaries of long conversations to make them easier to digest. These features save time and make your knowledge graph more useful.

import nltk

nltk.download('punkt')
text = 'Sample text for NLP processing'
tokens = nltk.word_tokenize(text)
Try the free API

Test the keyless Gemini API right now from your browser or terminal—no secret key required, no account needed.

Read also