Building AI-powered intelligent agents has never been more accessible. Whether you want to create a customer service bot, an automated research assistant, or a personalized recommendation system, Coze's platform combined with HolySheep AI's high-performance infrastructure gives you enterprise-grade capabilities at a fraction of the traditional cost.
In this hands-on guide, I will walk you through every step of configuring plugins and knowledge bases for your Coze intelligent agent, even if you have zero prior experience with APIs or coding. By the end, you will have a fully functional agent that can retrieve information, process user queries, and deliver intelligent responses powered by HolySheep AI's <50ms latency API.
Understanding the Coze Platform Architecture
Before diving into configuration, let us understand what we are building. A Coze intelligent agent consists of three core components that work together seamlessly.
The **Bot** itself serves as the interface that users interact with. It handles conversation flow, manages context, and orchestrates responses. When a user sends a message, the bot routes it through the appropriate processing pipeline.
**Plugins** extend the bot's capabilities beyond basic text generation. They connect to external services, databases, and APIs to fetch real-time data, perform calculations, or execute specific tasks. Without plugins, your bot can only work with static information built into its prompts.
**Knowledge Bases** provide a structured way to store and retrieve domain-specific information. Unlike plugins that pull external data, knowledge bases contain documents, FAQs, product catalogs, or any structured information you want the bot to access during conversations.
HolySheep AI enhances this architecture by providing the underlying language model processing power. When your Coze agent needs to understand context, generate responses, or reason through complex queries, it calls the HolySheheep API which delivers results in under 50 milliseconds—a speed that makes conversational AI feel truly responsive.
Setting Up Your HolySheep AI Account
Before configuring Coze, you need your HolySheep AI API credentials. [Sign up here](https://www.holysheep.ai/register) to receive free credits immediately upon registration.
The registration process takes less than two minutes. HolySheep AI supports both international payment methods and local Chinese options including WeChat Pay and Alipay, making it convenient regardless of your location.
After registration, navigate to your dashboard and locate the API Keys section. Click "Create New Key" and give it a descriptive name like "Coze-Integration." Copy the generated key immediately—**HolySheep only displays it once**.
For reference, here are the current 2026 model pricing per million tokens that make HolySheep AI exceptionally cost-effective:
- **DeepSeek V3.2**: $0.42 per million tokens
- **Gemini 2.5 Flash**: $2.50 per million tokens
- **Claude Sonnet 4.5**: $15 per million tokens
- **GPT-4.1**: $8 per million tokens
With the exchange rate of ¥1 equals $1 and HolySheep's direct pricing, you save over 85% compared to market rates of ¥7.3 per dollar equivalent.
Configuring Your First Plugin in Coze
Plugins in Coze act as bridges between your bot and external services. Let us create a weather lookup plugin as our first example—this demonstrates the core concepts clearly.
Step 1: Create the Plugin Definition
In your Coze workspace, navigate to the Plugins section and click "Create Plugin." You will see a configuration panel with several fields.
The **Plugin Name** should be descriptive and lowercase with hyphens:
weather-lookup. The **Description** field should explain what the plugin does in plain language. Write something like: "Retrieves current weather conditions and forecasts for any city worldwide."
The **Authentication** section determines how Coze communicates with your plugin. For development purposes, select "None" or "API Key" depending on your weather service. Most public weather APIs require a free API key that you obtain from their developer portal.
Step 2: Define the API Endpoint
Every plugin needs at least one API endpoint to function. Click "Add Endpoint" and configure the following:
- **Method**: GET (we are retrieving data, not modifying it)
- **URL Pattern**:
https://api.weather-service.com/v1/current
- **Parameters**: Add a parameter named
city with type "string" and description "The city name to look up"
In the **Headers** section, add your API key if required. Most weather services expect this in the Authorization header as
Bearer YOUR_API_KEY.
Step 3: Connect to HolySheep AI
Now comes the critical integration step. In Coze's model settings, select HolySheep AI as your provider. Enter your HolySheep API credentials:
import requests
HolySheep AI API Configuration
HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
HOLYSHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY"
def query_holysheep(prompt, context=None):
"""
Send a query to HolySheep AI and receive a processed response.
Args:
prompt: The user's question or request
context: Optional context from previous conversation turns
Returns:
dict: Contains 'response' (text) and 'tokens_used' (int)
"""
headers = {
"Authorization": f"Bearer {HOLYSHEEP_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": "deepseek-v3.2",
"messages": [
{"role": "system", "content": "You are a helpful weather assistant."}
],
"temperature": 0.7,
"max_tokens": 500
}
if context:
payload["messages"].append({"role": "user", "content": f"Context: {context}\n\nQuestion: {prompt}"})
else:
payload["messages"].append({"role": "user", "content": prompt})
try:
response = requests.post(
f"{HOLYSHEEP_BASE_URL}/chat/completions",
headers=headers,
json=payload,
timeout=30
)
response.raise_for_status()
data = response.json()
return {
"response": data["choices"][0]["message"]["content"],
"tokens_used": data["usage"]["total_tokens"],
"latency_ms": response.elapsed.total_seconds() * 1000
}
except requests.exceptions.Timeout:
return {"error": "Request timed out. Please try again."}
except requests.exceptions.RequestException as e:
return {"error": f"API request failed: {str(e)}"}
Example usage
result = query_holysheep("What is the weather in Tokyo today?")
print(f"Response: {result.get('response')}")
print(f"Latency: {result.get('latency_ms', 'N/A')}ms")
This integration ensures that when your Coze agent needs language understanding or generation capabilities, it leverages HolySheheep's infrastructure with sub-50ms response times.
Building and Configuring Knowledge Bases
Knowledge bases transform your Coze agent from a generic chatbot into a specialized expert on your specific domain. Let us create a product knowledge base for an e-commerce bot.
Creating Your Knowledge Base
Navigate to the Knowledge Bases section in Coze and click "Create Knowledge Base." Give it a meaningful name:
Product-Knowledge-Base.
The **Data Source** section accepts multiple formats. You can upload documents directly (PDF, DOCX, TXT), connect to external sources like Notion or Confluence, or use the API to push structured data programmatically.
For our e-commerce example, we will create a structured knowledge base using the API:
import json
import requests
from datetime import datetime
HolySheep Knowledge Base Management
HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
HOLYSHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY"
class ProductKnowledgeBase:
"""
Manages a product knowledge base for Coze integration.
Supports adding, updating, and querying product information.
"""
def __init__(self, api_key, base_url=HOLYSHEEP_BASE_URL):
self.api_key = api_key
self.base_url = base_url
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def add_product(self, product_data):
"""
Add a new product to the knowledge base.
Args:
product_data: dict containing:
- name: Product name
- category: Product category
- price: Price in USD
- description: Product description
- features: List of key features
"""
endpoint = f"{self.base_url}/knowledge-base/products"
payload = {
"action": "upsert",
"collection": "ecommerce_products",
"document": {
"id": f"prod_{product_data['name'].lower().replace(' ', '_')}",
"name": product_data["name"],
"category": product_data["category"],
"price_usd": product_data["price"],
"description": product_data["description"],
"features": product_data.get("features", []),
"last_updated": datetime.now().isoformat()
},
"metadata": {
"embedding_model": "text-embedding-v2",
"chunk_size": 512
}
}
try:
response = requests.post(endpoint, headers=self.headers, json=payload)
response.raise_for_status()
result = response.json()
return {
"success": True,
"document_id": result.get("id"),
"tokens_cost": result.get("usage", {}).get("total_tokens", 0)
}
except requests.exceptions.RequestException as e:
return {"success": False, "error": str(e)}
def search_products(self, query, top_k=5):
"""
Search the knowledge base for relevant products.
Args:
query: Natural language search query
top_k: Number of results to return
Returns:
List of matching products with relevance scores
"""
endpoint = f"{self.base_url}/knowledge-base/search"
payload = {
"collection": "ecommerce_products",
"query": query,
"top_k": top_k,
"include_embeddings": False,
"filter": None
}
try:
response = requests.post(endpoint, headers=self.headers, json=payload)
response.raise_for_status()
results = response.json()
return {
"results": results.get("matches", []),
"search_latency_ms": results.get("latency_ms", 0),
"query_embedding_cost": results.get("usage", {}).get("total_tokens", 0)
}
except requests.exceptions.RequestException as e:
return {"results": [], "error": str(e)}
Initialize the knowledge base
kb = ProductKnowledgeBase(HOLYSHEEP_API_KEY)
Add sample products
sample_products = [
{
"name": "Wireless Noise-Canceling Headphones",
"category": "Electronics",
"price": 249.99,
"description": "Premium over-ear headphones with active noise cancellation, 30-hour battery life, and Hi-Res Audio support.",
"features": ["ANC", "30hr battery", "Bluetooth 5.2", "USB-C charging"]
},
{
"name": "Mechanical Gaming Keyboard",
"category": "Electronics",
"price": 129.99,
"description": "RGB backlit mechanical keyboard with Cherry MX switches, programmable macros, and aircraft-grade aluminum frame.",
"features": ["Cherry MX Blue", "RGB", "Anti-ghosting", "Media keys"]
},
{
"name": "Ergonomic Office Chair",
"category": "Furniture",
"price": 399.99,
"description": "Lumbar support office chair with adjustable armrests, breathable mesh back, and 5-year warranty.",
"features": ["Adjustable arms", "Mesh back", "Lumbar support", "360° swivel"]
}
]
Populate the knowledge base
for product in sample_products:
result = kb.add_product(product)
print(f"Added: {product['name']} - Success: {result.get('success')}")
Test search functionality
search_result = kb.search_products("What wireless headphones are available?")
print(f"\nSearch returned {len(search_result.get('results', []))} results")
print(f"Search latency: {search_result.get('search_latency_ms')}ms")
Structuring Documents for Optimal Retrieval
The way you structure documents in your knowledge base directly impacts retrieval quality. Coze uses semantic search, meaning it finds content based on meaning rather than exact keyword matches.
Break large documents into logical chunks of 300-800 tokens. Each chunk should represent a complete, self-contained unit of information. If you have a 2000-word product manual, split it into sections like "Getting Started," "Troubleshooting," and "Advanced Features."
Use clear, descriptive headings and include relevant keywords naturally within the content. The HolySheep AI embedding model processes these chunks efficiently, enabling accurate retrieval even with complex queries.
Integrating Plugins with Knowledge Bases
The true power of Coze emerges when plugins and knowledge bases work together. Let us create a customer service agent that uses both.
Designing the Conversation Flow
Your agent should seamlessly transition between using knowledge base information and calling plugins. For instance, when a customer asks about a product, the agent first searches the knowledge base. If the customer then asks to place an order, the agent calls the order plugin.
Configure this in Coze's workflow editor by creating conditional nodes:
User Input
↓
[Intent Detection] → Use HolySheep AI to classify intent
↓
├── Product Query → [Knowledge Base Search] → Format Response
│
├── Order Request → [Order Plugin] → Confirm Order
│
├── Complaint → [Ticket Plugin] → Create Support Ticket
│
└── General Question → [Direct HolySheep Response]
Implementing the Hybrid Agent
import requests
import re
class CozeHybridAgent:
"""
A Coze intelligent agent that combines knowledge base
search with plugin capabilities and HolySheep AI processing.
"""
def __init__(self, holysheep_api_key, coze_bot_id):
self.holysheep_key = holysheep_api_key
self.coze_bot_id = coze_bot_id
self.base_url = "https://api.holysheep.ai/v1"
self.coze_url = "https://api.coze.com/v1"
def detect_intent(self, user_message):
"""
Use HolySheep AI to classify user intent.
"""
prompt = f"""Classify this customer message into one of these intents:
- product_query: Questions about products, features, pricing
- order_request: Requests to place, modify, or cancel orders
- complaint: Issues, problems, or dissatisfaction
- general: Questions outside other categories
Message: "{user_message}"
Return only the intent category, nothing else."""
headers = {"Authorization": f"Bearer {self.holysheep_key}"}
payload = {
"model": "deepseek-v3.2",
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.1,
"max_tokens": 20
}
response = requests.post(
f"{self.base_url}/chat/completions",
headers=headers,
json=payload
)
intent_text = response.json()["choices"][0]["message"]["content"].strip().lower()
# Map response to intent
for intent in ["product_query", "order_request", "complaint", "general"]:
if intent in intent_text:
return intent
return "general"
def process_message(self, user_message, conversation_context=None):
"""
Main message processing pipeline.
"""
intent = self.detect_intent(user_message)
if intent == "product_query":
return self.handle_product_query(user_message, conversation_context)
elif intent == "order_request":
return self.handle_order_request(user_message)
elif intent == "complaint":
return self.handle_complaint(user_message)
else:
return self.handle_general_query(user_message, conversation_context)
def handle_product_query(self, query, context):
"""
Search knowledge base and generate comprehensive response.
"""
# Step 1: Search knowledge base
kb_response = self.search_knowledge_base(query)
# Step 2: Generate response with HolySheep AI
context_prompt = f"Customer is asking about: {query}\n\nRelevant product information:\n{kb_response}\n\n"
if context:
context_prompt += f"Previous conversation:\n{context}\n\n"
context_prompt += "Provide a helpful, accurate response based on the product information above."
headers = {"Authorization": f"Bearer {self.holysheep_key}"}
payload = {
"model": "deepseek-v3.2",
"messages": [{"role": "user", "content": context_prompt}],
"temperature": 0.7,
"max_tokens": 300
}
response = requests.post(
f"{self.base_url}/chat/completions",
headers=headers,
json=payload,
timeout=30
)
return {
"response": response.json()["choices"][0]["message"]["content"],
"intent": "product_query",
"sources": kb_response
}
def search_knowledge_base(self, query):
"""
Query the Coze knowledge base through HolySheep AI.
"""
headers = {"Authorization": f"Bearer {self.holysheep_key}"}
payload = {
"model": "deepseek-v3.2",
"messages": [{
"role": "system",
"content": "You are a product search assistant. Given a customer query, extract the key product-related terms and generate an optimized search query for a product database."
}, {
"role": "user",
"content": f"Customer query: {query}\n\nGenerate a concise search query (max 10 words):"
}],
"temperature": 0.1,
"max_tokens": 50
}
response = requests.post(
f"{self.base_url}/chat/completions",
headers=headers,
json=payload
)
search_query = response.json()["choices"][0]["message"]["content"].strip()
# Simulate knowledge base search result
return f"Found products matching '{search_query}': Wireless Headphones ($249.99), Gaming Keyboard ($129.99), Office Chair ($399.99)"
def handle_order_request(self, message):
"""Process order-related requests."""
return {
"response": "I can help you with your order. Let me connect you to our order management system.",
"intent": "order_request",
"action": "transfer_to_order_plugin"
}
def handle_complaint(self, message):
"""Handle customer complaints."""
return {
"response": "I'm sorry you're experiencing issues. Let me create a support ticket and connect you with our customer service team.",
"intent": "complaint",
"action": "create_support_ticket"
}
def handle_general_query(self, message, context):
"""Handle general questions using pure AI generation."""
prompt = message
if context:
prompt = f"Previous context: {context}\n\nCurrent question: {message}"
headers = {"Authorization": f"Bearer {self.holysheep_key}"}
payload = {
"model": "deepseek-v3.2",
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.7,
"max_tokens": 300
}
response = requests.post(
f"{self.base_url}/chat/completions",
headers=headers,
json=payload,
timeout=30
)
return {
"response": response.json()["choices"][0]["message"]["content"],
"intent": "general"
}
Initialize the agent
agent = CozeHybridAgent(
holysheep_api_key="YOUR_HOLYSHEEP_API_KEY",
coze_bot_id="your-coze-bot-id"
)
Process a sample conversation
test_message = "Do you have wireless headphones? What's the battery life?"
result = agent.process_message(test_message)
print(f"Intent detected: {result['intent']}")
print(f"Response: {result['response']}")
Testing and Optimization
After configuring your plugins and knowledge bases, rigorous testing ensures everything works correctly before deployment.
Unit Testing Individual Components
Test each plugin independently before integration. For our weather plugin, manually call the API endpoint with various city names and verify the responses.
Test knowledge base retrieval by running searches with different phrasings of the same query. If searching for "headphones" and "audio gear" returns different results, your embeddings may need adjustment.
Integration Testing
Run end-to-end conversations that exercise both plugins and knowledge bases. Create test scenarios like:
1. Query that triggers knowledge base search
2. Request that requires plugin execution
3. Multi-turn conversation testing context retention
4. Error handling when plugins or knowledge bases fail
Performance Benchmarking
Measure latency at each stage of the pipeline. HolySheep AI consistently delivers responses under 50ms for standard queries, but your overall agent response time includes Coze processing, network latency, and plugin execution.
Typical breakdown for a product query:
- Intent detection: ~30ms (HolySheep)
- Knowledge base search: ~100ms (Coze)
- Response generation: ~40ms (HolySheep)
- Network overhead: ~20ms
- **Total: ~190ms**
Related Resources
Related Articles