Runoob Tutorial ArchiveEnglish

AI Agent Production Deployment and Engineering

AI Agent Production Deployment and Engineering

Production deployment involves multiple aspects such as reliability, scalability, and cost control.

Engineering practices ensure the system runs stably and is easy to maintain.


Production Deployment Architecture

The production environment has higher requirements for the system.

Multiple aspects such as reliability, scalability, and monitoring alerts need to be considered.

Deployment Mode

Single-node deployment

Suitable for development and testing environments.

Simple and easy to deploy, but cannot handle production-level traffic.

Distributed deployment

Suitable for production environments, requiring consideration of multiple aspects.

Load balancing: Distributes requests to multiple instances.

Service discovery: Dynamically manages the instance list.

State management: Handles distributed state consistency issues.

Fault tolerance: Single point of failure does not affect overall service.

Containerized deployment

Dockerfile example

Based on Python 3.11 image

FROM python:3.11-slim

Set working directory

WORKDIR /app

Install dependencies

COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt

Copy application code

COPY . .

Create a non-root user (for security)

RUN useradd -m appuser && chown -R appuser:appuser /app

USER appuser

Expose port

EXPOSE 8000

Startup command

CMD ["python", "agent.py"]

Kubernetes deployment

Kubernetes Deployment configuration

span style="color: green;">

apiVersion

:

apps/v1

kind

:

Deployment

metadata

:

name

:

ai-agent

labels

:

app

:

ai-agent

spec

:

 

Number of replicas

replicas

:

3

selector

:

matchLabels

:

app

:

ai-agent

template

:

metadata

:

labels

:

app

:

ai-agent

spec

:

containers

:

- name

:

agent

image

:

your-registry/ai-agent:latest

ports

:

- containerPort

:

8000

       

Resource limits

resources

:

limits

:

memory

:

"2Gi"

cpu

:

"1"

requests

:

memory

:

"1Gi"

cpu

:

"0.5"

       

Health check

livenessProbe

:

httpGet

:

path

:

/health

port

:

8000

initialDelaySeconds

:

10

periodSeconds

:

30

readinessProbe

:

httpGet

:

path

:

/ready

port

:

8000

initialDelaySeconds

:

5

periodSeconds

:

10


apiVersion

:

v1

kind

:

Service

metadata

:

name

:

ai-agent-service

spec

:

selector

:

    app

:

ai-agent

  ports

:

  - port

:

80

targetPort

:

8000

type

:

LoadBalancer


Cost control

The cost of the Agent system mainly comes from LLM API calls.

Cost optimization is an important topic for production deployment.

Token optimization strategies

Prompt compression: streamline prompts and reduce unnecessary text.

Context truncation: retain only key context content.

Response caching: cache responses for identical or similar queries.

Code implementation

Cost optimization Agent implementation

import

hashlib

import

json

from

functools

import

lru_cache

class

CostOptimizedAgent:

   

"""
Cost-optimized Agent
Reduces API call costs through caching and compression
"""

   

   

def

init

(

self

,

base_agent

,

cache

,

embedder

=

None

)

:

       

Basic Agent

       

self

.

base_agent

=

base_agent

       

Cache Storage

       

self

.

cache

=

cache

       

Embedder (for similarity cache matching)

       

self

.

embedder

=

embedder

   

   

def

process

(

self

,

request

)

:

       

"""
Process requests, including cost optimization logic
"""

       

Generate request fingerprint

request_fingerprint

=

self

.

generate_fingerprint

(

request

)

       

       

Check precise cache

cached_result

=

self

.

cache

.

get

(

request_fingerprint

)

       

if

cached_result:

           

return

{

                **cached_result

,

               

"from_cache"

:

True

           

}

       

       

If there is an embedder, check the semantic similarity cache

       

if

self

.

embedder

:

similar

=

self

.

find_similar_cached

(

request

)

           

if

similar:

               

return

{

**similar

,

                   

"from_cache"

:

True

,

                   

"similar_to"

: similar.

get

(

"request_id"

)

               

}

       

       

Execute request

result

=

self

.

base_agent

.

process

(

request

)

       

       

Cache results

       

self

.

cache

.

set

(

request_fingerprint

,

result

,

ttl

=

3600

 

1 hour expiration

       

)

       

       

return

{

**result

,

           

"from_cache"

:

False

       

}

   

   

def

generate_fingerprint

(

self

,

request

)

:

       

"""
Generate request fingerprint
Used for precise cache matching
"""

content

=

json.

dumps

(

request

,

sort_keys

=

True

)

       

return

hashlib.

sha256

(

content.

encode

(

)

)

.

hexdigest

(

)

   

   

