Querying Golden's Knowledge Graph with LangChain's GoldenQueryAPIWrapper

Posted: Nov 22, 2024.

Golden provides a powerful knowledge graph that can be queried using natural language. In this guide, we'll explore how to use LangChain's GoldenQueryAPIWrapper to programmatically access Golden's Query API and retrieve structured data.

What is GoldenQueryAPIWrapper?

GoldenQueryAPIWrapper is a LangChain utility class that provides a simple interface to Golden's Query API. It allows you to make natural language queries to Golden's knowledge graph and retrieve structured information about various entities like companies, products, people, and more.

This wrapper is particularly useful when you need to:

  • Get information about companies in specific industries
  • Find products from particular companies
  • Research funding information about startups
  • Discover relationships between different entities

Reference

MethodDescription
__init__(golden_api_key: str = None)Initialize the wrapper with your Golden API key. If not provided, it will look for the GOLDEN_API_KEY environment variable
run(query: str) -> strExecute a natural language query and return the results as a JSON string

How to Use GoldenQueryAPIWrapper

Setup and Installation

Before using the wrapper, you'll need to:

  1. Sign up for a Golden account at golden.com
  2. Get your API key from Golden API Settings
  3. Set up your environment:
import os
os.environ["GOLDEN_API_KEY"] = "your-api-key-here"

Basic Usage

Here's how to make simple queries using the wrapper:

from langchain_community.utilities.golden_query import GoldenQueryAPIWrapper
import json

# Initialize the wrapper
golden_query = GoldenQueryAPIWrapper()

# Make a query and parse the results
response = golden_query.run("companies in nanotech")
results = json.loads(response)

# Print formatted results
for company in results['results']:
    name = company['properties'][0]['instances'][0]['value']
    print(f"Company: {name}")

This will return a list of companies in the nanotech industry, with their basic information.

Advanced Queries

The wrapper supports various types of natural language queries. Here are some examples:

# Query for specific company products
products = golden_query.run("Products from OpenAI")

# Find companies with specific funding criteria
startups = golden_query.run("Generative AI companies with series a funding")

# Research people in specific categories
investors = golden_query.run("rappers who invest")

# All responses are returned as JSON strings that can be parsed
results = json.loads(products)  # Convert to Python dictionary

Working with Results

The API returns structured data that includes various properties about the entities. Here's how to process more complex results:

def process_golden_results(query_text):
    golden_query = GoldenQueryAPIWrapper()
    response = json.loads(golden_query.run(query_text))
    
    processed_results = []
    for item in response['results']:
        entity = {
            'id': item['id'],
            'version': item['latestVersionId']
        }
        
        # Extract properties
        for prop in item['properties']:
            if prop['predicateId'] == 'name':
                entity['name'] = prop['instances'][0]['value']
        
        processed_results.append(entity)
    
    return processed_results

# Use the function
results = process_golden_results("AI companies in healthcare")
for result in results:
    print(f"Company ID: {result['id']}, Name: {result['name']}")

Error Handling

Since the API requires authentication and may have rate limits, it's good practice to add error handling:

from typing import Dict, Any
import json

def safe_golden_query(query: str) -> Dict[str, Any]:
    try:
        golden_query = GoldenQueryAPIWrapper()
        response = golden_query.run(query)
        return json.loads(response)
    except ValueError as e:
        print(f"Error parsing JSON response: {e}")
        return {}
    except Exception as e:
        print(f"Error making Golden API request: {e}")
        return {}

# Use with error handling
results = safe_golden_query("companies in quantum computing")

The GoldenQueryAPIWrapper provides a powerful way to access structured data from Golden's knowledge graph. By combining it with proper error handling and result processing, you can build robust applications that leverage this vast knowledge base.

An alternative to LangSmith

Open-source LangChain monitoring, prompt management, and magic. Get started in 2 minutes.

LangChain Docs

Join 10,000+ subscribers

Every 2 weeks, latest model releases and industry news.

An alternative to LangSmith

Open-source LangChain monitoring, prompt management, and magic. Get started in 2 minutes.

LangChain Docs