Skip to content

Commit

Permalink
Merge pull request #136 from indexnetwork/sdk-fix
Browse files Browse the repository at this point in the history
Sdk fix
  • Loading branch information
serefyarar authored Jul 5, 2024
2 parents fa463cb + 89a00e7 commit 205ecc5
Show file tree
Hide file tree
Showing 10 changed files with 513 additions and 67 deletions.
25 changes: 22 additions & 3 deletions sdk/js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Quick start


Index is a discovery protocol that eliminates the need for intermediaries in finding knowledge, products, and like-minded people through direct, composable discovery across the web. As the first decentralized semantic index, it leverages Web3 and AI and offers an open layer for discovery.

You can either use the API directly or the client available. Here is a quick start to discover it.
Expand Down Expand Up @@ -39,7 +40,7 @@ const indexClient = new IndexClient({
});
```

For authentication, you need a `DIDSession`. You can either sign in using a wallet or pass an existing session. Check [Authentication](../api-reference/identity/authentication.md) for details explanation on how to initiate a session.
For authentication, you need a `DIDSession`. You can either sign in using a wallet or pass an existing session. Check [Authentication](https://docs.index.network/docs/api-reference/identity/authentication) for details explanation on how to initiate a session.

```typescript
await indexClient.authenticate();
Expand All @@ -51,15 +52,14 @@ We're almost ready. Now, let's create an Index, with a title.
const index = await indexClient.createIndex("Future of publishing");
```

Great, now you have a truly decentralized index to interact with! Though it's empty, which means we need to create and add an [`Item`](../api-reference/indexing/item.md) into it so we can interact. Let's do that.
Great, now you have a truly decentralized index to interact with! Though it's empty, which means we need to create and add an [`Item`](https://docs.index.network/docs/api-reference/indexing/index) into it so we can interact. Let's do that.

```typescript
const webPage = await indexClient.crawlWebPage("http://www.paulgraham.com/publishing.html");

await indexClient.addItemToIndex(index.id, webPage.id);
```


### Using Custom Schemas
If you want to use your own schema, you can do so by creating and deploying a custom model. Below are the methods and examples of how to use them.

Expand Down Expand Up @@ -108,6 +108,25 @@ After creating a custom model, use the deployModel method to deploy it.
await indexClient.deployModel(modelResponse.models[0]);
```

#### Using Your Model
To use it, create a node with your model and required data.

```typescript
const sampleNodeData = { } // Fill with your data

const createdNode = await indexClient.createNode(
modelResponse.models[0],
sampleNodeData,
);

const newIndex = await indexClient.createIndex("Index with your model");

const addedItem = await indexClient.addItemToIndex(
newIndex.id,
createdNode.id,
);
```

## Interact with your index
Your index is now ready for interaction! To start a conversation and interact with the data, follow these steps:

Expand Down
10 changes: 3 additions & 7 deletions sdk/js/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,11 +208,8 @@ export default class IndexClient {
});
}

public async createIndex(
title: string,
signerFunction?: string,
): ApiResponse<IIndex> {
const body = { title, signerFunction };
public async createIndex(title: string): ApiResponse<IIndex> {
const body = { title };
return this.request(`/indexes`, {
method: "POST",
body: JSON.stringify(body),
Expand Down Expand Up @@ -306,7 +303,7 @@ export default class IndexClient {
return this.request(`/model`, {
method: "POST",
body: JSON.stringify({
schema: graphQLSchema
schema: graphQLSchema,
}),
});
}
Expand Down Expand Up @@ -368,7 +365,6 @@ export default class IndexClient {
handleMessage: (data: any) => void,
handleError: (error: any) => void,
) {

const eventUrl = `${this.baseUrl}/conversations/${conversationId}/updates?session=${this.session}`;
const eventSource = new EventSource(eventUrl);

Expand Down
2 changes: 1 addition & 1 deletion sdk/python/.gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
venv
demo.py
build
dist
*.egg-info
.env
.pytest_cache
2 changes: 1 addition & 1 deletion sdk/python/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
include README.MD
recursive-include indexnetwork_sdk/bin *
recursive-include . *.bin
2 changes: 2 additions & 0 deletions sdk/python/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
test:
pytest
185 changes: 141 additions & 44 deletions sdk/python/README.MD
Original file line number Diff line number Diff line change
@@ -1,35 +1,29 @@
<h1 align="center">
<a href="https://index.network/#gh-light-mode-only">
<img style="width:400px" src="https://index.network/images/IndexNetworkLogo.png">
</a>
</h1>
<p align="center">
<i align="center">Discovery Protocol 🚀</i>
</p>


# Index Network Python SDK

Index is a discovery protocol that eliminates the need for intermediaries when finding knowledge, products, and like-minded people through direct, composable discovery across the web. By leveraging Web3 and AI, Index offers an open layer for discovery as the first decentralized semantic index. It functions as a composable vector database with a user-centric perspective, enabling interaction with decentralized graphs.
Index is a discovery protocol that eliminates the need for intermediaries in finding knowledge, products, and like-minded people through direct, composable discovery across the web. As the first decentralized semantic index, it leverages Web3 and AI and offers an open layer for discovery.

You can either use the API directly or the client available. Here is a quick start to discover it.


## Using the Index Network Python SDK

The Index Network offers a Python SDK to facilitate various operations on our platform. This guide will walk you through setting up the SDK, authenticating, creating an Index, and adding an Item to it and finally interacting with it.
The Index Network offers an SDK to facilitate various operations on the protocol. In this example, we'll demonstrate how to authenticate, create an Index, and add an Item to it.

> [**Index**](https://docs.index.network/docs/getting-started/data-models#index) is a fundamental component of the Index Network, designed to facilitate context management and enable semantic interoperability within your system. It serves as a structured way to organize and store data related to specific contexts.
> [**Item**](https://docs.index.network/docs/getting-started/data-models#indexitem) represents a graph node within an Index. It provides a standardized approach to representing and managing various types of data.
### Installation

First, install the indexnetwork-sdk package via pip:


```
```shell
pip install indexnetwork-sdk
```


Creating an Instance of IndexClient

```
```python
from indexclient import IndexClient

client = IndexClient(
Expand All @@ -38,64 +32,167 @@ client = IndexClient(
network="ethereum" # Specify the network you're working on
)
```
For authentication, you need a `DIDSession`. You can either sign in using a wallet or pass an existing session. Check [Authentication](https://docs.index.network/docs/api-reference/identity/authentication) for details explanation on how to initiate a session.

Authenticate it.

```
```python
client.authenticate()
```

### Creating an Index

We're ready. Now, let's create an Index with a title.
We're almost ready. Now, let's create an Index with a title.

```
```python
index_id = client.create_index("Future of publishing")
```

Voilà, now you have a truly decentralized index to interact with! Though it's empty, which means we need to create and add an Item into it so we can interact. Let's do that.
Great, now you have a truly decentralized index to interact with! Though it's empty, which means we need to create and add an [`Item`](https://docs.index.network/docs/api-reference/indexing/index) into it so we can interact. Let's do that.

```python
web_page = client.crawl_web_page("http://www.paulgraham.com/publishing.html")
client.add_item(index_id, web_page["id"])
```
web_page_id = client.crawl_web_page("http://www.paulgraham.com/publishing.html")
client.add_item_to_index(index_id, web_page_id)
````

### Using Custom Schemas
If you want to use your own schema, you can do so by creating and deploying a custom model. Below are the methods and examples of how to use them.

#### Creating a Custom Model
Use the createModel method to create a custom model using a GraphQL schema.

### Interacting with an Index
```python
graphQLSchema = """
type CustomObject {
title: String! @string(maxLength: 50)
}
Your index is now ready for interaction! Querying the index is straightforward:
type YourModel @createModel(accountRelation: LIST, description: "Full schema for models") {
id: ID!
booleanValue: Boolean!
intValue: Int!
floatValue: Float!
did: DID!
streamId: StreamID!
commitId: CommitID!
cid: CID!
chainId: ChainID!
accountId: AccountID!
uri: URI! @string(maxLength: 2000)
date: Date!
dateTime: DateTime!
time: Time!
localDate: LocalDate!
localTime: LocalTime!
timeZone: TimeZone!
utcOffset: UTCOffset!
duration: Duration!
stringValue: String! @string(maxLength: 10)
objectArray: [CustomObject!] @list(maxLength: 30)
singleObject: CustomObject
}
"""

model_response = index_client.create_model(graphQLSchema)
```
import uuid

chat_id = str(uuid.uuid4())
#### Deploying a Custom Model
After creating a custom model, use the deployModel method to deploy it.

messages = [
{
"content": "How do you evaluate a startup?",
"role": "user",
},
]
```python
index_client.deploy_model(model_response["models"][0]["id"])
```

response = client.chat(chat_id, messages, sources=[index_id])
#### Using Your Model
To use it, create a node with your model and required data.

print(response)
```python
sample_node_data = {} # Fill with your data

created_node = index_client.create_node(
model_response["models"][0]["id"],
sample_node_data
)

new_index = index_client.create_index("Index with your model")
added_item = index_client.add_item(new_index["id"], created_node["id"])
```

The response should look something like this:
## Interact with your index
Your index is now ready for interaction! To start a conversation and interact with the data, follow these steps:

```python
conversation_params = {
"sources": [index["id"]],
"summary": "Mock summary"
}
conversation = index_client.create_conversation(conversation_params)

message_params = {
"role": "user",
"content": "How do you do this?"
}
message = index_client.create_message(conversation["id"], message_params)

messages = index_client.get_conversation(conversation["id"])
print("Retrieved Messages:", messages)
```

The response should look something like this:
```python
{
"response": "This article discusses the intricacies and challenges of publishing ... strategies for successful online publishing."
"sources": [
{
"itemId": "kjzl6kcy...ii7z1anybovo",
"indexId": "rt38xm13...b2ca76w5ky27",
}
]
"id": "message-id",
"content": "How do you do this?",
"role": "user",
"createdAt": "timestamp"
}
```

### Listening to Conversation Updates

The Index Client SDK allows you to listen for updates to a conversation in real-time. This is useful for applications that need to react to new messages or changes in a conversation.

Here is an example of how you can use the `listen_to_index_updates` method to handle real-time updates in a conversation:

```python
conversation_id = "your-conversation-id"

def handle_message(data):
print("New message received:", data)

def handle_error(error):
print("Error receiving updates:", error)

index_client.listen_to_conversation_updates(
conversation_id=conversation_id,
handle_message=handle_message,
handle_error=handle_error
)
```

### Listening to Index Updates

The Index Client SDK allows you to listen for updates to miltiple indexes in real-time. This is useful for applications that need to react to new data events, using natural language.

Here is an example of how you can use the `listen_to_index_updates` method to handle real-time updates in a conversation:

```python
sources = ["did:pkh:eip155:1:0x1b9Aceb609a62bae0c0a9682A9268138Faff4F5f"]
query = "if it is relevant to decentralized AI"

def handle_message(data):
print("New event received:", data)

def handle_error(error):
print("Error receiving updates:", error)

index_client.listen_to_index_updates(
sources=sources,
query=query,
handle_message=handle_message,
handle_error=handle_error
)
```

### Additional Methods

#### Get All Indexes
Expand Down
Loading

0 comments on commit 205ecc5

Please sign in to comment.