الأكاديمية ← أدلة تطبيقيةتوثيق رسمي · إرشاد عربي

استخدام Hermes كمكتبة Python

Using Hermes as a Python Library

متوسط7 دقائق قراءةالدرس 64 أسئلة✓ 2026-08-18
قبل أن تقرأ

ما هذه الصفحة، وماذا تحتوي.

التشغيل البرمجي: استعمال Hermes من داخل برنامج آخر بدل الكتابة له في المحادثة. يتيح إدخاله في أنظمتك: موقع، سكربت، خط إنتاج بيانات. الصفحة فيها تحذير من المصدر، و7 دقائق قراءة. انتبه: الواجهة المفتوحة على الشبكة تحتاج مصادقة. لا تتركها بلا حماية ولو على جهازك.

11أقسام
13أمثلة برمجية
1جداول
1أوامر
1,107كلمة من المصدر
الوصف الرسمي في سطر

Embed AIAgent in your own Python scripts, web apps, or automation pipelines — no CLI required

ماذا ستستطيع بعدها

نتائج مأخوذة من هذه الصفحة، لا من قالب.

  • تعرف ما التشغيل البرمجي ولماذا قد تحتاجه.
  • تنفّذ hermes uv sync وتفهم ما يحدث بعدها.
  • تقرأ الجدول وتأخذ منه السطر الذي يخصّك فقط.
  • تضبط OPENROUTER_API_KEY في المكان الصحيح.
ما ستقابله من أسماء

كما تظهر تمامًا داخل Hermes.

الأوامر
  • hermes uv sync
متغيرات البيئة
  • OPENROUTER_API_KEY
  • OPENAI_API_KEY
  • ANTHROPIC_API_KEY
  • YOUR_DISCORD_TOKEN
خريطة الصفحة

انتقل مباشرة إلى ما تحتاجه.

  1. 01Installation
  2. 02Basic Usage
  3. 03Full Conversation Control
  4. 04Configuring Tools
  5. 05Multi-turn Conversations
  6. 06Saving Trajectories
  7. 07Custom System Prompts
  8. 08Batch Processing
  9. 09Integration Examples
  10. 10Key Constructor Parameters
  11. 11Important Notes
الصفحة الرسمية كاملة

بلا اختصار أو حذف.

النص أدناه منقول من المصدر الرسمي بالإنجليزية حتى تبقى الأوامر والأسماء دقيقة كما هي. قبل كل قسم شرح عربي يوضّح ما بداخله.

Hermes isn't just a CLI tool. You can import AIAgent directly and use it programmatically in your own Python scripts, web applications, or automation pipelines. This guide shows you how.

---

Installation

خطوات عملية بالترتيب. نفّذ خطوة وتأكد أنها نجحت قبل الانتقال للتالية. الأوامر هنا: hermes uv sync.

Clone Hermes and create its supported editable development environment:

Shell3 أسطر
git clone https://github.com/NousResearch/hermes-agent.git
cd hermes-agent
uv sync

Run your application with uv run python your_app.py from that checkout. Hermes does not publish a supported wheel or source distribution for requirements.txt installs.

---

Basic Usage

فيه تحذير مهم. اقرأه قبل أن تنفّذ أي شيء من هذا القسم. نصّ التحذير من المصدر مذكور أسفل هذا الشرح.

The simplest way to use Hermes is the chat() method — pass a message, get a string back:

Python8 أسطر
from run_agent import AIAgent

agent = AIAgent(
    model="anthropic/claude-sonnet-4.6",
    quiet_mode=True,
)
response = agent.chat("What is the capital of France?")
print(response)

chat() handles the full conversation loop internally — tool calls, retries, everything — and returns just the final text response.

---

Full Conversation Control

شرح للفكرة نفسها. اقرأه ببطء، فبقية الأقسام تبني عليه. تذكير: استعمال Hermes من داخل برنامج آخر بدل الكتابة له في المحادثة.

For more control over the conversation, use run_conversation() directly. It returns a dictionary with the full response, message history, and metadata:

