claude openai agents
Commercial Agent Frameworks Integration
Last Updated: January 7, 2026
Overview
This guide covers integration of commercial AI agent frameworks with GitLab Ultimate:
- Claude Code - Anthropic's official CLI tool for Claude
- OpenAI Agents SDK - Lightweight multi-agent framework
- LangChain/LangGraph - Agent orchestration frameworks
- Integration Patterns - Best practices for GitLab integration
Claude Code
Version: Latest Repository: https://github.com/anthropics/claude-code Maintained by: Anthropic
What is Claude Code?
Claude Code is Anthropic's official CLI tool that provides:
- Interactive CLI: Chat with Claude from terminal
- File Operations: Read, write, edit files with AI assistance
- Tool Integration: Extensible tool system (MCP protocol)
- Git Integration: Commit messages, code review, PR creation
- GitLab CI/CD: Beta integration for pipeline execution
Installation
# Install via npm npm install -g @anthropic/claude-code # Or via pip pip install claude-code # Verify installation claude --version
Configuration
Setup API Key:
# Set Anthropic API key export ANTHROPIC_API_KEY='your-api-key-here' # Or configure via CLI claude configure --api-key your-api-key-here
Project Configuration (.claude/config.json):
{ "model": "claude-sonnet-4.5", "max_tokens": 8192, "temperature": 0.2, "tools": { "enabled": ["read", "write", "edit", "bash", "grep"], "disabled": [] }, "git": { "auto_commit": false, "commit_prefix": "feat: ", "branch_strategy": "feature" }, "gitlab": { "enabled": true, "instance_url": "https://gitlab.com", "project_id": 12345, "auto_create_mr": false } }
Claude Code + GitLab CI/CD
Beta Feature: Run Claude Code in CI/CD Pipelines
# .gitlab-ci.yml claude_code_review: stage: test image: node:18 before_script: - npm install -g @anthropic/claude-code script: # Run Claude Code review - | claude chat --prompt "Review this MR for: - Security vulnerabilities - Code quality issues - Best practices violations Provide specific recommendations for each file." \ --context merge_request \ --mr-iid $CI_MERGE_REQUEST_IID \ --output review.json # Post results to MR - | glab mr note $CI_MERGE_REQUEST_IID \ --message "$(cat review.json | jq -r '.summary')" artifacts: reports: codequality: review.json rules: - if: $CI_MERGE_REQUEST_ID
Claude Code MCP Servers
Install MCP Servers for Enhanced Capabilities:
# Install GitLab MCP server npx @modelcontextprotocol/create-server gitlab # Configure in Claude Code cat > ~/.claude/mcp-config.json <<EOF { "mcpServers": { "gitlab": { "command": "node", "args": ["~/.mcp/servers/gitlab/index.js"], "env": { "GITLAB_TOKEN": "${GITLAB_TOKEN}", "GITLAB_URL": "https://gitlab.com" } }, "sentry": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-sentry"], "env": { "SENTRY_AUTH_TOKEN": "${SENTRY_AUTH_TOKEN}" } } } } EOF
Use MCP Tools in Claude Code:
# Claude can now use GitLab tools claude chat --prompt "Create an issue in project 12345 titled 'Fix auth bug'" # Claude executes via MCP: # 1. Calls gitlab_create_issue tool # 2. Returns issue URL
GitLab Integration Patterns
1. Automated Code Review:
#!/bin/bash # .gitlab/scripts/claude-review.sh # Get MR diff MR_DIFF=$(glab mr diff $CI_MERGE_REQUEST_IID) # Run Claude Code review claude chat --prompt " Review this code diff: $MR_DIFF Provide: 1. Security concerns (if any) 2. Code quality issues 3. Suggested improvements 4. Overall assessment " --output json > review.json # Parse and post results SECURITY=$(jq -r '.security_concerns' review.json) QUALITY=$(jq -r '.quality_issues' review.json) SUGGESTIONS=$(jq -r '.suggestions' review.json) # Post to MR glab mr note $CI_MERGE_REQUEST_IID --message " ## AI Code Review ### Security $SECURITY ### Quality $QUALITY ### Suggestions $SUGGESTIONS "
2. Commit Message Generation:
# .git/hooks/prepare-commit-msg #!/bin/bash # Get staged diff DIFF=$(git diff --cached) # Generate commit message with Claude COMMIT_MSG=$(claude chat --prompt " Generate a conventional commit message for: $DIFF Format: <type>: <description> " --output text) # Write to commit message file echo "$COMMIT_MSG" > "$1"
3. PR Description Generation:
# Generate PR description generate_pr_description() { BRANCH=$(git branch --show-current) DIFF=$(git diff main...$BRANCH) COMMITS=$(git log main...$BRANCH --oneline) claude chat --prompt " Generate a comprehensive PR description for: Branch: $BRANCH Commits: $COMMITS Diff Summary: $DIFF Include: - Summary of changes - Testing done - Breaking changes (if any) - Related issues " --output markdown } # Create MR with generated description DESCRIPTION=$(generate_pr_description) glab mr create \ --title "$(git log -1 --format=%s)" \ --description "$DESCRIPTION"
Claude Code Custom Tools
Create Custom Tool for GitLab:
// ~/.claude/tools/gitlab-tools.ts import { Tool } from '@anthropic/claude-code'; import { Gitlab } from '@gitbeaker/node'; export const gitlabTools: Tool[] = [ { name: 'gitlab_create_issue', description: 'Create a new GitLab issue', input_schema: { type: 'object', properties: { project_id: { type: 'number' }, title: { type: 'string' }, description: { type: 'string' }, labels: { type: 'array', items: { type: 'string' } } }, required: ['project_id', 'title'] }, async execute(input) { const gitlab = new Gitlab({ token: process.env.GITLAB_TOKEN }); const issue = await gitlab.Issues.create( input.project_id, { title: input.title, description: input.description, labels: input.labels?.join(',') } ); return { issue_iid: issue.iid, url: issue.web_url }; } }, { name: 'gitlab_trigger_pipeline', description: 'Trigger a GitLab CI/CD pipeline', input_schema: { type: 'object', properties: { project_id: { type: 'number' }, ref: { type: 'string' }, variables: { type: 'object' } }, required: ['project_id', 'ref'] }, async execute(input) { const gitlab = new Gitlab({ token: process.env.GITLAB_TOKEN }); const pipeline = await gitlab.Pipelines.create( input.project_id, input.ref, { variables: input.variables } ); return { pipeline_id: pipeline.id, url: pipeline.web_url, status: pipeline.status }; } } ];
Register Custom Tools:
// ~/.claude/config.ts import { ClaudeCode } from '@anthropic/claude-code'; import { gitlabTools } from './tools/gitlab-tools'; const claude = new ClaudeCode({ apiKey: process.env.ANTHROPIC_API_KEY, tools: [ ...ClaudeCode.defaultTools, ...gitlabTools ] }); export default claude;
OpenAI Agents SDK
Version: Latest Repository: https://github.com/openai/openai-agents-sdk Maintained by: OpenAI
What is OpenAI Agents SDK?
A lightweight Python framework for building multi-agent systems:
- Structured Outputs: Pydantic models for type-safe responses
- Multi-Agent: Agent-to-agent communication
- Tool Integration: Function calling
- Streaming: Real-time responses
- Error Handling: Robust retry mechanisms
Installation
# Install OpenAI Agents SDK pip install openai-agents # Install GitLab integration pip install python-gitlab openai-agents-gitlab
Basic Agent Setup
# agents/code_reviewer.py from openai_agents import Agent from pydantic import BaseModel from typing import List class CodeIssue(BaseModel): file: str line: int severity: str issue: str recommendation: str class ReviewResult(BaseModel): summary: str issues: List[CodeIssue] approval_status: str code_reviewer = Agent( model="gpt-4-turbo", system_prompt=""" You are an expert code reviewer. Analyze code for security, quality, and best practices. """, response_format=ReviewResult, tools=[ "read_file", "git_diff", "sast_scan" ] ) # Execute review result = code_reviewer.run( prompt="Review MR !123 in project 456", context={ "project_id": 456, "mr_iid": 123 } ) print(f"Summary: {result.summary}") print(f"Issues found: {len(result.issues)}") print(f"Status: {result.approval_status}")
Multi-Agent System
# agents/multi_agent_system.py from openai_agents import Agent, AgentOrchestrator # Define specialized agents planner = Agent( name="planner", model="gpt-4-turbo", system_prompt="Break down requirements into tasks" ) implementer = Agent( name="implementer", model="gpt-4-turbo", system_prompt="Generate code based on plan" ) reviewer = Agent( name="reviewer", model="gpt-4-turbo", system_prompt="Review code for quality and security" ) # Create orchestrator orchestrator = AgentOrchestrator( agents=[planner, implementer, reviewer], workflow=[ {"agent": "planner", "output_to": "implementer"}, {"agent": "implementer", "output_to": "reviewer"}, {"agent": "reviewer"} ] ) # Execute workflow result = orchestrator.run( initial_prompt="Implement OAuth2 authentication", context={"language": "Python", "framework": "FastAPI"} )
GitLab Integration
GitLab Tools for OpenAI Agents:
# tools/gitlab_tools.py from openai_agents import Tool import gitlab class GitLabTools: def __init__(self, token: str, url: str = "https://gitlab.com"): self.gl = gitlab.Gitlab(url, private_token=token) @Tool( name="gitlab_get_mr", description="Get merge request details" ) def get_mr(self, project_id: int, mr_iid: int): project = self.gl.projects.get(project_id) mr = project.mergerequests.get(mr_iid) return { "title": mr.title, "description": mr.description, "changes": mr.changes(), "source_branch": mr.source_branch, "target_branch": mr.target_branch, } @Tool( name="gitlab_comment_mr", description="Add comment to merge request" ) def comment_mr(self, project_id: int, mr_iid: int, comment: str): project = self.gl.projects.get(project_id) mr = project.mergerequests.get(mr_iid) note = mr.notes.create({"body": comment}) return {"note_id": note.id} @Tool( name="gitlab_create_issue", description="Create a new issue" ) def create_issue(self, project_id: int, title: str, description: str, labels: List[str]): project = self.gl.projects.get(project_id) issue = project.issues.create({ "title": title, "description": description, "labels": labels }) return {"iid": issue.iid, "url": issue.web_url} @Tool( name="gitlab_trigger_pipeline", description="Trigger CI/CD pipeline" ) def trigger_pipeline(self, project_id: int, ref: str, variables: dict): project = self.gl.projects.get(project_id) pipeline = project.pipelines.create({ "ref": ref, "variables": [{"key": k, "value": v} for k, v in variables.items()] }) return {"pipeline_id": pipeline.id, "status": pipeline.status}
Use GitLab Tools in Agent:
# agents/gitlab_agent.py from openai_agents import Agent from tools.gitlab_tools import GitLabTools gitlab_tools = GitLabTools(token=os.getenv("GITLAB_TOKEN")) agent = Agent( name="gitlab_assistant", model="gpt-4-turbo", system_prompt="You help manage GitLab projects", tools=[ gitlab_tools.get_mr, gitlab_tools.comment_mr, gitlab_tools.create_issue, gitlab_tools.trigger_pipeline ] ) # Use agent result = agent.run( "Review MR !45 in project 789 and create follow-up issues for any problems found" )
CI/CD Integration
# .gitlab-ci.yml openai_agent_review: stage: test image: python:3.11 before_script: - pip install openai-agents python-gitlab script: - | python -c " from agents.code_reviewer import code_reviewer import os result = code_reviewer.run( prompt='Review this MR', context={ 'project_id': int(os.getenv('CI_PROJECT_ID')), 'mr_iid': int(os.getenv('CI_MERGE_REQUEST_IID')) } ) # Post results print(f'Review Summary: {result.summary}') print(f'Issues: {len(result.issues)}') # Fail if critical issues if any(i.severity == 'critical' for i in result.issues): exit(1) " rules: - if: $CI_MERGE_REQUEST_ID
Agent Persistence
Save/Load Agent State:
# agents/persistent_agent.py from openai_agents import Agent, AgentState import json # Create agent agent = Agent( name="stateful_agent", model="gpt-4-turbo" ) # Execute with state tracking result = agent.run( "Analyze project health", save_state=True ) # Save state to file with open("agent_state.json", "w") as f: json.dump(agent.get_state(), f) # Load state later with open("agent_state.json", "r") as f: state = json.load(f) agent.load_state(state) # Continue from where it left off result = agent.run("Continue analysis")
LangChain/LangGraph
LangChain: Framework for LLM applications LangGraph: Graph-based agent orchestration
Installation
pip install langchain langchain-anthropic langchain-openai langgraph
LangChain GitLab Agent
# agents/langchain_gitlab.py from langchain.agents import initialize_agent, Tool from langchain_anthropic import ChatAnthropic from langchain.memory import ConversationBufferMemory import gitlab gl = gitlab.Gitlab("https://gitlab.com", private_token=os.getenv("GITLAB_TOKEN")) # Define tools tools = [ Tool( name="GetMergeRequest", func=lambda x: gl.projects.get(x.split(',')[0]).mergerequests.get(int(x.split(',')[1])).attributes, description="Get MR details. Input: 'project_id,mr_iid'" ), Tool( name="CreateIssue", func=lambda x: gl.projects.get(json.loads(x)['project_id']).issues.create(json.loads(x)), description="Create issue. Input: JSON with project_id, title, description" ), Tool( name="TriggerPipeline", func=lambda x: gl.projects.get(json.loads(x)['project_id']).pipelines.create(json.loads(x)), description="Trigger pipeline. Input: JSON with project_id, ref" ) ] # Create agent llm = ChatAnthropic(model="claude-sonnet-4.5") memory = ConversationBufferMemory(memory_key="chat_history") agent = initialize_agent( tools=tools, llm=llm, agent="conversational-react-description", memory=memory, verbose=True ) # Use agent response = agent.run("Get MR !45 from project 123 and analyze it")
LangGraph Multi-Agent Workflow
# agents/langgraph_workflow.py from langgraph.graph import StateGraph, END from typing import TypedDict, Annotated import operator class AgentState(TypedDict): messages: Annotated[list, operator.add] task: str plan: str code: str review: str approved: bool # Define agent nodes def planner_node(state: AgentState): llm = ChatAnthropic(model="claude-sonnet-4.5") plan = llm.invoke([ {"role": "system", "content": "Create implementation plan"}, {"role": "user", "content": state["task"]} ]) return {"plan": plan.content} def coder_node(state: AgentState): llm = ChatAnthropic(model="claude-sonnet-4.5") code = llm.invoke([ {"role": "system", "content": "Generate code from plan"}, {"role": "user", "content": state["plan"]} ]) return {"code": code.content} def reviewer_node(state: AgentState): llm = ChatAnthropic(model="claude-sonnet-4.5") review = llm.invoke([ {"role": "system", "content": "Review code quality and security"}, {"role": "user", "content": state["code"]} ]) # Determine approval approved = "APPROVED" in review.content return {"review": review.content, "approved": approved} # Build graph workflow = StateGraph(AgentState) # Add nodes workflow.add_node("planner", planner_node) workflow.add_node("coder", coder_node) workflow.add_node("reviewer", reviewer_node) # Add edges workflow.set_entry_point("planner") workflow.add_edge("planner", "coder") workflow.add_edge("coder", "reviewer") # Conditional edge based on review workflow.add_conditional_edges( "reviewer", lambda state: "end" if state["approved"] else "coder", { "end": END, "coder": "coder" # Loop back for revisions } ) # Compile app = workflow.compile() # Execute result = app.invoke({ "task": "Implement user authentication with JWT", "messages": [] }) print(f"Plan: {result['plan']}") print(f"Code: {result['code']}") print(f"Review: {result['review']}") print(f"Approved: {result['approved']}")
LangGraph + GitLab CI/CD
# .gitlab-ci.yml langgraph_workflow: stage: build image: python:3.11 before_script: - pip install langchain langchain-anthropic langgraph python-gitlab script: - | python agents/langgraph_workflow.py \ --task "$(cat $CI_MERGE_REQUEST_DESCRIPTION)" \ --project-id $CI_PROJECT_ID \ --output generated_code/ # Commit generated code - git config user.email "agent@gitlab.com" - git config user.name "LangGraph Agent" - git add generated_code/ - git commit -m "feat: generated by LangGraph workflow" - git push origin HEAD:$CI_COMMIT_REF_NAME rules: - if: $CI_MERGE_REQUEST_ID changes: - specifications/**/*
Integration Best Practices
1. Authentication & Security
Use OIDC Tokens in CI/CD:
# .gitlab-ci.yml agent_execution: id_tokens: GITLAB_OIDC_TOKEN: aud: https://gitlab.com script: - export GITLAB_TOKEN=$GITLAB_OIDC_TOKEN - python agents/run.py
Secrets Management:
# Store API keys in GitLab CI/CD variables # Settings CI/CD Variables # Access in agents claude chat --env-var ANTHROPIC_API_KEY openai-agents run --env-var OPENAI_API_KEY
2. Cost Optimization
Token Usage Monitoring:
# agents/cost_tracker.py import openai from functools import wraps def track_costs(func): @wraps(func) def wrapper(*args, **kwargs): # Track token usage openai.api_requestor._global_request_context = { "metrics_enabled": True } result = func(*args, **kwargs) # Log usage usage = result.get("usage", {}) cost = calculate_cost(usage) # Store in GitLab gl.projects.get(PROJECT_ID).variables.create({ "key": f"AGENT_COST_{datetime.now().date()}", "value": str(cost) }) return result return wrapper
3. Error Handling
Retry Logic:
# agents/utils/retry.py import tenacity @tenacity.retry( wait=tenacity.wait_exponential(multiplier=1, min=2, max=10), stop=tenacity.stop_after_attempt(3), retry=tenacity.retry_if_exception_type(RateLimitError) ) def call_agent(agent, prompt): return agent.run(prompt)
4. Observability
OpenTelemetry Integration:
# agents/observability.py from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter # Setup tracing trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) otlp_exporter = OTLPSpanExporter( endpoint="https://otel-collector.gitlab.com" ) span_processor = BatchSpanProcessor(otlp_exporter) trace.get_tracer_provider().add_span_processor(span_processor) # Trace agent execution with tracer.start_as_current_span("agent_execution"): result = agent.run(prompt)
5. Testing
Agent Unit Tests:
# tests/test_agents.py import pytest from agents.code_reviewer import code_reviewer def test_code_review(): # Mock GitLab API with mock.patch("gitlab.Gitlab") as mock_gl: mock_gl.return_value.projects.get.return_value.mergerequests.get.return_value.changes.return_value = { "files": [ {"path": "src/app.py", "diff": "..."} ] } # Run agent result = code_reviewer.run( prompt="Review MR", context={"project_id": 123, "mr_iid": 45} ) # Assert assert result.approval_status in ["approved", "changes_requested", "blocked"] assert len(result.issues) >= 0
Complete Integration Example
Scenario: Multi-Framework Agent Pipeline
# .gitlab-ci.yml stages: - planning - implementation - review - deploy # Stage 1: Claude Code for planning planning: stage: planning image: node:18 script: - npm install -g @anthropic/claude-code - | claude chat --prompt "Create implementation plan for: $(cat requirements.md)" --output plan.json artifacts: paths: - plan.json # Stage 2: OpenAI Agents for implementation implementation: stage: implementation image: python:3.11 needs: [planning] script: - pip install openai-agents - | python -c " from agents.implementer import implementer import json with open('plan.json') as f: plan = json.load(f) result = implementer.run(plan['tasks']) with open('generated_code.zip', 'wb') as f: f.write(result.code_archive) " artifacts: paths: - generated_code.zip # Stage 3: LangChain for review review: stage: review image: python:3.11 needs: [implementation] script: - pip install langchain langchain-anthropic - | python -c " from agents.langchain_reviewer import reviewer import zipfile with zipfile.ZipFile('generated_code.zip') as z: z.extractall('code/') result = reviewer.run('Review code in code/ directory') with open('review_report.md', 'w') as f: f.write(result) " artifacts: reports: codequality: review_report.json # Stage 4: Deploy if approved deploy: stage: deploy needs: [review] script: - ./deploy.sh when: manual
Resources
Documentation
- Claude Code: https://docs.anthropic.com/claude-code
- OpenAI Agents SDK: https://platform.openai.com/docs/agents
- LangChain: https://docs.langchain.com
- LangGraph: https://langchain-ai.github.io/langgraph/
Examples & Templates
- Claude Code Examples: https://github.com/anthropics/claude-code-examples
- OpenAI Agents Cookbook: https://cookbook.openai.com/examples/agents
- LangChain Templates: https://github.com/langchain-ai/langchain/tree/master/templates
Community
- Claude Discord: https://discord.gg/A9rVHm4MXG
- OpenAI Forum: https://community.openai.com
- LangChain Discord: https://discord.gg/A9rVHm4MXG
Next Steps
- Setup Claude Code: Install and configure for local development
- Try OpenAI Agents SDK: Build first agent with GitLab tools
- Explore LangGraph: Create multi-agent workflow
- Integrate with CI/CD: Add agents to GitLab pipelines
- Monitor Costs: Track token usage and optimize
Related Documentation: