# Connect and organize concepts for smarter AI

The Knowledge Graph establishes semantic and hierarchical relationships between your concepts — such as synonyms, hyponyms, and hypernyms — laying the foundation for more intelligent, context-aware systems.

These relationships are crucial for building robust knowledge representations that enhance both computer vision and natural language processing capabilities.

Whether you're managing a product catalog, powering a search engine, or organizing complex datasets, using concept relationships allows you to structure, search, and retrieve information more effectively — making your AI applications significantly smarter and more precise.

## Types of Concepts Relations

- **Hyponym** — This represents an _“is a kind of”_ relationship. For instance, if you define the relationship as _'honey' (subject), 'hyponym' (predicate), 'food' (object),_ it can be interpreted as _"honey is a kind of food."_ This helps systems understand that "honey" belongs to a broader category.

- **Hypernym** — This is the inverse of a hyponym, signifying a _“parent of”_ relationship. Using the same example, if you define _'food' (subject), 'hypernym' (predicate), 'honey' (object),_ it is read as _"food is a parent of honey."_ When a hyponym is defined, the corresponding hypernym is automatically inferred in queries, and vice versa, ensuring consistency in how concept hierarchies are interpreted.

- **Synonym** — This relationship connects two concepts that essentially mean the same thing, similar to an _“is”_ statement. For example, defining _'puppy' as a synonym of 'pup'_ allows the model to treat them interchangeably. This relationship is bidirectional, so adding one synonym automatically implies the reverse, making searches and classifications more flexible and inclusive.

## Use Case Examples

- **Enhanced search and retrieval** — Concept relationships enable more intelligent searches. For example, a search for “Animal” can automatically include related hyponyms like “Dog” and “Cat,” returning broader and more relevant results.

- **Improved data organization** — Hierarchical relationships help structure complex datasets more effectively. For example, hypernyms allow models to group specific entities under broader categories, improving organizational structures.

- **Contextual understanding** — When models grasp the semantic links between concepts, they can better interpret context. For instance, recognizing that “Puppy” is a synonym of “Dog” ensures all relevant information is considered during classification or prediction.

- **Dynamic content delivery** — In use cases like personalized content, search recommendations, or targeted advertising, concept relationships allow systems to infer user intent and deliver more relevant, meaningful results.

## How to Create Relations

To create a relation between two concepts, you first have to create them in your app. Each relation should have a specified predicate, which can be _hyponym_, _hypernym_, or _synonym_.

Below is an example of how to create a relation between two concepts.

```python
import os
from clarifai.client.app import App

# Set your Personal Access Token (PAT)
os.environ["CLARIFAI_PAT"] = "YOUR_PAT_HERE"

app = App(user_id="YOUR_USER_ID_HERE", app_id="YOUR_APP_ID_HERE")

# A hyponym relation between "cat" and "animal", indicating that "cat" is a kind of "animal"
# A synonym relation between "cat" and "kitten", suggests that these two concepts are essentially the same
app.create_concept_relations("cat", ["animal", "kitten"], ["hyponym", "synonym"])
```

```python
###################################################################################
# In this section, we set the user authentication, app ID, subject concept ID,
# object concept ID, and predicate. Change these strings to run your own example.
###################################################################################

USER_ID = 'YOUR_USER_ID_HERE'
# Your PAT (Personal Access Token) can be found in the Account's Security section
PAT = 'YOUR_PAT_HERE'
APP_ID = 'YOUR_APP_ID_HERE'
# Change these to whatever relations you want to create
SUBJECT_CONCEPT_ID = 'honey'
OBJECT_CONCEPT_ID = 'food'
PREDICATE = "hypernym" # This can be hypernym, hyponym, or synonym

##########################################################################
# YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
##########################################################################

from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel
from clarifai_grpc.grpc.api import resources_pb2, service_pb2, service_pb2_grpc
from clarifai_grpc.grpc.api.status import status_code_pb2

channel = ClarifaiChannel.get_grpc_channel()
stub = service_pb2_grpc.V2Stub(channel)

metadata = (('authorization', 'Key ' + PAT),)

post_concept_relation_response = stub.PostConceptRelations(
    service_pb2.PostConceptRelationsRequest(
        user_app_id=resources_pb2.UserAppIDSet(
            user_id=USER_ID,
            app_id=APP_ID
        ),
        concept_id=SUBJECT_CONCEPT_ID,
        concept_relations=[
            resources_pb2.ConceptRelation(
                object_concept=resources_pb2.Concept(id=OBJECT_CONCEPT_ID),
                predicate=PREDICATE
            )
        ]
    ),
    metadata=metadata
)

if post_concept_relation_response.status.code != status_code_pb2.SUCCESS:
    print(post_concept_relation_response.status)
    raise Exception("Post concept relation failed, status: " + post_concept_relation_response.status.description)

print(post_concept_relation_response)
```

## List Existing Relations

### List All Relations

Below is an example of how to list all the existing relations between concepts.

```python
import os
from clarifai.client.app import App

# Set your Personal Access Token (PAT)
os.environ["CLARIFAI_PAT"] = "YOUR_PAT_HERE"

app = App(user_id="YOUR_USER_ID_HERE", app_id="YOUR_APP_ID_HERE")

concept_relations = list(app.search_concept_relations())

for relation in concept_relations:
    print("Subject_concept:", relation.subject_concept.id)
    print('\t' "Object_concept:", relation.object_concept.id)
    print('\t' "Predicate:", relation.predicate, '\n')
```

### Delete Relations

Below is an example of how to delete relations between concepts.

```python
###################################################################################
# In this section, we set the user authentication, app ID, object concept ID, and
# concept relation IDs. Change these strings to run your own example.
####################################################################################

USER_ID = 'YOUR_USER_ID_HERE'
# Your PAT (Personal Access Token) can be found in the Account's Security section
PAT = 'YOUR_PAT_HERE'
APP_ID = 'YOUR_APP_ID_HERE'
# Change these to whatever relations you want to delete
OBJECT_CONCEPT_ID = 'YOUR_OBJECT_CONCEPT_ID_HERE'
CONCEPT_RELATION_IDS = ['0d9b0acb10fb4dac9a9d60a149d8fc5c','f5acf9c2a76143d78daf5f984693c52c']

channel = ClarifaiChannel.get_grpc_channel()
stub = service_pb2_grpc.V2Stub(channel)

metadata = (('authorization', 'Key ' + PAT),)

delete_concept_relation_response = stub.DeleteConceptRelations(
    service_pb2.DeleteConceptRelationsRequest(
        user_app_id=resources_pb2.UserAppIDSet(
            user_id=USER_ID,
            app_id=APP_ID
        ),
        concept_id=OBJECT_CONCEPT_ID,
        ids=CONCEPT_RELATION_IDS
    ),
    metadata=metadata
)

if delete_concept_relation_response.status.code != status_code_pb2.SUCCESS:
    print(delete_concept_relation_response.status)
    raise Exception("Delete concept relation failed, status: " + delete_concept_relation_response.status.description)
```

### Conclusion

Build your next AI app, test and tune popular LLMs models, and much more.
