Metaphor Python API Client
Metaphor-python is a Python client library for interacting with the Metaphor API, a search engine optimized for Large Language Models (LLMs). It enables neural search and content retrieval, providing clean HTML content from search results. The library is currently at version 0.1.23 and is under active development, indicated by its 'Alpha' status on PyPI. While no explicit release cadence is documented, updates are released as new features and improvements to the Metaphor API are made available.
Common errors
-
metaphor_python.api.ApiException: (401) Reason: Unauthorized HTTP response body: b'{"detail":"Invalid API key"}'cause The Metaphor API key provided is either missing, incorrect, or expired.fixVerify that your `METAPHOR_API_KEY` environment variable holds the correct and active API key obtained from the Metaphor website. Re-initialize the `Metaphor` client after updating the key. -
AttributeError: 'Metaphor' object has no attribute 'some_non_existent_method'
cause Attempting to call a method or access an attribute that does not exist on the `Metaphor` client object or its response objects. This could be due to a typo or misunderstanding the available API methods.fixConsult the official Metaphor API documentation and the `metaphor-python` library's source or examples to ensure you are using the correct method names and arguments. The main methods are `search()`, `find_similar()`, and `get_contents()` (from the search results).
Warnings
- gotcha The Metaphor API key is crucial for authentication. Failing to provide a valid key will result in authentication errors when making API calls.
- gotcha The library is in an 'Alpha' development status (0.1.x), meaning its API might evolve rapidly, and breaking changes could occur in minor or patch releases without strict adherence to semantic versioning until a 1.0 release.
Install
-
pip install metaphor-python
Imports
- Metaphor
from metaphor_python import Metaphor
Quickstart
import os
from metaphor_python import Metaphor
# Ensure your Metaphor API key is set as an environment variable
# e.g., export METAPHOR_API_KEY="your_metaphor_api_key_here"
api_key = os.environ.get('METAPHOR_API_KEY')
if not api_key:
print("Error: METAPHOR_API_KEY environment variable not set.")
else:
try:
metaphor = Metaphor(api_key=api_key)
# Perform a search
results = metaphor.search("latest developments in AI agents", num_results=3, use_autoprompt=True)
if results.contents:
print("Search Results:")
for i, item in enumerate(results.contents):
print(f"---\nResult {i+1}:\nTitle: {item.title}\nURL: {item.url}\nExtract: {item.extract[:200]}...")
else:
print("No search results found.")
except Exception as e:
print(f"An error occurred: {e}")