def

find_similar_cached

(

self

,

request

,

threshold

=

0.95

)

:

       

"""
Find semantically similar cached results
Cosine similarity using embedding vectors
"""

       

if

not

self

.

embedder

:

           

return

None

       

       

Vectorize the request

request_vector

=

self

.

embedder

.

embed

(

[

str

(

request

)

]

)

[

0

]

       

       

Search for similar requests in the cache

best_match

=

None

best_similarity

=

0

       

       

for

cached

in

self

.

cache

.

get_all

(

)

:

cached_vector

=

cached

[

"vector"

]

similarity

=

cosine_similarity

(

request_vector

,

cached_vector

)

           

           

if

similarity

best_similarity

and

similarity

=

threshold:

best_similarity

=

similarity

best_match

=

cached

       

       

return

best_match

class

ResponseCache:

   

"""
Response cache
A simple in-memory cache implementation
Redis can be used in production environments
"""

   

   

def

init

(

self

)

:

       

self

.

cache

=

{

}

       

self

.

timestamps

=

{

}

   

   

def

get

(

self

,

key

)

:

       

Get cache

       

if

key

in

self

.

cache

:

           

Check if expired

           

if

self

.

is_expired

(

key

)

:

               

self

.

delete

(

key

)

               

return

None

           

return

self

.

cache

[

key

]

       

return

None

   

   

def

set

(

self

,

key

,

value

,

ttl

=

3600

)

:

       

"""Set cache"""

       

self

.

cache

[

key

]

=

value

       

self

.

timestamps

[

key

]

=

time

.

time

(

)

   

   

def

delete

(

self

,

key

)

:

       

"""Delete cache"""

       

if

key

in

self

.

cache

:

           

del

self

.

cache

[

key

]

       

if

key

in

self

.

timestamps

:

           

del

self

.

timestamps

[

key

]

   

   

def

is_expired

(

self

,

key

)

:

       

"""Check if expired"""

       

if

key

not

in

self

.

timestamps

:

           

return

True

       

return

time

.

time

(

)

self

.

timestamps

[

key

]

   

   

def

get_all

(

self

)

:

       

"""Get all cached items"""

       

return

list

(

self

.

cache

.

values

(

)

)

def

cosine_similarity

(

vec1

,

vec2

)

:

   

"""Calculate cosine similarity"""

dot_product

=

sum

(

a * b

for

a

,

b

in

zip

(

vec1

,

vec2

)

)

    norm1

=

math

.

sqrt

(

sum

(

a * a

for

a

in

vec1

)

)

    norm2

=

math

.

sqrt

(

sum

(

b * b

for

b

in

vec2

)

)

   

return

dot_product /

(

norm1 * norm2

)


Streaming and Asynchronous

Streaming Response

Streaming responses reduce waiting time and improve user experience.

You don't have to wait for the complete response; generated content can be displayed incrementally.

Code Implementation

Streaming Response Agent

import

asyncio

class

StreamingAgent:

   

"""
Agent that supports streaming responses
Returns as it is generated, reducing waiting time
"""

   

   

def

init

(

self

,

llm

)

:

       

self

.

llm

=

llm

   

async

def

stream_generate

(

self

,

prompt

)

:

       

"""
Stream response generation
Using async generator mode
:yield: generated text segments
"""

       

Start asynchronous generation task

async

for

chunk

in

self

.

llm

.

stream_generate

(

prompt

)

:

           

yield

chunk

   

async

def

process_stream

(

self

,

request

)

:

       

"""
Process streaming requests
Return an asynchronous generator
"""

prompt

=

self

.

build_prompt

(

request

)

       

       

return generator

async

def

generate

(

)

:

            async

for

chunk

in

self

.

stream_generate

(

prompt

)

:

               

yield

chunk

       

       

return

generate

(

)

Usage example

async

def

main

(

)

:

    agent

=

StreamingAgent

(

llm

)

   

   

Start streaming generation

async

for

token

in

agent.

stream_generate

(

"Explain quantum computing"

)

:

       

Print while generating

       

print

(

token

,

end

=

""

,

flush

=

True

)

   

print

(

)

 

Newline

Run

asyncio.

run

(

main

(

)

)

Asynchronous task queue

For long-running tasks, use the asynchronous queue for processing.

Returns immediately after the user submits the task, and executes asynchronously in the background.

Asynchronous task queue implementation

import

asyncio

from

queue

import

Queue

from

threading

import

Thread

import

uuid

class

AsyncAgent:

   

"""
Asynchronous Agent
Uses a task queue to handle long-running tasks
"""

   

   

def

init

(

self

,

agent

,

task_queue

)

:

       

Basic Agent

       