Python12 سطرًا
agent = AIAgent(
    model="anthropic/claude-sonnet-4.6",
    quiet_mode=True,
)

result = agent.run_conversation(
    user_message="Search for recent Python 3.13 features",
    task_id="my-task-1",
)

print(result["final_response"])
print(f"Messages exchanged: {len(result['messages'])}")

The returned dictionary contains:

  • final_response — The agent's final text reply
  • messages — The complete message history (system, user, assistant, tool calls)

(The task_id you pass in is stored on the agent instance for VM isolation but isn't echoed back in the return dict.)

You can also pass a custom system message that overrides the ephemeral system prompt for that call:

Python4 أسطر
result = agent.run_conversation(
    user_message="Explain quicksort",
    system_message="You are a computer science tutor. Use simple analogies.",
)

---

Configuring Tools

شرح للفكرة نفسها. اقرأه ببطء، فبقية الأقسام تبني عليه.

Control which toolsets the agent has access to using enabled_toolsets or disabled_toolsets:

Python13 سطرًا
# Only enable web tools (browsing, search)
agent = AIAgent(
    model="anthropic/claude-sonnet-4.6",
    enabled_toolsets=["web"],
    quiet_mode=True,
)

# Enable everything except terminal access
agent = AIAgent(
    model="anthropic/claude-sonnet-4.6",
    disabled_toolsets=["terminal"],
    quiet_mode=True,
)

---

Multi-turn Conversations

شرح للفكرة نفسها. اقرأه ببطء، فبقية الأقسام تبني عليه.

Maintain conversation state across multiple turns by passing the message history back in:

Python15 سطرًا
agent = AIAgent(
    model="anthropic/claude-sonnet-4.6",
    quiet_mode=True,
)

# First turn
result1 = agent.run_conversation("My name is Alice")
history = result1["messages"]

# Second turn — agent remembers the context
result2 = agent.run_conversation(
    "What's my name?",
    conversation_history=history,
)
print(result2["final_response"])  # "Your name is Alice."

The conversation_history parameter accepts the messages list from a previous result. The agent copies it internally, so your original list is never mutated.

---

Saving Trajectories

شرح للفكرة نفسها. اقرأه ببطء، فبقية الأقسام تبني عليه.

Enable trajectory saving to capture conversations in ShareGPT format — useful for generating training data or debugging:

Python8 أسطر
agent = AIAgent(
    model="anthropic/claude-sonnet-4.6",
    save_trajectories=True,
    quiet_mode=True,
)

agent.chat("Write a Python function to sort a list")
# Saves to trajectory_samples.jsonl in ShareGPT format

Each conversation is appended as a single JSONL line, making it easy to collect datasets from automated runs.

---

Custom System Prompts

شرح للفكرة نفسها. اقرأه ببطء، فبقية الأقسام تبني عليه.

Use ephemeral_system_prompt to set a custom system prompt that guides the agent's behavior but is not saved to trajectory files (keeping your training data clean):

Python8 أسطر
agent = AIAgent(
    model="anthropic/claude-sonnet-4",
    ephemeral_system_prompt="You are a SQL expert. Only answer database questions.",
    quiet_mode=True,
)

response = agent.chat("How do I write a JOIN query?")
print(response)

This is ideal for building specialized agents — a code reviewer, a documentation writer, a SQL assistant — all using the same underlying tooling.

---

Batch Processing

فيه تحذير مهم. اقرأه قبل أن تنفّذ أي شيء من هذا القسم. نصّ التحذير من المصدر مذكور أسفل هذا الشرح.

For running many prompts in parallel, Hermes includes batch_runner.py. It manages concurrent AIAgent instances with proper resource isolation:

Shellسطر واحد
python batch_runner.py --input prompts.jsonl --output results.jsonl

Each prompt gets its own task_id and isolated environment. If you need custom batch logic, you can build your own using AIAgent directly:

Python23 سطرًا

from run_agent import AIAgent

prompts = [
    "Explain recursion",
    "What is a hash table?",
    "How does garbage collection work?",
]

def process_prompt(prompt):
    # Create a fresh agent per task for thread safety
    agent = AIAgent(
        model="anthropic/claude-sonnet-4",
        quiet_mode=True,
        skip_memory=True,
    )
    return agent.chat(prompt)

with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
    results = list(executor.map(process_prompt, prompts))

for prompt, result in zip(prompts, results):
    print(f"Q: {prompt}\nA: {result}\n")

---

Integration Examples

إعدادات تضبطها مرة وتنساها. غيّر واحدًا في كل مرة حتى تعرف أثر كل تغيير. تضبط YOUR_DISCORD_TOKEN خارج المحادثة، في بيئة التشغيل.

FastAPI Endpoint

Python20 سطرًا
from fastapi import FastAPI
from pydantic import BaseModel
from run_agent import AIAgent

app = FastAPI()

class ChatRequest(BaseModel):
    message: str
    model: str = "anthropic/claude-sonnet-4"

@app.post("/chat")
async def chat(request: ChatRequest):
    agent = AIAgent(
        model=request.model,
        quiet_mode=True,
        skip_context_files=True,
        skip_memory=True,
    )
    response = agent.chat(request.message)
    return {"response": response}

Discord Bot

Python22 سطرًا

from run_agent import AIAgent

client = discord.Client(intents=discord.Intents.default())

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith("!hermes "):
        query = message.content[8:]
        agent = AIAgent(
            model="anthropic/claude-sonnet-4",
            quiet_mode=True,
            skip_context_files=True,
            skip_memory=True,
            platform="discord",
        )
        response = agent.chat(query)
        await message.channel.send(response[:2000])

client.run("YOUR_DISCORD_TOKEN")

CI/CD Pipeline Step

Python19 سطرًا
#!/usr/bin/env python3
"""CI step: auto-review a PR diff."""

from run_agent import AIAgent

diff = subprocess.check_output(["git", "diff", "main...HEAD"]).decode()

agent = AIAgent(
    model="anthropic/claude-sonnet-4",
    quiet_mode=True,
    skip_context_files=True,
    skip_memory=True,
    disabled_toolsets=["terminal", "browser"],
)

review = agent.chat(
    f"Review this PR diff for bugs, security issues, and style problems:\n\n{diff}"
)
print(review)

---

Key Constructor Parameters

جدول مرجعي. لا تقرأه كله، ابحث عن السطر الذي يخصّك فقط.

ParameterTypeDefaultDescription
modelstr""Model in OpenRouter format (defaults to empty; resolved from your hermes config at runtime)
quiet_modeboolFalseSuppress CLI output
enabled_toolsetsList[str]NoneWhitelist specific toolsets
disabled_toolsetsList[str]NoneBlacklist specific toolsets
save_trajectoriesboolFalseSave conversations to JSONL
ephemeral_system_promptstrNoneCustom system prompt (not saved to trajectories)
max_iterationsint500Max tool-calling iterations per conversation
skip_context_filesboolFalseSkip loading AGENTS.md files
skip_memoryboolFalseDisable persistent memory read/write
api_keystrNoneAPI key (falls back to env vars)
base_urlstrNoneCustom API endpoint URL
platformstrNonePlatform hint ("discord", "telegram", etc.)

---

Important Notes

فيه تحذير مهم. اقرأه قبل أن تنفّذ أي شيء من هذا القسم. نصّ التحذير من المصدر مذكور أسفل هذا الشرح.

اختبار الفهم

4 أسئلة إجاباتها كلها في هذه الصفحة.

كل خيار اسم حقيقي من توثيق Hermes. حتى الخيارات الخاطئة حقيقية، لكنها من صفحات أخرى.

1. في جدول هذا الدرس، ما «Type» المقابل لـ«skipcontextfiles»؟
2. أي متغير بيئة من التالي يظهر فعليًا في هذا الدرس؟
3. ما التحذير الذي يذكره المصدر في هذا الدرس؟
4. أي عنوان من التالي لا يظهر في هذا الدرس؟