Holoworld 백서

Holoworld

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 13쪽 중 6쪽

| Type | Required | Description | | --------- | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Yes | ID of the Agent to use. This will be used to determined the voice, body, and personality to use during the video. | | `scale` | number | Yes | <p>Size of the model relative to the frame (0.1-2.0).<br>You can figure this out from <a href="https://app.holoworld.com/studio"><https://app.holoworld.com/studio></a></p> | | `x` | number | Yes | Horizontal position of the model. You can figure this out from <https://app.holoworld.com/studio> | | `y` | number | Yes | Vertical position of the model. You can figure this out from <https://app.holoworld.com/studio> | ### Limitations and Best Practices #### Limitations * Maximum text length: try to keep the text under 200 characters per scene * Maximum scenes: 5 per video * Supported background image formats: JPG, PNG * Maximum file size for background images: try to keep the images under 5MB ### Pricing Each scene costs 0.3 credits. If a scene also has subtitles that adds an extra 0.1 credits.&#x20; ### Sample Backgrounds We provide these sample background to easily getting up and running. But you can always add your own! (Just make sure the sizes are correct!) ```javascript // Sample backgrounds for 1/1 videos (1200x1200) [ 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/square/background0.jpg', 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/square/background1.jpg', 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/square/background2.jpg', 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/square/background3.jpg', 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/square/background4.jpg', 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/square/background5.jpg', 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/square/background6.jpg', ]; // Sample backgrounds for 9/16 videos (1080 x 1920) [ 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/vertical/background0.jpg', 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/vertical/background1.jpg', 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/vertical/background2.jpg', 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/vertical/background3.jpg', 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/vertical/background4.jpg', 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/vertical/background5.jpg', 'https://hologramxyz.s3.us-east-1.amazonaws.com/backgrounds/video/vertical/background6.jpg', ]; ``` ### Examples #### Watching the video rendering status in Typescript ```typescript const renderId = '123'; // Await for the video to be completed! while (true) { const response = await fetch( `https://app.holoworld.com/api/studio/render/${renderId}`, { method: 'GET', headers: { 'Content-Type': 'application/json', 'x-api-key': YOUR_API_KEY, }, }, ); if (!response.ok) { const errorData = await response.json(); throw new Error( `HTTP error while polling video render status! status: ${response.status} data: ${errorData}`, ); } const data = await response.json(); if (data.status === 'completed') { return data.url; } if (data.status === 'failed') { throw new Error(`Failed to render video! Reason: ${data.errorMessage}`); } await new Promise((resolve) => setTimeout(resolve, 1000)); } ``` # Chat API Generate a dynamic chat response with MCP support for an agent using the Holoworld Chat API. #### Authentication All API requests require authentication using an API key. The API key should be included in the request headers as `x-api-key`. To obtain an API key: 1. Register for an account at [Holoworld](https://app.holoworld.com/) 2. Navigate to your profile > settings 3. Copy the API key. From now on, this key be referenced as `YOUR_API_KEY` <figure><img src="https://3847104975-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fx3XJPuHjcm9UuQOCtVEu%2Fuploads%2FswOyiICQU7yWQD8r4Lzt%2Fff5c2190720a6cc2e8ec418e07499d3a.png?alt=media&amp;token=9fc71153-6baa-4daf-a083-626a8a3f13b1" alt=""><figcaption></figcaption></figure> ### Before getting started Ensure you have an Agent with a valid agent created on Holoworld (consult [Create Agent](/holoworld/agent-market/create-agent) for more information). Go to your agent's profile page and copy the Agent ID (the agent ID is the last part of the URL after the slash on the Agent's profile page) <figure><img src="https://3847104975-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fx3XJPuHjcm9UuQOCtVEu%2Fuploads%2FCDhKulDt72UJGCMolZov%2Fca7cb8ef8a57c359f602305ec5ba52e0.png?alt=media&amp;token=a14e7eb3-d8ce-48fd-9069-0eb1329e43ce" alt=""><figcaption></figcaption></figure> From now on, this will be referenced as `YOUR_AGENT_ID.` ### API Endpoints Send a message and receive a response `/api/chat` Initiates a new video rendering job with the specified parameters. * **URL:** `https://holoworld-llm.com`&#x20; * **Method:** `POST` * **Headers:** * `Content-Type: application/json` * `x-api-key: YOUR_API_KEY` **Request Body** ```json { "agentId": "YOUR_AGENT_ID", "input": "Hey there how are you?", "username": "YOUR_USERNAME", "chatHistory": [ { "speaker": "Human", "content": "Hello!", "sentAt": "2023-04-03T10:15:30Z" }, { "speaker": "AI", "content": "Hi there! How can I help you today?", "sentAt": "2023-04-03T10:15:35Z" } ] } ``` **Chat History Format** The chat history should be an array of `ChatMessage` objects with the following structure: ```typescript type ChatMessage = { speaker: 'AI' | 'Human'; content: string; sentAt?: string; toolCalls?: ToolCall[]; isToolCall?: boolean; }; type ToolCall = { name: string; content: string; query?: string; }; ``` **Streaming Response** The endpoint returns an HTTP stream containing a series of JSON chunks, each separated by double newlines (`\n\n`). Each chunk represents a different event in the response generation process. **Streaming Chunk Format** Each streaming chunk follows this structure: ```typescript interface StreamingChunk { type: | 'tool_result' | 'tool_call' | 'completion' | 'content' | 'start' | 'unknown' | 'error' | 'end'; name?: string; content?: string; id?: string; index?: number; args?: string; messageId?: string; reason?: string; data?: string; message?: string; original?: string; } ``` #### Chunk Types * `start`: Indicates the beginning of a new message or response * `content`: Contains a fragment of the agent's text response * `tool_call`: Indicates the agent is invoking a tool, with tool name and arguments * `tool_result`: Contains the result of a tool invocation * `completion`: Signals completion of a message or tool operation * `end`: Marks the end of the entire response * `error`: Contains error information if something went wrong * `unknown`: Used for unrecognized event types #### Handling Streaming Responses ```typescript /** * Processes a chat stream from the API, handling different event types * including content, tool calls, and tool results */ async function processChatStream({ characterId, chatHistory, newMessageContent, username }: { characterId: string; chatHistory: ChatMessage[]; newMessageContent: string; username: string; }) { try { // 1. Initialize API call and stream const response = await fetchChatResponse(characterId, chatHistory, newMessageContent, username); const { stream, isValid } = validateResponse(response); if (!isValid) { console.log('No stream available in response'); return { isValid: false, answer: '', newChatHistory: chatHistory }; } // 2. Process the stream const { newChatHistory } = await processStream(stream, chatHistory); return { isValid: true, answer: getLatestContent(newChatHistory), newChatHistory }; } catch (error) { console.error('Stream processing error:', error); return { isValid: false, answer: '', newChatHistory: chatHistory }; } } /** * Makes the API call to the chat endpoint */ async function fetchChatResponse( characterId: string, chatHistory: ChatMessage[], newMessageContent: string, username: string ) { return await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'YOUR_API_KEY' }, cache: 'no-store', body: JSON.stringify({ agentId: characterId, chatHistory: chatHistory, input: newMessageContent, username: username }), }); } /** * Validates the API response and gets the stream */ function validateResponse(response: Response) { const stream = response.body; return { stream, isValid: !!stream }; } /** * Process the stream data and update chat history */ async function processStream(stream: ReadableStream<Uint8Array>, chatHistory: ChatMessage[]) { const reader = stream.getReader(); let newChatHistory = [...chatHistory]; // State tracking const state = { currentPhase: 'content', // 'content' | 'tool_calling' | 'post_tool' currentContent: '', toolQuery: '', buffer: '' }; try { // Read the stream in chunks while (true) { const { done, value } = await reader.read(); if (done) { console.log('Stream reading complete'); break; } // Update buffer with new data state.buffer += new TextDecoder().decode(value, { stream: true }); // Process complete chunks const chunks = state.buffer.split('\n\n'); state.buffer = chunks.pop() || ''; // Process each chunk for (const chunk of chunks) { if (!chunk.trim()) continue; try { const event = JSON.parse(chunk) as StreamingChunk; console.log('Parsed event:', event); // Handle the event based on type newChatHistory = handleEvent(event, newChatHistory, state); } catch (e) { console.error('Error parsing JSON chunk:', e, 'Raw chunk:', chunk); } } } } finally { reader.releaseLock(); } return { newChatHistory }; } /** * Handle a single streaming event and update chat history accordingly */ function handleEvent( event: StreamingChunk, chatHistory: ChatMessage[], state: { currentPhase: string; currentContent: string; toolQuery: string; buffer: string; } ): ChatMessage[] { switch (event.type) { case 'start': return handleStartEvent(chatHistory, state); case 'content': return handleContentEvent(event, chatHistory, state); case 'tool_call': return handleToolCallEvent(event, chatHistory, state); case 'tool_result': return handleToolResultEvent(event, chatHistory); case 'completion': return handleCompletionEvent(event, chatHistory, state); case 'end': console.log('End event received'); return chatHistory; default: console.log(`Unknown event type: ${event.type}`); return chatHistory; } } /** * Handle the 'start' event type */ function handleStartEvent( chatHistory: ChatMessage[], state: { currentPhase: string; currentContent: string; toolQuery: string; } ) { console.log('New message starting'); if (state.currentPhase === 'tool_calling') { // If we were in tool calling phase, start a new message for post-tool content state.currentPhase = 'post_tool'; state.currentContent = ''; state.toolQuery = ''; // Add a new message for post-tool content return [ ...chatHistory, { speaker: 'AI', content: '', sentAt: new Date().toString(), } ]; } return chatHistory; } /** * Handle the 'content' event type */ function handleContentEvent( event: StreamingChunk, chatHistory: ChatMessage[], state: { currentPhase: string; currentContent: string; } ) { console.log('Content event received'); // Update the current content state.currentContent += event.content || ''; // Update phase state.currentPhase = 'content'; // Update the last message with new content const lastIndex = chatHistory.length - 1; return [ ...chatHistory.slice(0, lastIndex), { ...chatHistory[lastIndex], content: state.currentContent, }, ]; } /** * Handle the 'tool_call' event type */ function handleToolCallEvent( event: StreamingChunk, chatHistory: ChatMessage[], state: { currentPhase: string; toolQuery: string; } ) { console.log('Tool call event received'); // If this is the first tool call in a content or post-tool phase if (state.currentPhase === 'content' || state.currentPhase === 'post_tool') { // Transition to tool calling phase state.currentPhase = 'tool_calling'; // Start building the tool query state.toolQuery = event.args || ''; // Add a new message for tool calling return [ ...chatHistory, { speaker: 'AI', content: '', // Empty content for tool message sentAt: new Date().toString(), toolCalls: [ { name: event.name || 'unknown_tool', content: '', // Will be filled by tool result query: state.toolQuery, }, ], isToolCall: true, } ]; } // Update existing tool call if (state.currentPhase === 'tool_calling') { if (event.args) { state.toolQuery += event.args; } // Find the last tool call message const lastIndex = chatHistory.findLastIndex(msg => msg.isToolCall); if (lastIndex === -1) return chatHistory; const currToolCalls = chatHistory[lastIndex].toolCalls; // Update the last tool call return [ ...chatHistory.slice(0, lastIndex), { ...chatHistory[lastIndex], toolCalls: [ ...currToolCalls.slice(0, currToolCalls.length - 1), { ...currToolCalls[currToolCalls.length - 1], query: state.toolQuery, }, ], }, ...chatHistory.slice(lastIndex + 1), ]; } return chatHistory; } /** * Handle the 'tool_result' event type */ function handleToolResultEvent(event: StreamingChunk, chatHistory: ChatMessage[]) { console.log('Tool result event received'); // Find the last tool call message const lastIndex = chatHistory.findLastIndex(msg => msg.isToolCall); if (lastIndex === -1) return chatHistory; const currToolCalls = chatHistory[lastIndex].toolCalls; // Update the tool call with result return [ ...chatHistory.slice(0, lastIndex), { ...chatHistory[lastIndex], toolCalls: [ ...currToolCalls.slice(0, currToolCalls.length - 1), { ...currToolCalls[currToolCalls.length - 1], name: event.name || 'unknown_tool', content: event.content || '', }, ], }, ...chatHistory.slice(lastIndex + 1), ]; } /** * Handle the 'completion' event type */ function handleCompletionEvent( event: StreamingChunk, chatHistory: ChatMessage[], state: { currentPhase: string; currentContent: string; } ) { console.log('Completion event received'); if (event.reason === 'tool_use') { // Tool call completion console.log('Tool use completion'); return chatHistory; } if (event.reason === 'end_turn' && state.currentPhase === 'post_tool' && state.currentContent.trim()) { // Final message completion - ensure the current content is saved const finalIndex = chatHistory.length - 1; return [ ...chatHistory.slice(0, finalIndex), { ...chatHistory[finalIndex], content: state.currentContent, }, ]; } return chatHistory; } /** * Extract the latest content from chat history */ function getLatestContent(chatHistory: ChatMessage[]): string { if (chatHistory.length === 0) return ''; const lastMessage = chatHistory[chatHistory.length - 1]; return lastMessage.content || ''; } ``` **Standard vs. Tool Messages** The API distinguishes between standard content messages and tool-invocation messages: **Standard Message** A regular message from the AI with text content that's displayed directly to the user: ```typescript { "speaker": "AI", "content": "Hello! How can I help you today?", "sentAt": "2023-04-03T10:15:35Z" } ``` #### Tool Message A special message type that indicates the AI has called a tool to perform a task: ```typescript { "speaker": "AI", "content": "", // Usually empty for tool calls "sentAt": "2023-04-03T10:16:00Z", "toolCalls": [ { "name": "calculator", "query": "12 * 34 + 56", "content": "464" // Result from the tool } ], "isToolCall": true } ``` #### UI Considerations In a chat interface, these message types should be displayed differently: * **Standard Messages**: Displayed as regular chat bubbles with the AI's text content. * **Tool Messages**: Displayed as a specialized UI component that shows: * The tool being used (e.g., "Calculator", "Weather API") * The query or input to the tool * The result returned by the tool Tool messages can be styled differently to visually distinguish them from regular content, such as using a different background color, adding an icon representing the tool type, or displaying them in a card-like interface with clear sections for the tool name, query, and result. For example, a calculator tool might be displayed with a calculator icon, showing the calculation performed and its result in a structured format, while a weather tool might show forecast information with appropriate weather icons. #### Example of collapsable tool query and content&#x20; <figure><img src="https://3847104975-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fx3XJPuHjcm9UuQOCtVEu%2Fuploads%2FvegPfifdxsUz7as3ailY%2Fimage.png?alt=media&amp;token=878afd91-3361-42fc-acd1-4364c3fc55d3" alt=""><figcaption></figcaption></figure> <figure><img src="https://3847104975-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fx3XJPuHjcm9UuQOCtVEu%2Fuploads%2FJKRiD0Vq8McUWSuVazJT%2Fimage.png?alt=media&amp;token=8911cabe-a181-45cb-af18-c7af235d76c3" alt=""><figcaption></figcaption></figure> #### Error Handling The API may return error events in the stream. These should be handled appropriately: ```typescript case 'error': { console.error('Error event received:', event.message); // Display appropriate error message to the user break; } ``` <br> # FAQs ### **Is it available on mobile?** Yes, Holoworld is desktop and mobile friendly. ### **How do I create my own character on Holoworld?** Head to the [create page](https://www.holoworld.live/create) and start the creation process! You can then create a Character with a Brain and a Body, or just with a Brain. It’s up to you to share your creativity! ### **Can I connect my Wallet?** Yes, you can connect your wallet via MetaMask, Coinbase or WalletConnect. ### **Is Holoworld suitable for all age groups?** Yes, any age groups can access Holoworld. However, to access the NSFW content you must be 18 years or older. ### How about content that is not safe for work (NSFW)? Holoworld provides NSFW characters. ### **How often is Holoworld updated with new features?** Holworld is updated with new features on a weekly basis. Make sure to check back for the latest updates! ### **Can I rely on the accuracy of the responses provided by Characters?** While we strive to provide accurate and helpful information, it's important to note that Characters do not always provide accurate informations. ### **How can I report a quality concern regarding Character responses?** We’d love to hear your feedback! Feel free to open a ticket in our [Discord](https://discord.gg/vDaeDPtMF8) or send us an email at <gm@hologram.xyz> ### **Is my conversation data kept private?** Your conversations with characters is always 100% private. No one but you can access your conversations. ### **Can other users see my conversations?** No, only you can see your conversations. ### **How to permanently delete my account?** To permanently delete your account, please open a ticket in our [Discord](https://discord.gg/vDaeDPtMF8) or send us an email at <gm@hologram.xyz> ### **Is there an API?** Yes, we have an API to access our Characters. If you would like to get access to the API, please send us an email at <gm@hologram.xyz> # Community Guidelines ### 1. Introduction Welcome to Holoworld, a community where get your favorite characters alive. ### 2. Age Requirement To access any NSFW content, you must be 18 years and older. ### 3. Conten
프로젝트로 돌아가기