Skip to content

Commit

Permalink
add chef service integration (#246)
Browse files Browse the repository at this point in the history
Co-authored-by: pratrivedi <[email protected]>
  • Loading branch information
pratrivedi and pratrivedi authored Mar 13, 2024
1 parent 7c567b1 commit bdcad46
Show file tree
Hide file tree
Showing 4 changed files with 143 additions and 0 deletions.
59 changes: 59 additions & 0 deletions integrations/recipe-finder/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Recipe Finder Integration

## Overview
Recipe Finder integration enhances the capabilities of an AI agent by leveraging OpenAI. This integration allows the AI agent to generate number of recipes, providing users with recipes based on the list of ingredients they have.


## Recipe Finder
**Recipe Finder** is a real-time, high-scale recipe generator based on list of ingredients user have readily available.

## Usage
To use the Recipe Finder integration, create an instance of the `RecipeSearch` model with a specific list of ingredients and send it to the agent. The agent will utilize the OpenAI API to generate list of recipes with requested ingredients and respond with formatted results.

# Getting OpenAI API Key

To access the OpenAI API, you need an API key. Follow these steps to obtain your API key:

1. Visit the OpenAI website at [https://platform.openai.com/](https://platform.openai.com/).
2. Sign up or log in to your account.
3. Navigate to the View API Keys under Profile section.
4. Create a new secret key.
5. Copy the generated API key.
6. Replace the placeholder in the script with your actual API key.

Ensure that you keep your API key secure and do not share it publicly. It is a sensitive credential that grants access to Rainforest services.

# Agent Secrets on Agentverse

1. Go to the Agentverse platform.
2. Navigate to the Agent Secrets section.
3. Create an agent and copy the code in it
4. Add a new secret with the key `API_KEY` and the value as your API KEY.

# Steps to Enroll an Agent as a Service on Agentverse

You can integrate into DeltaV your Agents created on your local computer, IoT devices, in the VMs, or agents created on Agentverse. The steps are the same.

Once your agents are run, the agent protocol manifests are uploaded to the Almanac contract in the form of protocol digests. After uploading the manifests, we take the agent addresses and enroll the agents as a service under the "Services" tab in Agentverse.

## Agent Validation on Agentverse Explorer
*Note: You can validate the procedure by searching for your agent's address on Agent Explorer, checking if the protocols have been uploaded successfully. If not, you need to wait for some time (1-2 minutes) until the protocols are uploaded successfully.*

## Create a Service Group

1. Start by creating a new service group on Agentverse.
2. Set up the service group as PRIVATE (you will only be able to see your own agents).
- If you set up your service group as Public, anyone will be able to see your agents.

**Service group has been created.**

## Create a Service

1. To register the agents as a service, input a concise title and description for the agent service.
2. Choose the service group for the agent service that you've created previously.
3. Fill in the agent address in the Agent field.
4. Set the task type to Task.

![Image](./image.png)

Now, your agents are enrolled as a service in Agentverse. You can manage and monitor them under the "Services" tab. Ensure that you follow the agent validation steps on Agent Explorer to confirm successful enrollment.
78 changes: 78 additions & 0 deletions integrations/recipe-finder/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Here we demonstrate how we can create a DeltaV compatible agent responsible for generating recipes with list of
# ingredients. After running this agent, it can be registered to DeltaV on Agentverse's Services tab. For registration,
# you will have to use the agent's address.
#
# third party modules used in this example
import requests
from pydantic import Field
from ai_engine import UAgentResponse, UAgentResponseType


class RecipeSearch(Model):
ingredients: str = Field(description="Describes the field where user provides the ingredients to get the recipe")


chef_agent_protocol = Protocol("Chef")


def generate_recipes_api(ingredients: list, api_key: str, num_results: int = 2) -> list:
"""Generate multiple recipes and instructions based on a single set of ingredients.
Args:
ingredients (list): list of ingredients.
api_key (str): OpenAI secret key.
num_results (integer): max number of results.
"""
endpoint = "https://api.openai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}

recipes = []

for _ in range(num_results):
# Construct the input message for the GPT-3.5-turbo API
prompt = f"Create a recipe using the following ingredients: {', '.join(ingredients)}."

data = json.dumps({
"model": "gpt-3.5-turbo",
"messages": [{"role": "system", "content": "You are a helpful assistant that generates recipes."},
{"role": "user", "content": prompt}],
"temperature": 0.7
})

try:
response = requests.post(endpoint, headers=headers, data=data)
response.raise_for_status()
api_response = response.json()

# Extract the generated message from the API response
if api_response.get('choices'):
recipe = api_response['choices'][0]['message']['content']
recipes.append({"ingredients": ingredients, "recipe": recipe})
else:
recipes.append({"ingredients": ingredients, "recipe": None})
except Exception as e:
print(f"Error during OpenAI GPT-3.5-turbo API call: {e}")
recipes.append({"ingredients": ingredients, "recipe": None})
return recipes


@chef_agent_protocol.on_message(model=RecipeSearch, replies=UAgentResponse)
async def on_message(ctx: Context, sender: str, msg: RecipeSearch):
api_key = API_Key
options = []
splited_str = msg.ingredients.split(",")
recipes_result = generate_recipes_api(splited_str, api_key, 2)
for i, recipe_info in enumerate(recipes_result):
recipe = recipe_info["recipe"]
formatted_segment = f"""
🌟 Instructions: {recipe}\n
"""
options.append(formatted_segment)
print(options)
await ctx.send(sender, UAgentResponse(message='\n\n'.join(options), type=UAgentResponseType.FINAL))


agent.include(chef_agent_protocol)
Binary file added integrations/recipe-finder/image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions integrations/recipe-finder/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"title": "Recipe Finder",
"description": "Recipe Finder integration enhances the capabilities of an AI agent by leveraging OpenAI for Recipe Generation.",
"categories": ["Recipe Finder", "OpenAI"],
"deltav": true
}

0 comments on commit bdcad46

Please sign in to comment.