Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,8 @@ OPENAI_API_KEY=your_openai_api_key_here

# Optional: Custom MCP server paths (if different from default)
# INVOPOP_MCP_PATH=/custom/path/to/invopop/src/index.js
# GOBL_MCP_PATH=/custom/path/to/gobl/src/index.js
# GOBL_MCP_PATH=/custom/path/to/gobl/src/index.js

# Opik api key
OPIK_API_KEY=your_opik_api_key_here
OPIK_WORKSPACE=opik_workspace
43 changes: 41 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,12 @@ An AI-powered agent library for answering questions about Invopop and GOBL docum

3. **Set up environment variables**:
```bash
export OPENAI_API_KEY=your_openai_api_key
# Copy the example environment file and edit it with your values
cp .env.example .env

# Edit .env file with your API keys
# Then source it or restart your terminal
source .env
```

4. **Run the CLI**:
Expand Down Expand Up @@ -125,6 +130,9 @@ llm:
model: "gpt-4.1-2025-04-14"
temperature: 0.1

opik:
project_name: "invopop-expert"

# MCP Server Configuration
mcp:
servers:
Expand All @@ -146,10 +154,38 @@ chat:

### Environment Variables

You can configure the application using environment variables. Copy the example file and customize it:

```bash
cp .env.example .env
# Edit .env with your values, then source it:
source .env
```

**Available Variables:**
- `OPENAI_API_KEY` (required): Your OpenAI API key
- `OPIK_API_KEY` (optional): Your Opik API key for conversation tracing
- `OPIK_WORKSPACE` (optional): Your Opik workspace name for conversation tracing
- `INVOPOP_MCP_PATH` (optional): Custom path to Invopop MCP server
- `GOBL_MCP_PATH` (optional): Custom path to GOBL MCP server

### Opik Tracing Setup

Invopop Expert supports optional conversation tracing with [Opik](https://opik.vercel.app/) for monitoring and analytics. You have two setup options:

**Option 1: Environment Variables**
```bash
export OPIK_API_KEY=your_opik_api_key
export OPIK_WORKSPACE=your_opik_workspace
```

**Option 2: Interactive Configuration**
```bash
opik configure
```

If neither option is configured, the agent will run normally but without tracing capabilities.

## Integration Examples

### Building a Web API
Expand Down Expand Up @@ -222,7 +258,10 @@ src/expert/

4. **Set environment variables**:
```bash
export OPENAI_API_KEY=your_api_key
# Copy and configure environment variables
cp .env.example .env
# Edit .env file with your API keys, then source it
source .env
```

5. **Run the CLI**:
Expand Down
3 changes: 3 additions & 0 deletions config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ llm:
model: "gpt-4.1-2025-04-14"
temperature: 0.1

opik:
project_name: "invopop-expert"

mcp:
servers:
deepwiki:
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ dependencies = [
"langchain-openai>=0.3.18",
"langgraph>=0.4.7",
"langgraph-prebuilt>=0.2.2",
"opik>=1.7.36",
]

[project.optional-dependencies]
Expand Down
32 changes: 25 additions & 7 deletions src/expert/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

from datetime import datetime
from pathlib import Path
from typing import Any

from langchain_core.tools import StructuredTool
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.prebuilt import create_react_agent
from opik.integrations.langchain import OpikTracer

from .config import Config

Expand Down Expand Up @@ -91,13 +91,34 @@ async def setup(self):
prompt=self.system_prompt,
)

async def get_response(self, user_input: str, config: dict[str, Any]) -> str:
# Initialize Opik tracer if configured
if self.config.opik_api_key:
opik_config = self.config.opik_config
project_name = opik_config.get("project_name", "invopop-expert")

self.tracer = OpikTracer(
graph=self.agent.get_graph(xray=True), project_name=project_name
)
print(f"✅ Opik tracing enabled for project: {project_name}")
else:
self.tracer = None
print("⚠️ Opik tracing disabled - missing API key")

async def get_response(self, user_input: str, thread_id: str) -> str:
"""Get response from the agent for a given input."""
if not self.agent:
raise RuntimeError("Agent not initialized. Call setup() first.")

thread_config = {
"configurable": {"thread_id": thread_id},
}

# Add tracer callback if available
if self.tracer:
thread_config["callbacks"] = [self.tracer]

async for chunk in self.agent.astream(
{"messages": [{"role": "user", "content": user_input}]}, config
{"messages": [{"role": "user", "content": user_input}]}, thread_config
):
if "agent" in chunk:
for message in chunk["agent"]["messages"]:
Expand Down Expand Up @@ -137,8 +158,6 @@ async def chat_loop(self):
# Create a thread id based on the current date and time
thread_id = datetime.now().strftime("%Y%m%d%H%M%S")

thread_config = {"configurable": {"thread_id": thread_id}}

while True:
try:
# Get user input
Expand All @@ -160,13 +179,12 @@ async def chat_loop(self):
break
elif user_input.lower() in ["clear"]:
thread_id = datetime.now().strftime("%Y%m%d%H%M%S")
thread_config = {"configurable": {"thread_id": thread_id}}
print("\n🤖 Cleared thread")
continue

# Get and print agent response
print("\n🤖 Thinking...", flush=True)
response = await self.get_response(user_input, thread_config)
response = await self.get_response(user_input, thread_id)
print(f"\n🤖 Assistant: {response}")

except KeyboardInterrupt:
Expand Down
28 changes: 25 additions & 3 deletions src/expert/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,32 @@ def _validate_env_vars(self):
if not os.getenv("OPENAI_API_KEY"):
raise ValueError("OPENAI_API_KEY environment variable is required")

# Opik configuration - check if either env vars are set or opik is configured
opik_api_key = os.getenv("OPIK_API_KEY")

if not opik_api_key:
# Inform about Opik configuration options
print("ℹ️ Opik tracing is not configured.")
print(" This is optional but enables tracking of agent interactions.")
print(" To enable Opik tracing, you can:")
print(" 1. Set OPIK_API_KEY environment variable")
print(" 2. Run 'opik configure' to set up Opik configuration")

@property
def opik_api_key(self) -> str | None:
"""Get Opik API key."""
return os.getenv("OPIK_API_KEY")

@property
def openai_api_key(self) -> str:
"""Get OpenAI API key."""
return os.getenv("OPENAI_API_KEY")
def opik_config(self) -> dict[str, Any]:
"""Get Opik configuration."""
config = self.config.get("opik", {})

opik_project_name = os.getenv("OPIK_PROJECT_NAME")
if opik_project_name:
config["project_name"] = opik_project_name

return config

@property
def llm_config(self) -> dict[str, Any]:
Expand Down
Loading
Loading