Skip to content

Commit

Permalink
feat(docs): added guide for ai engine python sdk (#829)
Browse files Browse the repository at this point in the history
Co-authored-by: Joshua Croft <[email protected]>
  • Loading branch information
gautamgambhir97 and devjsc authored Aug 12, 2024
1 parent 8e2876a commit b52c164
Show file tree
Hide file tree
Showing 2 changed files with 280 additions and 0 deletions.
4 changes: 4 additions & 0 deletions pages/guides/ai-engine-sdk/_meta.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
{
"python": {
"title": "AI Engine Python SDK",
"tags": ["AI-Engine SDK", "Agentverse", "Functions", "DeltaV"]
},
"javascript": {
"title": "AI Engine Javascript SDK",
"tags": ["AI-Engine SDK", "Agentverse", "Functions", "DeltaV"]
Expand Down
276 changes: 276 additions & 0 deletions pages/guides/ai-engine-sdk/python.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,276 @@
import { Callout } from 'nextra/components'


# AI-Engine Python SDk

## Introduction

AI Engine SDK provides an easy-to-use interface for integrating advanced AI functionalities into your applications. With a simple API and comprehensive documentation, developers can effortlessly leverage powerful AI tools and enhance their projects.

## Getting Started

### Prerequisites
Before you begin, ensure you have met the following requirements:
- **Python 3.10 or higher** installed on your system.
- A valid **Agentverse API key**. You can obtain this from [Agentverse ↗️](https://agentverse.ai/).

<Callout type="info" emoji="ℹ️">
To find out how to generate an API KEY check out the documentation regarding [Agentverse API keys ↗️](https://fetch.ai/docs/guides/apis/agent-function-creation-apis).
</Callout>

### Installation
You can install the AI Engine SDK using either Poetry or pip. Follow the commands below.

```bash copy
poetry add ai-engine-sdk
pip install ai-engine-sdk
```

<Callout type="info" emoji="ℹ️">
Explore the additional resources we have on AI Engine compatible Agents:
- [Make your agents AI Engine compatible ↗️](/guides/agents/intermediate/ai-engine-compatible-agent)
- [Agent Functions ↗️](/guides/agents/intermediate/agent-functions)
- [Register Agent Functions ↗️](/guides/agentverse/agentverse-functions/registering-agent-services)
- [DeltaV ↗️](/concepts/ai-engine/deltav)
</Callout>


## SDK overview

### Creating the AI Engine client object

To set up and initialize the AiEngine client with your API key, use the following code snippet. This client will allow you to interact with the AI Engine API, enabling you to start sessions, get function groups, and manage messages.

```py copy
from ai_engine_sdk import AiEngine
ai_engine: AiEngine = AiEngine(api_key)
```

### Querying Function Groups in AI Engine SDK

```py copy
function_groups: list[FunctionGroup] = await ai_engine.get_function_groups()

public_group = next(
(g for g in function_groups if g.name == "Fetch Verified"),
None
)
```

If you would like to use the functions in your own My Functions function group instead then you can use this filter instead:

```py copy
my_group = next(
(g for g in function_groups if g.name == "My Functions"),
None
)
```

### Creating a session with the AI Engine.

This code starts a session with the AI Engine using the UUID of the selected function group.

```py copy
session = await ai_engine.create_session(function_group=public_group.uuid)
```

### Starting the conversation with an arbitrary objective

```py copy
await session.start(objective)
```

### Querying new messages

This line asynchronously queries the AI engine to retrieve a list of messages related to the current session. The messages are returned as a list of `ApiBaseMessage` objects, which can include various types of messages such as agent messages, AI engine messages, task selections, confirmations, and session stop messages. These messages are then processed to determine the next actions in the session workflow.

```py copy
while True:
messages: list[ApiBaseMessage] = await session.get_messages()
sleep(4)
```

## Handling Different Types of Messages


#### Task Selection Message (`is_task_selection_message`)

This message is generated when the AI engine suggests functions based on the initial objective or provides multiple options for a function.


#### Agent Message (`is_agent_message`)

This is a regular question from the AI Engine that the user needs to reply to with a string.

#### AI Engine Message (`is_ai_engine_message`)

This message type doesn't require a user response; it simply notifies the user about something.

#### Confirmation Message (`is_confirmation_message`)

This message is sent when the AI Engine has gathered all necessary inputs for the agent's function, indicating that the context is complete.

#### Stop Message (`is_stop_message`)

This message is sent when the session has ended, and the AI Engine no longer expects any replies from the user.


<Callout type="info" emoji="ℹ️">
All message types (expect for the AI engine message and stop message) expects a response from the user.
</Callout>


## SDK Methods for Replying

### Task Selection Message

Use `session.submit_task_selection`.

### Agent Message

Use `session.submit_response`.

### Confirmation Message

Use either `session.submit_confirmation` to confirm, or `session.reject_confirmation` to reject the context generated by the AI engine.



## Deleting session

After finishing a conversation with the AI Engine, you can delete the session by using the following command.

```py copy
await session.delete()
```


## Example Usage of the SDK

The following example demonstrates how to use the AI Engine SDK to interact with the AI Engine. The script sets up the client, queries function groups, creates a session, and handles different types of messages in a loop.

```py copy filename="run_example.py"
import asyncio
import logging
import os
import sys
from time import sleep
from ai_engine_sdk import (
AiEngine,
is_agent_message,
is_ai_engine_message,
is_confirmation_message,
is_stop_message,
is_task_selection_message, TaskSelectionMessage
)
from ai_engine_sdk import ApiBaseMessage, FunctionGroup

logger = logging.getLogger(__name__)

api_key = os.getenv("AV_API_KEY", "")
interaction_user_prompt_header = f"\n\n🤖 Interaction time"


async def main():
logger.debug("🚀 Starting example execution")
ai_engine = AiEngine(api_key)

function_groups: list[FunctionGroup] = await ai_engine.get_function_groups()

public_group = next((g for g in function_groups if g.name == "Fetch Verified"), None)
if public_group is None:
raise Exception('Could not find "Public" function group.')

session = await ai_engine.create_session(function_group=public_group.uuid)
default_objective: str = "Find a flight to warsaw."

logger.info(interaction_user_prompt_header)
objective = input(f"\n🎯 What is your objective [default: {default_objective}]: ") or default_objective
await session.start(objective)

try:
empty_count = 0
session_ended = False

while empty_count < 100:
messages: list[ApiBaseMessage] = await session.get_messages()
if len(messages) == 0:
empty_count += 1
else:
empty_count = 0

message: ApiBaseMessage
for message in messages:
if is_task_selection_message(message_type=message.type):
task_selection_message: TaskSelectionMessage = message

logger.info(interaction_user_prompt_header)
print("Please select a key from the list below:\n")
for _, option in task_selection_message.options.items():
print(f"➡ 🔑 {option.key} -> 🧰 {option.title}")
option_key = str(input("\nEnter task key: "))

# check the index
if option_key not in task_selection_message.options.keys():
raise Exception(f"🔴 Invalid task number.\n You selected: {option_key}")
logger.debug(option_key)
await session.submit_task_selection(
message,
[task_selection_message.options[option_key]]
)
del task_selection_message
elif is_agent_message(message):
logger.info(interaction_user_prompt_header)
print(message.text.capitalize())
response = input("✍ (enter to skip): ")
if response == "exit":
break

if response != "":
await session.submit_response(message, response)
elif is_ai_engine_message(message):
logger.info(f"\n 🤖 ℹ Informative message \n\n ---> ✨{message.text}")
sleep(3.5)
elif is_confirmation_message(message_type=message.type):
logger.info(interaction_user_prompt_header)
print("Confirm:", message.payload)
response = input("\nPress enter to confirm, otherwise explain issue:\n")

if response == "":
await session.submit_confirmation(message)
else:
await session.reject_confirmation(message, response)
elif is_stop_message(message):

logger.info("\n 👋 Session has ended, thanks! ")
session_ended = True
break

# if the session has concluded then break
if session_ended:
break

logger.info(f"\n🤖 Processing\n")
sleep(1.5)
logger.debug(f"No messages: {empty_count} times in a row")

except Exception as e:
logger.debug(f"Unhandled exception: {e}")
print("Error", e)
raise e
finally:
# clean up the session
await session.delete()


if __name__ == "__main__":
logging.basicConfig(
stream=sys.stdout,
level=logging.DEBUG,
# level=logging.INFO,
format='%(asctime)s %(levelname)s %(module)s: %(message)s',
datefmt="%H:%M:%S"
)
asyncio.run(main())
```

0 comments on commit b52c164

Please sign in to comment.