Hydra AI
Troubleshooting

Manual Setup

Set up Hydra AI manually without using the CLI

Manual Setup Guide

While the CLI provides the easiest way to get started with Hydra AI, you can also set up everything manually. This guide walks you through the process step by step.

Prerequisites

  1. Node.js (v16+ recommended)
  2. NPM or Yarn or PNPM
  3. A Hydra AI account and API key

Installation

Install the Hydra AI package in your project:

npm install hydra-ai

Step 1: Environment Setup

  1. Create a .env file in your project root:
NEXT_PUBLIC_HYDRAAI_API_KEY=your_api_key_here

How to use the CLI to get your API key?

  1. If you're using TypeScript, ensure your tsconfig.json includes:
tsconfig.json
{
  "compilerOptions": {
    "jsx": "react",
    "esModuleInterop": true
    // ... other options
  }
}

Step 2: Create Hydra Client

Create a hydra-client.ts file in your project:

src/hydra-client.ts
import { HydraClient } from "hydra-ai";
 
export const getHydraClient = (): HydraClient => {
  const hydra = new HydraClient({
    hydraApiKey: process.env.NEXT_PUBLIC_HYDRAAI_API_KEY,
  });
  return hydra;
};
 
export const registerHydraComponents = async (hydra: HydraClient) => {
  try {
    await Promise.all([
      // Register your components
      hydra.registerComponent({
        name: "MyComponent",
        description: "Description of your component...",
        component: MyComponent,
        propsDefinition: {
          MyComponent: zodToJsonSchema(MyComponentSchema),
        },
        // Optional: Add contextTools if your component needs data fetching
        contextTools: [
          /* your tools */
        ],
      }),
      // Register more components as needed
    ]);
  } catch (error) {
    console.error("Error registering components:", error);
  }
};

Step 3: Component Integration

Create your main chat or interaction component:

src/mainComponent.tsx
"use client";
 
import { useEffect, useMemo, useState } from "react";
import { getHydraClient, registerHydraComponents } from "./hydra-client";
 
export default function MainComponent() {
  const [isHydraReady, setIsHydraReady] = useState(false);
  const [isRegistering, setIsRegistering] = useState(false);
  const [message, setMessage] = useState("");
  const [generatedComponent, setGeneratedComponent] =
    useState<React.ReactNode | null>(null);
 
  // Initialize Hydra client
  const hydra = useMemo(() => getHydraClient(), []);
 
  // Register components on mount
  useEffect(() => {
    if (!isHydraReady && !isRegistering) {
      setIsRegistering(true);
      registerHydraComponents(hydra).then(() => {
        setIsHydraReady(true);
        setIsRegistering(false);
      });
    }
  }, [hydra, isHydraReady, isRegistering]);
 
  // Update handleGenerate to store the component
  const handleGenerate = async (message: string) => {
    try {
      const response = await hydra.generateComponent(message, (progress) => {
        console.log(progress);
      });
 
      if (typeof response === "object" && response.component) {
        setGeneratedComponent(response.component);
      }
    } catch (error) {
      console.error("Error generating component:", error);
    }
  };
 
  return (
    <div className="space-y-4">
      <div className="flex gap-2">
        <input
          type="text"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          placeholder="User context in the form of a message..."
          className="flex-1 p-2 border rounded"
        />
        <button
          onClick={() => handleGenerate(message)}
          disabled={!isHydraReady}
          className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
        >
          Generate
        </button>
      </div>
 
      {generatedComponent && (
        <div className="border rounded p-4">{generatedComponent}</div>
      )}
    </div>
  );
}

Type Safety

To ensure type safety, we recommend using Zod schemas for your components. Here's how to set up your types:

types/hydra.d.ts
import { z } from "zod";
 
declare module "hydra-ai" {
  export interface HydraClientOptions {
    hydraApiKey: string;
    options?: z.infer<typeof clientOptionsSchema>;
  }
 
  export class HydraClient {
    constructor(options: HydraClientOptions);
    registerComponent(config: {
      name: string;
      description: string;
      component: React.ComponentType<any>;
      propsDefinition: Record<string, any>;
    }): void;
    render(componentName: string, props: any): React.ReactElement;
    // Add other methods as needed
  }
}

See the Zod guide for more information on using Zod with Hydra AI.

Error Handling

Implement error boundaries for Hydra AI components:

src/components/HydraErrorBoundary.tsx
import React from "react";
 
class HydraErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { hasError: boolean }
> {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
 
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
 
  componentDidCatch(error, errorInfo) {
    console.error("Hydra AI Error:", error, errorInfo);
  }
 
  render() {
    if (this.state.hasError) {
      return <div>Something went wrong with this component.</div>;
    }
 
    return this.props.children;
  }
}
 
export default HydraErrorBoundary;

Troubleshooting

Common issues you might encounter:

  1. API Key Issues

    Error: Invalid API key provided

    Solution: Double-check your .env file and ensure the API key is correctly set.

  2. Component Registration Errors

    Error: Component "X" already registered

    Solution: Ensure you're not registering the same component multiple times.

  3. Type Errors

    Type 'X' is not assignable to type 'Y'

    Solution: Verify your component props match the registered prop types.


This manual setup gives you more control over the integration process and might be preferred for complex applications or when you need custom configuration options.

On this page