self

.

agent

=

agent

       

Task Queue

       

self

.

task_queue

=

task_queue

       

Result Storage

       

self

.

results

=

{

}

       

Start the background worker thread

       

self

.

worker_thread

=

Thread

(

target

=

self

.

process_queue

,

daemon

=

True

)

       

self

.

worker_thread

.

start

(

)

   

async

def

submit

(

self

,

task

)

:

       

"""
Submit task
Immediately return task ID
"""

       

Generate unique task ID

task_id

=

str

(

uuid.

uuid4

(

)

)

       

       

Add to queue

await

self

.

task_queue

.

enqueue

(

{

           

"id"

: task_id

,

           

"task"

: task

,

           

"status"

:

"pending"

,

           

"created_at"

:

time

.

time

(

)

       

}

)

       

       

return

task_id

   

async

def

get_result

(

self

,

task_id

)

:

       

"""
Get task results
Non-blocking
"""

       

if

task_id

in

self

.

results

:

           

return

self

.

results

[

task_id

]

       

       

Check task status

status

=

await

self

.

task_queue

.

get_status

(

task_id

)

       

       

if

status

is

None

:

           

return

None

 

Task does not exist

       

       

if

status

==

"pending"

or

status

==

"processing"

:

           

return

{

               

"status"

: status

,

               

"result"

:

None

           

}

       

       

return

None

   

   

def

process_queue

(

self

)

:

       

"""
Background worker thread
Takes tasks from the queue and executes them
"""

loop

=

asyncio.

new_event_loop

(

)

        asyncio.

set_event_loop

(

loop

)

       

       

while

True

:

task

=

loop.

run_until_complete

(

self

.

task_queue

.

dequeue

(

)

)

           

           

if

task:

               

Update status to processing

loop.

run_until_complete

(

                   

self

.

task_queue

.

update_status

(

task

[

"id"

]

,

"processing"

)

               

)

               

               

try

:

                   

Execute task

result

=

self

.

agent

.

process

(

task

[

"task"

]

)

                   

                   

Save results

                   

self

.

results

[

task

[

"id"

]

]

=

{

                       

"status"

:

"completed"

,

                       

"result"

: result

,

                       

"completed_at"

:

time

.

time

(

)

                   

}

                   

loop.

run_until_complete

(

                       

self

.

task_queue

.

update_status

(

task

[

"id"

]

,

"completed"

)

                   

)

               

except

Exception

as

e:

                   

self

.

results

[

task

[

"id"

]

]

=

{

                       

"status"

:

"failed"

,

                       

"error"

:

str

(

e

)

                   

}

                   

loop.

run_until_complete

(

                       

self

.

task_queue

.

update_status

(

task

[

"id"

]

,

"failed"

)

                   

)

class

TaskQueue:

   

"""Simple task queue implementation"""

   

   

def

init

(

self

)

:

       

self

.

queue

=

Queue

(

)

       

self

.

statuses

=

{

}

   

async

def

enqueue

(

self

,

task

)

:

       

"""Add task to queue"""

       

self

.

queue

.

put

(

task

)

       

self

.

statuses

[

task

[

"id"

]

]

=

"pending"

   

async

def

dequeue

(

self

)

:

       

"""Get out a task"""

       

if

not

self

.

queue

.

empty

(

)

:

           

return

self

.

queue

.

get

(

)

       

return

None

   

async

def

get_status

(

self

,

task_id

)

:

       

"""Get task status"""

       

return

self

.

statuses

.

get

(

task_id

)

   

async

def

update_status

(

self

,

task_id

,

status

)

:

       

Update task status

       

self

.

statuses

[

task_id

]

=

status


Microservice design

Decompose the Agent system into multiple independent services to improve maintainability and scalability.

Service division

Service Responsibility
API Gateway Unified entry point, authentication, rate limiting, routing forwarding
Agent Service Core logic, inference planning
Tool Service External API integration, tool calling
Storage Service Knowledge base, state management, caching
Monitoring Service Log collection, metric monitoring, alerting

Inter-service communication

Synchronous communication: HTTP/gRPC, used for real-time request-response.

Asynchronous communication: Message queue, used for long-running operations and event notifications.


Chapter Summary

This chapter introduces key practices for production deployment and engineering.

Production deployment architecture: Scaling from single-machine to distributed.

Containerized deployment using Docker and Kubernetes.

Cost control by reducing costs through caching and Token optimization.

Streaming and asynchronous to improve user experience and system throughput.

Microservice design to improve system maintainability and scalability.

Production deployment requires comprehensive consideration of reliability, performance, cost, and other aspects.

It is recommended to start small and gradually increase complexity.